popup.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523
  1. /*!
  2. * # Semantic UI 2.3.3 - 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(settings.on == 'hover' && openedWithTouch) {
  951. module.bind.touchClose();
  952. }
  953. if(settings.on == 'click' && settings.closable) {
  954. module.bind.clickaway();
  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. offstage: function(distanceFromBoundary, position) {
  1012. var
  1013. offstage = []
  1014. ;
  1015. // return boundaries that have been surpassed
  1016. $.each(distanceFromBoundary, function(direction, distance) {
  1017. if(distance < -settings.jitter) {
  1018. module.debug('Position exceeds allowable distance from edge', direction, distance, position);
  1019. offstage.push(direction);
  1020. }
  1021. });
  1022. if(offstage.length > 0) {
  1023. return true;
  1024. }
  1025. else {
  1026. return false;
  1027. }
  1028. },
  1029. svg: function(element) {
  1030. return module.supports.svg() && (element instanceof SVGGraphicsElement);
  1031. },
  1032. basic: function() {
  1033. return $module.hasClass(className.basic);
  1034. },
  1035. active: function() {
  1036. return $module.hasClass(className.active);
  1037. },
  1038. animating: function() {
  1039. return ($popup !== undefined && $popup.hasClass(className.animating) );
  1040. },
  1041. fluid: function() {
  1042. return ($popup !== undefined && $popup.hasClass(className.fluid));
  1043. },
  1044. visible: function() {
  1045. return ($popup !== undefined && $popup.hasClass(className.popupVisible));
  1046. },
  1047. dropdown: function() {
  1048. return $module.hasClass(className.dropdown);
  1049. },
  1050. hidden: function() {
  1051. return !module.is.visible();
  1052. },
  1053. rtl: function () {
  1054. return $module.css('direction') == 'rtl';
  1055. }
  1056. },
  1057. reset: function() {
  1058. module.remove.visible();
  1059. if(settings.preserve) {
  1060. if($.fn.transition !== undefined) {
  1061. $popup
  1062. .transition('remove transition')
  1063. ;
  1064. }
  1065. }
  1066. else {
  1067. module.removePopup();
  1068. }
  1069. },
  1070. setting: function(name, value) {
  1071. if( $.isPlainObject(name) ) {
  1072. $.extend(true, settings, name);
  1073. }
  1074. else if(value !== undefined) {
  1075. settings[name] = value;
  1076. }
  1077. else {
  1078. return settings[name];
  1079. }
  1080. },
  1081. internal: function(name, value) {
  1082. if( $.isPlainObject(name) ) {
  1083. $.extend(true, module, name);
  1084. }
  1085. else if(value !== undefined) {
  1086. module[name] = value;
  1087. }
  1088. else {
  1089. return module[name];
  1090. }
  1091. },
  1092. debug: function() {
  1093. if(!settings.silent && settings.debug) {
  1094. if(settings.performance) {
  1095. module.performance.log(arguments);
  1096. }
  1097. else {
  1098. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  1099. module.debug.apply(console, arguments);
  1100. }
  1101. }
  1102. },
  1103. verbose: function() {
  1104. if(!settings.silent && settings.verbose && settings.debug) {
  1105. if(settings.performance) {
  1106. module.performance.log(arguments);
  1107. }
  1108. else {
  1109. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  1110. module.verbose.apply(console, arguments);
  1111. }
  1112. }
  1113. },
  1114. error: function() {
  1115. if(!settings.silent) {
  1116. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  1117. module.error.apply(console, arguments);
  1118. }
  1119. },
  1120. performance: {
  1121. log: function(message) {
  1122. var
  1123. currentTime,
  1124. executionTime,
  1125. previousTime
  1126. ;
  1127. if(settings.performance) {
  1128. currentTime = new Date().getTime();
  1129. previousTime = time || currentTime;
  1130. executionTime = currentTime - previousTime;
  1131. time = currentTime;
  1132. performance.push({
  1133. 'Name' : message[0],
  1134. 'Arguments' : [].slice.call(message, 1) || '',
  1135. 'Element' : element,
  1136. 'Execution Time' : executionTime
  1137. });
  1138. }
  1139. clearTimeout(module.performance.timer);
  1140. module.performance.timer = setTimeout(module.performance.display, 500);
  1141. },
  1142. display: function() {
  1143. var
  1144. title = settings.name + ':',
  1145. totalTime = 0
  1146. ;
  1147. time = false;
  1148. clearTimeout(module.performance.timer);
  1149. $.each(performance, function(index, data) {
  1150. totalTime += data['Execution Time'];
  1151. });
  1152. title += ' ' + totalTime + 'ms';
  1153. if(moduleSelector) {
  1154. title += ' \'' + moduleSelector + '\'';
  1155. }
  1156. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  1157. console.groupCollapsed(title);
  1158. if(console.table) {
  1159. console.table(performance);
  1160. }
  1161. else {
  1162. $.each(performance, function(index, data) {
  1163. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  1164. });
  1165. }
  1166. console.groupEnd();
  1167. }
  1168. performance = [];
  1169. }
  1170. },
  1171. invoke: function(query, passedArguments, context) {
  1172. var
  1173. object = instance,
  1174. maxDepth,
  1175. found,
  1176. response
  1177. ;
  1178. passedArguments = passedArguments || queryArguments;
  1179. context = element || context;
  1180. if(typeof query == 'string' && object !== undefined) {
  1181. query = query.split(/[\. ]/);
  1182. maxDepth = query.length - 1;
  1183. $.each(query, function(depth, value) {
  1184. var camelCaseValue = (depth != maxDepth)
  1185. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  1186. : query
  1187. ;
  1188. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  1189. object = object[camelCaseValue];
  1190. }
  1191. else if( object[camelCaseValue] !== undefined ) {
  1192. found = object[camelCaseValue];
  1193. return false;
  1194. }
  1195. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  1196. object = object[value];
  1197. }
  1198. else if( object[value] !== undefined ) {
  1199. found = object[value];
  1200. return false;
  1201. }
  1202. else {
  1203. return false;
  1204. }
  1205. });
  1206. }
  1207. if ( $.isFunction( found ) ) {
  1208. response = found.apply(context, passedArguments);
  1209. }
  1210. else if(found !== undefined) {
  1211. response = found;
  1212. }
  1213. if($.isArray(returnedValue)) {
  1214. returnedValue.push(response);
  1215. }
  1216. else if(returnedValue !== undefined) {
  1217. returnedValue = [returnedValue, response];
  1218. }
  1219. else if(response !== undefined) {
  1220. returnedValue = response;
  1221. }
  1222. return found;
  1223. }
  1224. };
  1225. if(methodInvoked) {
  1226. if(instance === undefined) {
  1227. module.initialize();
  1228. }
  1229. module.invoke(query);
  1230. }
  1231. else {
  1232. if(instance !== undefined) {
  1233. instance.invoke('destroy');
  1234. }
  1235. module.initialize();
  1236. }
  1237. })
  1238. ;
  1239. return (returnedValue !== undefined)
  1240. ? returnedValue
  1241. : this
  1242. ;
  1243. };
  1244. $.fn.popup.settings = {
  1245. name : 'Popup',
  1246. // module settings
  1247. silent : false,
  1248. debug : false,
  1249. verbose : false,
  1250. performance : true,
  1251. namespace : 'popup',
  1252. // whether it should use dom mutation observers
  1253. observeChanges : true,
  1254. // callback only when element added to dom
  1255. onCreate : function(){},
  1256. // callback before element removed from dom
  1257. onRemove : function(){},
  1258. // callback before show animation
  1259. onShow : function(){},
  1260. // callback after show animation
  1261. onVisible : function(){},
  1262. // callback before hide animation
  1263. onHide : function(){},
  1264. // callback when popup cannot be positioned in visible screen
  1265. onUnplaceable : function(){},
  1266. // callback after hide animation
  1267. onHidden : function(){},
  1268. // when to show popup
  1269. on : 'hover',
  1270. // element to use to determine if popup is out of boundary
  1271. boundary : window,
  1272. // whether to add touchstart events when using hover
  1273. addTouchEvents : true,
  1274. // default position relative to element
  1275. position : 'top left',
  1276. // name of variation to use
  1277. variation : '',
  1278. // whether popup should be moved to context
  1279. movePopup : true,
  1280. // element which popup should be relative to
  1281. target : false,
  1282. // jq selector or element that should be used as popup
  1283. popup : false,
  1284. // popup should remain inline next to activator
  1285. inline : false,
  1286. // popup should be removed from page on hide
  1287. preserve : false,
  1288. // popup should not close when being hovered on
  1289. hoverable : false,
  1290. // explicitly set content
  1291. content : false,
  1292. // explicitly set html
  1293. html : false,
  1294. // explicitly set title
  1295. title : false,
  1296. // whether automatically close on clickaway when on click
  1297. closable : true,
  1298. // automatically hide on scroll
  1299. hideOnScroll : 'auto',
  1300. // hide other popups on show
  1301. exclusive : false,
  1302. // context to attach popups
  1303. context : 'body',
  1304. // context for binding scroll events
  1305. scrollContext : window,
  1306. // position to prefer when calculating new position
  1307. prefer : 'opposite',
  1308. // specify position to appear even if it doesn't fit
  1309. lastResort : false,
  1310. // number of pixels from edge of popup to pointing arrow center (used from centering)
  1311. arrowPixelsFromEdge: 20,
  1312. // delay used to prevent accidental refiring of animations due to user error
  1313. delay : {
  1314. show : 50,
  1315. hide : 70
  1316. },
  1317. // whether fluid variation should assign width explicitly
  1318. setFluidWidth : true,
  1319. // transition settings
  1320. duration : 200,
  1321. transition : 'scale',
  1322. // distance away from activating element in px
  1323. distanceAway : 0,
  1324. // number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding)
  1325. jitter : 2,
  1326. // offset on aligning axis from calculated position
  1327. offset : 0,
  1328. // maximum times to look for a position before failing (9 positions total)
  1329. maxSearchDepth : 15,
  1330. error: {
  1331. invalidPosition : 'The position you specified is not a valid position',
  1332. cannotPlace : 'Popup does not fit within the boundaries of the viewport',
  1333. method : 'The method you called is not defined.',
  1334. noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>',
  1335. notFound : 'The target or popup you specified does not exist on the page'
  1336. },
  1337. metadata: {
  1338. activator : 'activator',
  1339. content : 'content',
  1340. html : 'html',
  1341. offset : 'offset',
  1342. position : 'position',
  1343. title : 'title',
  1344. variation : 'variation'
  1345. },
  1346. className : {
  1347. active : 'active',
  1348. basic : 'basic',
  1349. animating : 'animating',
  1350. dropdown : 'dropdown',
  1351. fluid : 'fluid',
  1352. loading : 'loading',
  1353. popup : 'ui popup',
  1354. position : 'top left center bottom right',
  1355. visible : 'visible',
  1356. popupVisible : 'visible'
  1357. },
  1358. selector : {
  1359. popup : '.ui.popup'
  1360. },
  1361. templates: {
  1362. escape: function(string) {
  1363. var
  1364. badChars = /[&<>"'`]/g,
  1365. shouldEscape = /[&<>"'`]/,
  1366. escape = {
  1367. "&": "&amp;",
  1368. "<": "&lt;",
  1369. ">": "&gt;",
  1370. '"': "&quot;",
  1371. "'": "&#x27;",
  1372. "`": "&#x60;"
  1373. },
  1374. escapedChar = function(chr) {
  1375. return escape[chr];
  1376. }
  1377. ;
  1378. if(shouldEscape.test(string)) {
  1379. return string.replace(badChars, escapedChar);
  1380. }
  1381. return string;
  1382. },
  1383. popup: function(text) {
  1384. var
  1385. html = '',
  1386. escape = $.fn.popup.settings.templates.escape
  1387. ;
  1388. if(typeof text !== undefined) {
  1389. if(typeof text.title !== undefined && text.title) {
  1390. text.title = escape(text.title);
  1391. html += '<div class="header">' + text.title + '</div>';
  1392. }
  1393. if(typeof text.content !== undefined && text.content) {
  1394. text.content = escape(text.content);
  1395. html += '<div class="content">' + text.content + '</div>';
  1396. }
  1397. }
  1398. return html;
  1399. }
  1400. }
  1401. };
  1402. })( jQuery, window, document );