popup.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. /*!
  2. * # Fomantic-UI - Popup
  3. * http://github.com/fomantic/Fomantic-UI/
  4. *
  5. *
  6. * Released under the MIT license
  7. * http://opensource.org/licenses/MIT
  8. *
  9. */
  10. ;(function ($, window, document, undefined) {
  11. 'use strict';
  12. $.isFunction = $.isFunction || function(obj) {
  13. return typeof obj === "function" && typeof obj.nodeType !== "number";
  14. };
  15. window = (typeof window != 'undefined' && window.Math == Math)
  16. ? window
  17. : (typeof self != 'undefined' && self.Math == Math)
  18. ? self
  19. : Function('return this')()
  20. ;
  21. $.fn.popup = function(parameters) {
  22. var
  23. $allModules = $(this),
  24. $document = $(document),
  25. $window = $(window),
  26. $body = $('body'),
  27. moduleSelector = $allModules.selector || '',
  28. clickEvent = ('ontouchstart' in document.documentElement)
  29. ? 'touchstart'
  30. : 'click',
  31. time = new Date().getTime(),
  32. performance = [],
  33. query = arguments[0],
  34. methodInvoked = (typeof query == 'string'),
  35. queryArguments = [].slice.call(arguments, 1),
  36. returnedValue
  37. ;
  38. $allModules
  39. .each(function() {
  40. var
  41. settings = ( $.isPlainObject(parameters) )
  42. ? $.extend(true, {}, $.fn.popup.settings, parameters)
  43. : $.extend({}, $.fn.popup.settings),
  44. selector = settings.selector,
  45. className = settings.className,
  46. error = settings.error,
  47. metadata = settings.metadata,
  48. namespace = settings.namespace,
  49. eventNamespace = '.' + settings.namespace,
  50. moduleNamespace = 'module-' + namespace,
  51. $module = $(this),
  52. $context = $(settings.context),
  53. $scrollContext = $(settings.scrollContext),
  54. $boundary = $(settings.boundary),
  55. $target = (settings.target)
  56. ? $(settings.target)
  57. : $module,
  58. $popup,
  59. $offsetParent,
  60. searchDepth = 0,
  61. triedPositions = false,
  62. openedWithTouch = false,
  63. element = this,
  64. instance = $module.data(moduleNamespace),
  65. documentObserver,
  66. elementNamespace,
  67. id,
  68. module
  69. ;
  70. module = {
  71. // binds events
  72. initialize: function() {
  73. module.debug('Initializing', $module);
  74. module.createID();
  75. module.bind.events();
  76. if(!module.exists() && settings.preserve) {
  77. module.create();
  78. }
  79. if(settings.observeChanges) {
  80. module.observeChanges();
  81. }
  82. module.instantiate();
  83. },
  84. instantiate: function() {
  85. module.verbose('Storing instance', module);
  86. instance = module;
  87. $module
  88. .data(moduleNamespace, instance)
  89. ;
  90. },
  91. observeChanges: function() {
  92. if('MutationObserver' in window) {
  93. documentObserver = new MutationObserver(module.event.documentChanged);
  94. documentObserver.observe(document, {
  95. childList : true,
  96. subtree : true
  97. });
  98. module.debug('Setting up mutation observer', documentObserver);
  99. }
  100. },
  101. refresh: function() {
  102. if(settings.popup) {
  103. $popup = $(settings.popup).eq(0);
  104. }
  105. else {
  106. if(settings.inline) {
  107. $popup = $target.nextAll(selector.popup).eq(0);
  108. settings.popup = $popup;
  109. }
  110. }
  111. if(settings.popup) {
  112. $popup.addClass(className.loading);
  113. $offsetParent = module.get.offsetParent();
  114. $popup.removeClass(className.loading);
  115. if(settings.movePopup && module.has.popup() && module.get.offsetParent($popup)[0] !== $offsetParent[0]) {
  116. module.debug('Moving popup to the same offset parent as target');
  117. $popup
  118. .detach()
  119. .appendTo($offsetParent)
  120. ;
  121. }
  122. }
  123. else {
  124. $offsetParent = (settings.inline)
  125. ? module.get.offsetParent($target)
  126. : module.has.popup()
  127. ? module.get.offsetParent($popup)
  128. : $body
  129. ;
  130. }
  131. if( $offsetParent.is('html') && $offsetParent[0] !== $body[0] ) {
  132. module.debug('Setting page as offset parent');
  133. $offsetParent = $body;
  134. }
  135. if( module.get.variation() ) {
  136. module.set.variation();
  137. }
  138. },
  139. reposition: function() {
  140. module.refresh();
  141. module.set.position();
  142. },
  143. destroy: function() {
  144. module.debug('Destroying previous module');
  145. if(documentObserver) {
  146. documentObserver.disconnect();
  147. }
  148. // remove element only if was created dynamically
  149. if($popup && !settings.preserve) {
  150. module.removePopup();
  151. }
  152. // clear all timeouts
  153. clearTimeout(module.hideTimer);
  154. clearTimeout(module.showTimer);
  155. // remove events
  156. module.unbind.close();
  157. module.unbind.events();
  158. $module
  159. .removeData(moduleNamespace)
  160. ;
  161. },
  162. event: {
  163. start: function(event) {
  164. var
  165. delay = ($.isPlainObject(settings.delay))
  166. ? settings.delay.show
  167. : settings.delay
  168. ;
  169. clearTimeout(module.hideTimer);
  170. if(!openedWithTouch || (openedWithTouch && settings.addTouchEvents) ) {
  171. module.showTimer = setTimeout(module.show, delay);
  172. }
  173. },
  174. end: function() {
  175. var
  176. delay = ($.isPlainObject(settings.delay))
  177. ? settings.delay.hide
  178. : settings.delay
  179. ;
  180. clearTimeout(module.showTimer);
  181. module.hideTimer = setTimeout(module.hide, delay);
  182. },
  183. touchstart: function(event) {
  184. openedWithTouch = true;
  185. if(settings.addTouchEvents) {
  186. module.show();
  187. }
  188. },
  189. resize: function() {
  190. if( module.is.visible() ) {
  191. module.set.position();
  192. }
  193. },
  194. documentChanged: function(mutations) {
  195. [].forEach.call(mutations, function(mutation) {
  196. if(mutation.removedNodes) {
  197. [].forEach.call(mutation.removedNodes, function(node) {
  198. if(node == element || $(node).find(element).length > 0) {
  199. module.debug('Element removed from DOM, tearing down events');
  200. module.destroy();
  201. }
  202. });
  203. }
  204. });
  205. },
  206. hideGracefully: function(event) {
  207. var
  208. $target = $(event.target),
  209. isInDOM = $.contains(document.documentElement, event.target),
  210. inPopup = ($target.closest(selector.popup).length > 0)
  211. ;
  212. // don't close on clicks inside popup
  213. if(event && !inPopup && isInDOM) {
  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. },
  222. // generates popup html from metadata
  223. create: function() {
  224. var
  225. html = module.get.html(),
  226. title = module.get.title(),
  227. content = module.get.content()
  228. ;
  229. if(html || content || title) {
  230. module.debug('Creating pop-up html');
  231. if(!html) {
  232. html = settings.templates.popup({
  233. title : title,
  234. content : content
  235. });
  236. }
  237. $popup = $('<div/>')
  238. .addClass(className.popup)
  239. .data(metadata.activator, $module)
  240. .html(html)
  241. ;
  242. if(settings.inline) {
  243. module.verbose('Inserting popup element inline', $popup);
  244. $popup
  245. .insertAfter($module)
  246. ;
  247. }
  248. else {
  249. module.verbose('Appending popup element to body', $popup);
  250. $popup
  251. .appendTo( $context )
  252. ;
  253. }
  254. module.refresh();
  255. module.set.variation();
  256. if(settings.hoverable) {
  257. module.bind.popup();
  258. }
  259. settings.onCreate.call($popup, element);
  260. }
  261. else if(settings.popup) {
  262. $(settings.popup).data(metadata.activator, $module);
  263. module.verbose('Used popup specified in settings');
  264. module.refresh();
  265. if(settings.hoverable) {
  266. module.bind.popup();
  267. }
  268. }
  269. else if($target.next(selector.popup).length !== 0) {
  270. module.verbose('Pre-existing popup found');
  271. settings.inline = true;
  272. settings.popup = $target.next(selector.popup).data(metadata.activator, $module);
  273. module.refresh();
  274. if(settings.hoverable) {
  275. module.bind.popup();
  276. }
  277. }
  278. else {
  279. module.debug('No content specified skipping display', element);
  280. }
  281. },
  282. createID: function() {
  283. id = (Math.random().toString(16) + '000000000').substr(2, 8);
  284. elementNamespace = '.' + id;
  285. module.verbose('Creating unique id for element', id);
  286. },
  287. // determines popup state
  288. toggle: function() {
  289. module.debug('Toggling pop-up');
  290. if( module.is.hidden() ) {
  291. module.debug('Popup is hidden, showing pop-up');
  292. module.unbind.close();
  293. module.show();
  294. }
  295. else {
  296. module.debug('Popup is visible, hiding pop-up');
  297. module.hide();
  298. }
  299. },
  300. show: function(callback) {
  301. callback = callback || function(){};
  302. module.debug('Showing pop-up', settings.transition);
  303. if(module.is.hidden() && !( module.is.active() && module.is.dropdown()) ) {
  304. if( !module.exists() ) {
  305. module.create();
  306. }
  307. if(settings.onShow.call($popup, element) === false) {
  308. module.debug('onShow callback returned false, cancelling popup animation');
  309. return;
  310. }
  311. else if(!settings.preserve && !settings.popup) {
  312. module.refresh();
  313. }
  314. if( $popup && module.set.position() ) {
  315. module.save.conditions();
  316. if(settings.exclusive) {
  317. module.hideAll();
  318. }
  319. module.animate.show(callback);
  320. }
  321. }
  322. },
  323. hide: function(callback) {
  324. callback = callback || function(){};
  325. if( module.is.visible() || module.is.animating() ) {
  326. if(settings.onHide.call($popup, element) === false) {
  327. module.debug('onHide callback returned false, cancelling popup animation');
  328. return;
  329. }
  330. module.remove.visible();
  331. module.unbind.close();
  332. module.restore.conditions();
  333. module.animate.hide(callback);
  334. }
  335. },
  336. hideAll: function() {
  337. $(selector.popup)
  338. .filter('.' + className.popupVisible)
  339. .each(function() {
  340. $(this)
  341. .data(metadata.activator)
  342. .popup('hide')
  343. ;
  344. })
  345. ;
  346. },
  347. exists: function() {
  348. if(!$popup) {
  349. return false;
  350. }
  351. if(settings.inline || settings.popup) {
  352. return ( module.has.popup() );
  353. }
  354. else {
  355. return ( $popup.closest($context).length >= 1 )
  356. ? true
  357. : false
  358. ;
  359. }
  360. },
  361. removePopup: function() {
  362. if( module.has.popup() && !settings.popup) {
  363. module.debug('Removing popup', $popup);
  364. $popup.remove();
  365. $popup = undefined;
  366. settings.onRemove.call($popup, element);
  367. }
  368. },
  369. save: {
  370. conditions: function() {
  371. module.cache = {
  372. title: $module.attr('title')
  373. };
  374. if (module.cache.title) {
  375. $module.removeAttr('title');
  376. }
  377. module.verbose('Saving original attributes', module.cache.title);
  378. }
  379. },
  380. restore: {
  381. conditions: function() {
  382. if(module.cache && module.cache.title) {
  383. $module.attr('title', module.cache.title);
  384. module.verbose('Restoring original attributes', module.cache.title);
  385. }
  386. return true;
  387. }
  388. },
  389. supports: {
  390. svg: function() {
  391. return (typeof SVGGraphicsElement !== 'undefined');
  392. }
  393. },
  394. animate: {
  395. show: function(callback) {
  396. callback = $.isFunction(callback) ? callback : function(){};
  397. if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
  398. module.set.visible();
  399. $popup
  400. .transition({
  401. animation : settings.transition + ' in',
  402. queue : false,
  403. debug : settings.debug,
  404. verbose : settings.verbose,
  405. duration : settings.duration,
  406. onComplete : function() {
  407. module.bind.close();
  408. callback.call($popup, element);
  409. settings.onVisible.call($popup, element);
  410. }
  411. })
  412. ;
  413. }
  414. else {
  415. module.error(error.noTransition);
  416. }
  417. },
  418. hide: function(callback) {
  419. callback = $.isFunction(callback) ? callback : function(){};
  420. module.debug('Hiding pop-up');
  421. if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
  422. $popup
  423. .transition({
  424. animation : settings.transition + ' out',
  425. queue : false,
  426. duration : settings.duration,
  427. debug : settings.debug,
  428. verbose : settings.verbose,
  429. onComplete : function() {
  430. module.reset();
  431. callback.call($popup, element);
  432. settings.onHidden.call($popup, element);
  433. }
  434. })
  435. ;
  436. }
  437. else {
  438. module.error(error.noTransition);
  439. }
  440. }
  441. },
  442. change: {
  443. content: function(html) {
  444. $popup.html(html);
  445. }
  446. },
  447. get: {
  448. html: function() {
  449. $module.removeData(metadata.html);
  450. return $module.data(metadata.html) || settings.html;
  451. },
  452. title: function() {
  453. $module.removeData(metadata.title);
  454. return $module.data(metadata.title) || settings.title;
  455. },
  456. content: function() {
  457. $module.removeData(metadata.content);
  458. return $module.data(metadata.content) || settings.content || $module.attr('title');
  459. },
  460. variation: function() {
  461. $module.removeData(metadata.variation);
  462. return $module.data(metadata.variation) || settings.variation;
  463. },
  464. popup: function() {
  465. return $popup;
  466. },
  467. popupOffset: function() {
  468. return $popup.offset();
  469. },
  470. calculations: function() {
  471. var
  472. $popupOffsetParent = module.get.offsetParent($popup),
  473. targetElement = $target[0],
  474. isWindow = ($boundary[0] == window),
  475. targetPosition = (settings.inline || (settings.popup && settings.movePopup))
  476. ? $target.position()
  477. : $target.offset(),
  478. screenPosition = (isWindow)
  479. ? { top: 0, left: 0 }
  480. : $boundary.offset(),
  481. calculations = {},
  482. scroll = (isWindow)
  483. ? { top: $window.scrollTop(), left: $window.scrollLeft() }
  484. : { top: 0, left: 0},
  485. screen
  486. ;
  487. calculations = {
  488. // element which is launching popup
  489. target : {
  490. element : $target[0],
  491. width : $target.outerWidth(),
  492. height : $target.outerHeight(),
  493. top : targetPosition.top,
  494. left : targetPosition.left,
  495. margin : {}
  496. },
  497. // popup itself
  498. popup : {
  499. width : $popup.outerWidth(),
  500. height : $popup.outerHeight()
  501. },
  502. // offset container (or 3d context)
  503. parent : {
  504. width : $offsetParent.outerWidth(),
  505. height : $offsetParent.outerHeight()
  506. },
  507. // screen boundaries
  508. screen : {
  509. top : screenPosition.top,
  510. left : screenPosition.left,
  511. scroll: {
  512. top : scroll.top,
  513. left : scroll.left
  514. },
  515. width : $boundary.width(),
  516. height : $boundary.height()
  517. }
  518. };
  519. // if popup offset context is not same as target, then adjust calculations
  520. if($popupOffsetParent.get(0) !== $offsetParent.get(0)) {
  521. var
  522. popupOffset = $popupOffsetParent.offset()
  523. ;
  524. calculations.target.top -= popupOffset.top;
  525. calculations.target.left -= popupOffset.left;
  526. calculations.parent.width = $popupOffsetParent.outerWidth();
  527. calculations.parent.height = $popupOffsetParent.outerHeight();
  528. }
  529. // add in container calcs if fluid
  530. if( settings.setFluidWidth && module.is.fluid() ) {
  531. calculations.container = {
  532. width: $popup.parent().outerWidth()
  533. };
  534. calculations.popup.width = calculations.container.width;
  535. }
  536. // add in margins if inline
  537. calculations.target.margin.top = (settings.inline)
  538. ? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-top'), 10)
  539. : 0
  540. ;
  541. calculations.target.margin.left = (settings.inline)
  542. ? module.is.rtl()
  543. ? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-right'), 10)
  544. : parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-left'), 10)
  545. : 0
  546. ;
  547. // calculate screen boundaries
  548. screen = calculations.screen;
  549. calculations.boundary = {
  550. top : screen.top + screen.scroll.top,
  551. bottom : screen.top + screen.scroll.top + screen.height,
  552. left : screen.left + screen.scroll.left,
  553. right : screen.left + screen.scroll.left + screen.width
  554. };
  555. return calculations;
  556. },
  557. id: function() {
  558. return id;
  559. },
  560. startEvent: function() {
  561. if(settings.on == 'hover') {
  562. return 'mouseenter';
  563. }
  564. else if(settings.on == 'focus') {
  565. return 'focus';
  566. }
  567. return false;
  568. },
  569. scrollEvent: function() {
  570. return 'scroll';
  571. },
  572. endEvent: function() {
  573. if(settings.on == 'hover') {
  574. return 'mouseleave';
  575. }
  576. else if(settings.on == 'focus') {
  577. return 'blur';
  578. }
  579. return false;
  580. },
  581. distanceFromBoundary: function(offset, calculations) {
  582. var
  583. distanceFromBoundary = {},
  584. popup,
  585. boundary
  586. ;
  587. calculations = calculations || module.get.calculations();
  588. // shorthand
  589. popup = calculations.popup;
  590. boundary = calculations.boundary;
  591. if(offset) {
  592. distanceFromBoundary = {
  593. top : (offset.top - boundary.top),
  594. left : (offset.left - boundary.left),
  595. right : (boundary.right - (offset.left + popup.width) ),
  596. bottom : (boundary.bottom - (offset.top + popup.height) )
  597. };
  598. module.verbose('Distance from boundaries determined', offset, distanceFromBoundary);
  599. }
  600. return distanceFromBoundary;
  601. },
  602. offsetParent: function($element) {
  603. var
  604. element = ($element !== undefined)
  605. ? $element[0]
  606. : $target[0],
  607. parentNode = element.parentNode,
  608. $node = $(parentNode)
  609. ;
  610. if(parentNode) {
  611. var
  612. is2D = ($node.css('transform') === 'none'),
  613. isStatic = ($node.css('position') === 'static'),
  614. isBody = $node.is('body')
  615. ;
  616. while(parentNode && !isBody && isStatic && is2D) {
  617. parentNode = parentNode.parentNode;
  618. $node = $(parentNode);
  619. is2D = ($node.css('transform') === 'none');
  620. isStatic = ($node.css('position') === 'static');
  621. isBody = $node.is('body');
  622. }
  623. }
  624. return ($node && $node.length > 0)
  625. ? $node
  626. : $()
  627. ;
  628. },
  629. positions: function() {
  630. return {
  631. 'top left' : false,
  632. 'top center' : false,
  633. 'top right' : false,
  634. 'bottom left' : false,
  635. 'bottom center' : false,
  636. 'bottom right' : false,
  637. 'left center' : false,
  638. 'right center' : false
  639. };
  640. },
  641. nextPosition: function(position) {
  642. var
  643. positions = position.split(' '),
  644. verticalPosition = positions[0],
  645. horizontalPosition = positions[1],
  646. opposite = {
  647. top : 'bottom',
  648. bottom : 'top',
  649. left : 'right',
  650. right : 'left'
  651. },
  652. adjacent = {
  653. left : 'center',
  654. center : 'right',
  655. right : 'left'
  656. },
  657. backup = {
  658. 'top left' : 'top center',
  659. 'top center' : 'top right',
  660. 'top right' : 'right center',
  661. 'right center' : 'bottom right',
  662. 'bottom right' : 'bottom center',
  663. 'bottom center' : 'bottom left',
  664. 'bottom left' : 'left center',
  665. 'left center' : 'top left'
  666. },
  667. adjacentsAvailable = (verticalPosition == 'top' || verticalPosition == 'bottom'),
  668. oppositeTried = false,
  669. adjacentTried = false,
  670. nextPosition = false
  671. ;
  672. if(!triedPositions) {
  673. module.verbose('All available positions available');
  674. triedPositions = module.get.positions();
  675. }
  676. module.debug('Recording last position tried', position);
  677. triedPositions[position] = true;
  678. if(settings.prefer === 'opposite') {
  679. nextPosition = [opposite[verticalPosition], horizontalPosition];
  680. nextPosition = nextPosition.join(' ');
  681. oppositeTried = (triedPositions[nextPosition] === true);
  682. module.debug('Trying opposite strategy', nextPosition);
  683. }
  684. if((settings.prefer === 'adjacent') && adjacentsAvailable ) {
  685. nextPosition = [verticalPosition, adjacent[horizontalPosition]];
  686. nextPosition = nextPosition.join(' ');
  687. adjacentTried = (triedPositions[nextPosition] === true);
  688. module.debug('Trying adjacent strategy', nextPosition);
  689. }
  690. if(adjacentTried || oppositeTried) {
  691. module.debug('Using backup position', nextPosition);
  692. nextPosition = backup[position];
  693. }
  694. return nextPosition;
  695. }
  696. },
  697. set: {
  698. position: function(position, calculations) {
  699. // exit conditions
  700. if($target.length === 0 || $popup.length === 0) {
  701. module.error(error.notFound);
  702. return;
  703. }
  704. var
  705. offset,
  706. distanceAway,
  707. target,
  708. popup,
  709. parent,
  710. positioning,
  711. popupOffset,
  712. distanceFromBoundary
  713. ;
  714. calculations = calculations || module.get.calculations();
  715. position = position || $module.data(metadata.position) || settings.position;
  716. offset = $module.data(metadata.offset) || settings.offset;
  717. distanceAway = settings.distanceAway;
  718. // shorthand
  719. target = calculations.target;
  720. popup = calculations.popup;
  721. parent = calculations.parent;
  722. if(module.should.centerArrow(calculations)) {
  723. module.verbose('Adjusting offset to center arrow on small target element');
  724. if(position == 'top left' || position == 'bottom left') {
  725. offset += (target.width / 2);
  726. offset -= settings.arrowPixelsFromEdge;
  727. }
  728. if(position == 'top right' || position == 'bottom right') {
  729. offset -= (target.width / 2);
  730. offset += settings.arrowPixelsFromEdge;
  731. }
  732. }
  733. if(target.width === 0 && target.height === 0 && !module.is.svg(target.element)) {
  734. module.debug('Popup target is hidden, no action taken');
  735. return false;
  736. }
  737. if(settings.inline) {
  738. module.debug('Adding margin to calculation', target.margin);
  739. if(position == 'left center' || position == 'right center') {
  740. offset += target.margin.top;
  741. distanceAway += -target.margin.left;
  742. }
  743. else if (position == 'top left' || position == 'top center' || position == 'top right') {
  744. offset += target.margin.left;
  745. distanceAway -= target.margin.top;
  746. }
  747. else {
  748. offset += target.margin.left;
  749. distanceAway += target.margin.top;
  750. }
  751. }
  752. module.debug('Determining popup position from calculations', position, calculations);
  753. if (module.is.rtl()) {
  754. position = position.replace(/left|right/g, function (match) {
  755. return (match == 'left')
  756. ? 'right'
  757. : 'left'
  758. ;
  759. });
  760. module.debug('RTL: Popup position updated', position);
  761. }
  762. // if last attempt use specified last resort position
  763. if(searchDepth == settings.maxSearchDepth && typeof settings.lastResort === 'string') {
  764. position = settings.lastResort;
  765. }
  766. switch (position) {
  767. case 'top left':
  768. positioning = {
  769. top : 'auto',
  770. bottom : parent.height - target.top + distanceAway,
  771. left : target.left + offset,
  772. right : 'auto'
  773. };
  774. break;
  775. case 'top center':
  776. positioning = {
  777. bottom : parent.height - target.top + distanceAway,
  778. left : target.left + (target.width / 2) - (popup.width / 2) + offset,
  779. top : 'auto',
  780. right : 'auto'
  781. };
  782. break;
  783. case 'top right':
  784. positioning = {
  785. bottom : parent.height - target.top + distanceAway,
  786. right : parent.width - target.left - target.width - offset,
  787. top : 'auto',
  788. left : 'auto'
  789. };
  790. break;
  791. case 'left center':
  792. positioning = {
  793. top : target.top + (target.height / 2) - (popup.height / 2) + offset,
  794. right : parent.width - target.left + distanceAway,
  795. left : 'auto',
  796. bottom : 'auto'
  797. };
  798. break;
  799. case 'right center':
  800. positioning = {
  801. top : target.top + (target.height / 2) - (popup.height / 2) + offset,
  802. left : target.left + target.width + distanceAway,
  803. bottom : 'auto',
  804. right : 'auto'
  805. };
  806. break;
  807. case 'bottom left':
  808. positioning = {
  809. top : target.top + target.height + distanceAway,
  810. left : target.left + offset,
  811. bottom : 'auto',
  812. right : 'auto'
  813. };
  814. break;
  815. case 'bottom center':
  816. positioning = {
  817. top : target.top + target.height + distanceAway,
  818. left : target.left + (target.width / 2) - (popup.width / 2) + offset,
  819. bottom : 'auto',
  820. right : 'auto'
  821. };
  822. break;
  823. case 'bottom right':
  824. positioning = {
  825. top : target.top + target.height + distanceAway,
  826. right : parent.width - target.left - target.width - offset,
  827. left : 'auto',
  828. bottom : 'auto'
  829. };
  830. break;
  831. }
  832. if(positioning === undefined) {
  833. module.error(error.invalidPosition, position);
  834. }
  835. module.debug('Calculated popup positioning values', positioning);
  836. // tentatively place on stage
  837. $popup
  838. .css(positioning)
  839. .removeClass(className.position)
  840. .addClass(position)
  841. .addClass(className.loading)
  842. ;
  843. popupOffset = module.get.popupOffset();
  844. // see if any boundaries are surpassed with this tentative position
  845. distanceFromBoundary = module.get.distanceFromBoundary(popupOffset, calculations);
  846. if(!settings.forcePosition && module.is.offstage(distanceFromBoundary, position) ) {
  847. module.debug('Position is outside viewport', position);
  848. if(searchDepth < settings.maxSearchDepth) {
  849. searchDepth++;
  850. position = module.get.nextPosition(position);
  851. module.debug('Trying new position', position);
  852. return ($popup)
  853. ? module.set.position(position, calculations)
  854. : false
  855. ;
  856. }
  857. else {
  858. if(settings.lastResort) {
  859. module.debug('No position found, showing with last position');
  860. }
  861. else {
  862. module.debug('Popup could not find a position to display', $popup);
  863. module.error(error.cannotPlace, element);
  864. module.remove.attempts();
  865. module.remove.loading();
  866. module.reset();
  867. settings.onUnplaceable.call($popup, element);
  868. return false;
  869. }
  870. }
  871. }
  872. module.debug('Position is on stage', position);
  873. module.remove.attempts();
  874. module.remove.loading();
  875. if( settings.setFluidWidth && module.is.fluid() ) {
  876. module.set.fluidWidth(calculations);
  877. }
  878. return true;
  879. },
  880. fluidWidth: function(calculations) {
  881. calculations = calculations || module.get.calculations();
  882. module.debug('Automatically setting element width to parent width', calculations.parent.width);
  883. $popup.css('width', calculations.container.width);
  884. },
  885. variation: function(variation) {
  886. variation = variation || module.get.variation();
  887. if(variation && module.has.popup() ) {
  888. module.verbose('Adding variation to popup', variation);
  889. $popup.addClass(variation);
  890. }
  891. },
  892. visible: function() {
  893. $module.addClass(className.visible);
  894. }
  895. },
  896. remove: {
  897. loading: function() {
  898. $popup.removeClass(className.loading);
  899. },
  900. variation: function(variation) {
  901. variation = variation || module.get.variation();
  902. if(variation) {
  903. module.verbose('Removing variation', variation);
  904. $popup.removeClass(variation);
  905. }
  906. },
  907. visible: function() {
  908. $module.removeClass(className.visible);
  909. },
  910. attempts: function() {
  911. module.verbose('Resetting all searched positions');
  912. searchDepth = 0;
  913. triedPositions = false;
  914. }
  915. },
  916. bind: {
  917. events: function() {
  918. module.debug('Binding popup events to module');
  919. if(settings.on == 'click') {
  920. $module
  921. .on(clickEvent + eventNamespace, module.toggle)
  922. ;
  923. }
  924. if(settings.on == 'hover') {
  925. $module
  926. .on('touchstart' + eventNamespace, module.event.touchstart)
  927. ;
  928. }
  929. if( module.get.startEvent() ) {
  930. $module
  931. .on(module.get.startEvent() + eventNamespace, module.event.start)
  932. .on(module.get.endEvent() + eventNamespace, module.event.end)
  933. ;
  934. }
  935. if(settings.target) {
  936. module.debug('Target set to element', $target);
  937. }
  938. $window.on('resize' + elementNamespace, module.event.resize);
  939. },
  940. popup: function() {
  941. module.verbose('Allowing hover events on popup to prevent closing');
  942. if( $popup && module.has.popup() ) {
  943. $popup
  944. .on('mouseenter' + eventNamespace, module.event.start)
  945. .on('mouseleave' + eventNamespace, module.event.end)
  946. ;
  947. }
  948. },
  949. close: function() {
  950. if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
  951. module.bind.closeOnScroll();
  952. }
  953. if(module.is.closable()) {
  954. module.bind.clickaway();
  955. }
  956. else if(settings.on == 'hover' && openedWithTouch) {
  957. module.bind.touchClose();
  958. }
  959. },
  960. closeOnScroll: function() {
  961. module.verbose('Binding scroll close event to document');
  962. $scrollContext
  963. .one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
  964. ;
  965. },
  966. touchClose: function() {
  967. module.verbose('Binding popup touchclose event to document');
  968. $document
  969. .on('touchstart' + elementNamespace, function(event) {
  970. module.verbose('Touched away from popup');
  971. module.event.hideGracefully.call(element, event);
  972. })
  973. ;
  974. },
  975. clickaway: function() {
  976. module.verbose('Binding popup close event to document');
  977. $document
  978. .on(clickEvent + elementNamespace, function(event) {
  979. module.verbose('Clicked away from popup');
  980. module.event.hideGracefully.call(element, event);
  981. })
  982. ;
  983. }
  984. },
  985. unbind: {
  986. events: function() {
  987. $window
  988. .off(elementNamespace)
  989. ;
  990. $module
  991. .off(eventNamespace)
  992. ;
  993. },
  994. close: function() {
  995. $document
  996. .off(elementNamespace)
  997. ;
  998. $scrollContext
  999. .off(elementNamespace)
  1000. ;
  1001. },
  1002. },
  1003. has: {
  1004. popup: function() {
  1005. return ($popup && $popup.length > 0);
  1006. }
  1007. },
  1008. should: {
  1009. centerArrow: function(calculations) {
  1010. return !module.is.basic() && calculations.target.width <= (settings.arrowPixelsFromEdge * 2);
  1011. },
  1012. },
  1013. is: {
  1014. closable: function() {
  1015. if(settings.closable == 'auto') {
  1016. if(settings.on == 'hover') {
  1017. return false;
  1018. }
  1019. return true;
  1020. }
  1021. return settings.closable;
  1022. },
  1023. offstage: function(distanceFromBoundary, position) {
  1024. var
  1025. offstage = []
  1026. ;
  1027. // return boundaries that have been surpassed
  1028. $.each(distanceFromBoundary, function(direction, distance) {
  1029. if(distance < -settings.jitter) {
  1030. module.debug('Position exceeds allowable distance from edge', direction, distance, position);
  1031. offstage.push(direction);
  1032. }
  1033. });
  1034. if(offstage.length > 0) {
  1035. return true;
  1036. }
  1037. else {
  1038. return false;
  1039. }
  1040. },
  1041. svg: function(element) {
  1042. return module.supports.svg() && (element instanceof SVGGraphicsElement);
  1043. },
  1044. basic: function() {
  1045. return $module.hasClass(className.basic);
  1046. },
  1047. active: function() {
  1048. return $module.hasClass(className.active);
  1049. },
  1050. animating: function() {
  1051. return ($popup !== undefined && $popup.hasClass(className.animating) );
  1052. },
  1053. fluid: function() {
  1054. return ($popup !== undefined && $popup.hasClass(className.fluid));
  1055. },
  1056. visible: function() {
  1057. return ($popup !== undefined && $popup.hasClass(className.popupVisible));
  1058. },
  1059. dropdown: function() {
  1060. return $module.hasClass(className.dropdown);
  1061. },
  1062. hidden: function() {
  1063. return !module.is.visible();
  1064. },
  1065. rtl: function () {
  1066. return $module.attr('dir') === 'rtl' || $module.css('direction') === 'rtl';
  1067. }
  1068. },
  1069. reset: function() {
  1070. module.remove.visible();
  1071. if(settings.preserve) {
  1072. if($.fn.transition !== undefined) {
  1073. $popup
  1074. .transition('remove transition')
  1075. ;
  1076. }
  1077. }
  1078. else {
  1079. module.removePopup();
  1080. }
  1081. },
  1082. setting: function(name, value) {
  1083. if( $.isPlainObject(name) ) {
  1084. $.extend(true, settings, name);
  1085. }
  1086. else if(value !== undefined) {
  1087. settings[name] = value;
  1088. }
  1089. else {
  1090. return settings[name];
  1091. }
  1092. },
  1093. internal: function(name, value) {
  1094. if( $.isPlainObject(name) ) {
  1095. $.extend(true, module, name);
  1096. }
  1097. else if(value !== undefined) {
  1098. module[name] = value;
  1099. }
  1100. else {
  1101. return module[name];
  1102. }
  1103. },
  1104. debug: function() {
  1105. if(!settings.silent && settings.debug) {
  1106. if(settings.performance) {
  1107. module.performance.log(arguments);
  1108. }
  1109. else {
  1110. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  1111. module.debug.apply(console, arguments);
  1112. }
  1113. }
  1114. },
  1115. verbose: function() {
  1116. if(!settings.silent && settings.verbose && settings.debug) {
  1117. if(settings.performance) {
  1118. module.performance.log(arguments);
  1119. }
  1120. else {
  1121. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  1122. module.verbose.apply(console, arguments);
  1123. }
  1124. }
  1125. },
  1126. error: function() {
  1127. if(!settings.silent) {
  1128. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  1129. module.error.apply(console, arguments);
  1130. }
  1131. },
  1132. performance: {
  1133. log: function(message) {
  1134. var
  1135. currentTime,
  1136. executionTime,
  1137. previousTime
  1138. ;
  1139. if(settings.performance) {
  1140. currentTime = new Date().getTime();
  1141. previousTime = time || currentTime;
  1142. executionTime = currentTime - previousTime;
  1143. time = currentTime;
  1144. performance.push({
  1145. 'Name' : message[0],
  1146. 'Arguments' : [].slice.call(message, 1) || '',
  1147. 'Element' : element,
  1148. 'Execution Time' : executionTime
  1149. });
  1150. }
  1151. clearTimeout(module.performance.timer);
  1152. module.performance.timer = setTimeout(module.performance.display, 500);
  1153. },
  1154. display: function() {
  1155. var
  1156. title = settings.name + ':',
  1157. totalTime = 0
  1158. ;
  1159. time = false;
  1160. clearTimeout(module.performance.timer);
  1161. $.each(performance, function(index, data) {
  1162. totalTime += data['Execution Time'];
  1163. });
  1164. title += ' ' + totalTime + 'ms';
  1165. if(moduleSelector) {
  1166. title += ' \'' + moduleSelector + '\'';
  1167. }
  1168. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  1169. console.groupCollapsed(title);
  1170. if(console.table) {
  1171. console.table(performance);
  1172. }
  1173. else {
  1174. $.each(performance, function(index, data) {
  1175. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  1176. });
  1177. }
  1178. console.groupEnd();
  1179. }
  1180. performance = [];
  1181. }
  1182. },
  1183. invoke: function(query, passedArguments, context) {
  1184. var
  1185. object = instance,
  1186. maxDepth,
  1187. found,
  1188. response
  1189. ;
  1190. passedArguments = passedArguments || queryArguments;
  1191. context = element || context;
  1192. if(typeof query == 'string' && object !== undefined) {
  1193. query = query.split(/[\. ]/);
  1194. maxDepth = query.length - 1;
  1195. $.each(query, function(depth, value) {
  1196. var camelCaseValue = (depth != maxDepth)
  1197. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  1198. : query
  1199. ;
  1200. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  1201. object = object[camelCaseValue];
  1202. }
  1203. else if( object[camelCaseValue] !== undefined ) {
  1204. found = object[camelCaseValue];
  1205. return false;
  1206. }
  1207. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  1208. object = object[value];
  1209. }
  1210. else if( object[value] !== undefined ) {
  1211. found = object[value];
  1212. return false;
  1213. }
  1214. else {
  1215. return false;
  1216. }
  1217. });
  1218. }
  1219. if ( $.isFunction( found ) ) {
  1220. response = found.apply(context, passedArguments);
  1221. }
  1222. else if(found !== undefined) {
  1223. response = found;
  1224. }
  1225. if(Array.isArray(returnedValue)) {
  1226. returnedValue.push(response);
  1227. }
  1228. else if(returnedValue !== undefined) {
  1229. returnedValue = [returnedValue, response];
  1230. }
  1231. else if(response !== undefined) {
  1232. returnedValue = response;
  1233. }
  1234. return found;
  1235. }
  1236. };
  1237. if(methodInvoked) {
  1238. if(instance === undefined) {
  1239. module.initialize();
  1240. }
  1241. module.invoke(query);
  1242. }
  1243. else {
  1244. if(instance !== undefined) {
  1245. instance.invoke('destroy');
  1246. }
  1247. module.initialize();
  1248. }
  1249. })
  1250. ;
  1251. return (returnedValue !== undefined)
  1252. ? returnedValue
  1253. : this
  1254. ;
  1255. };
  1256. $.fn.popup.settings = {
  1257. name : 'Popup',
  1258. // module settings
  1259. silent : false,
  1260. debug : false,
  1261. verbose : false,
  1262. performance : true,
  1263. namespace : 'popup',
  1264. // whether it should use dom mutation observers
  1265. observeChanges : true,
  1266. // callback only when element added to dom
  1267. onCreate : function(){},
  1268. // callback before element removed from dom
  1269. onRemove : function(){},
  1270. // callback before show animation
  1271. onShow : function(){},
  1272. // callback after show animation
  1273. onVisible : function(){},
  1274. // callback before hide animation
  1275. onHide : function(){},
  1276. // callback when popup cannot be positioned in visible screen
  1277. onUnplaceable : function(){},
  1278. // callback after hide animation
  1279. onHidden : function(){},
  1280. // when to show popup
  1281. on : 'hover',
  1282. // element to use to determine if popup is out of boundary
  1283. boundary : window,
  1284. // whether to add touchstart events when using hover
  1285. addTouchEvents : true,
  1286. // default position relative to element
  1287. position : 'top left',
  1288. // if given position should be used regardless if popup fits
  1289. forcePosition : false,
  1290. // name of variation to use
  1291. variation : '',
  1292. // whether popup should be moved to context
  1293. movePopup : true,
  1294. // element which popup should be relative to
  1295. target : false,
  1296. // jq selector or element that should be used as popup
  1297. popup : false,
  1298. // popup should remain inline next to activator
  1299. inline : false,
  1300. // popup should be removed from page on hide
  1301. preserve : false,
  1302. // popup should not close when being hovered on
  1303. hoverable : false,
  1304. // explicitly set content
  1305. content : false,
  1306. // explicitly set html
  1307. html : false,
  1308. // explicitly set title
  1309. title : false,
  1310. // whether automatically close on clickaway when on click
  1311. closable : true,
  1312. // automatically hide on scroll
  1313. hideOnScroll : 'auto',
  1314. // hide other popups on show
  1315. exclusive : false,
  1316. // context to attach popups
  1317. context : 'body',
  1318. // context for binding scroll events
  1319. scrollContext : window,
  1320. // position to prefer when calculating new position
  1321. prefer : 'opposite',
  1322. // specify position to appear even if it doesn't fit
  1323. lastResort : false,
  1324. // number of pixels from edge of popup to pointing arrow center (used from centering)
  1325. arrowPixelsFromEdge: 20,
  1326. // delay used to prevent accidental refiring of animations due to user error
  1327. delay : {
  1328. show : 50,
  1329. hide : 70
  1330. },
  1331. // whether fluid variation should assign width explicitly
  1332. setFluidWidth : true,
  1333. // transition settings
  1334. duration : 200,
  1335. transition : 'scale',
  1336. // distance away from activating element in px
  1337. distanceAway : 0,
  1338. // number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding)
  1339. jitter : 2,
  1340. // offset on aligning axis from calculated position
  1341. offset : 0,
  1342. // maximum times to look for a position before failing (9 positions total)
  1343. maxSearchDepth : 15,
  1344. error: {
  1345. invalidPosition : 'The position you specified is not a valid position',
  1346. cannotPlace : 'Popup does not fit within the boundaries of the viewport',
  1347. method : 'The method you called is not defined.',
  1348. noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>',
  1349. notFound : 'The target or popup you specified does not exist on the page'
  1350. },
  1351. metadata: {
  1352. activator : 'activator',
  1353. content : 'content',
  1354. html : 'html',
  1355. offset : 'offset',
  1356. position : 'position',
  1357. title : 'title',
  1358. variation : 'variation'
  1359. },
  1360. className : {
  1361. active : 'active',
  1362. basic : 'basic',
  1363. animating : 'animating',
  1364. dropdown : 'dropdown',
  1365. fluid : 'fluid',
  1366. loading : 'loading',
  1367. popup : 'ui popup',
  1368. position : 'top left center bottom right',
  1369. visible : 'visible',
  1370. popupVisible : 'visible'
  1371. },
  1372. selector : {
  1373. popup : '.ui.popup'
  1374. },
  1375. templates: {
  1376. escape: function(string) {
  1377. var
  1378. badChars = /[<>"'`]/g,
  1379. shouldEscape = /[&<>"'`]/,
  1380. escape = {
  1381. "<": "&lt;",
  1382. ">": "&gt;",
  1383. '"': "&quot;",
  1384. "'": "&#x27;",
  1385. "`": "&#x60;"
  1386. },
  1387. escapedChar = function(chr) {
  1388. return escape[chr];
  1389. }
  1390. ;
  1391. if(shouldEscape.test(string)) {
  1392. string = string.replace(/&(?![a-z0-9#]{1,6};)/, "&amp;");
  1393. return string.replace(badChars, escapedChar);
  1394. }
  1395. return string;
  1396. },
  1397. popup: function(text) {
  1398. var
  1399. html = '',
  1400. escape = $.fn.popup.settings.templates.escape
  1401. ;
  1402. if(typeof text !== undefined) {
  1403. if(typeof text.title !== undefined && text.title) {
  1404. text.title = escape(text.title);
  1405. html += '<div class="header">' + text.title + '</div>';
  1406. }
  1407. if(typeof text.content !== undefined && text.content) {
  1408. text.content = escape(text.content);
  1409. html += '<div class="content">' + text.content + '</div>';
  1410. }
  1411. }
  1412. return html;
  1413. }
  1414. }
  1415. };
  1416. })( jQuery, window, document );