popup.js 50 KB

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