popup.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // A simple tracker dependency that we invalidate every time the window is
  2. // resized. This is used to reactively re-calculate the popup position in case
  3. // of a window resize.
  4. var windowResizeDep = new Tracker.Dependency();
  5. $(window).on('resize', function() { windowResizeDep.changed(); });
  6. Popup = {
  7. /// This function returns a callback that can be used in an event map:
  8. ///
  9. /// Template.tplName.events({
  10. /// 'click .elementClass': Popup.open("popupName")
  11. /// });
  12. ///
  13. /// The popup inherit the data context of its parent.
  14. open: function(name) {
  15. var self = this;
  16. var popupName = name + 'Popup';
  17. var clickFromPopup = function(evt) {
  18. return $(evt.target).closest('.js-pop-over').length !== 0;
  19. };
  20. return function(evt) {
  21. // If a popup is already openened, clicking again on the opener element
  22. // should close it -- and interupt the current `open` function.
  23. if (self.isOpen()) {
  24. var previousOpenerElement = self._getTopStack().openerElement;
  25. if (previousOpenerElement === evt.currentTarget) {
  26. return self.close();
  27. } else {
  28. $(previousOpenerElement).removeClass('is-active');
  29. }
  30. }
  31. // We determine the `openerElement` (the DOM element that is being clicked
  32. // and the one we take in reference to position the popup) from the event
  33. // if the popup has no parent, or from the parent `openerElement` if it
  34. // has one. This allows us to position a sub-popup exactly at the same
  35. // position than its parent.
  36. var openerElement;
  37. if (clickFromPopup(evt)) {
  38. openerElement = self._getTopStack().openerElement;
  39. } else {
  40. self._stack = [];
  41. openerElement = evt.currentTarget;
  42. }
  43. $(openerElement).addClass('is-active');
  44. evt.preventDefault();
  45. // We push our popup data to the stack. The top of the stack is always
  46. // used as the data source for our current popup.
  47. self._stack.push({
  48. popupName: popupName,
  49. hasPopupParent: clickFromPopup(evt),
  50. title: self._getTitle(popupName),
  51. openerElement: openerElement,
  52. depth: self._stack.length,
  53. offset: self._getOffset(openerElement),
  54. dataContext: this.currentData && this.currentData() || this
  55. });
  56. // If there are no popup currently opened we use the Blaze API to render
  57. // one into the DOM. We use a reactive function as the data parameter that
  58. // return the the complete along with its top element and depends on our
  59. // internal dependency that is being invalidated every time the top
  60. // element of the stack has changed and we want to update the popup.
  61. //
  62. // Otherwise if there is already a popup open we just need to invalidate
  63. // our internal dependency, and since we just changed the top element of
  64. // our internal stack, the popup will be updated with the new data.
  65. if (! self.isOpen()) {
  66. self.current = Blaze.renderWithData(self.template, function() {
  67. self._dep.depend();
  68. return _.extend(self._stack[self._stack.length - 1], {
  69. stack: self._stack
  70. });
  71. }, document.body);
  72. } else {
  73. self._dep.changed();
  74. }
  75. };
  76. },
  77. /// This function returns a callback that can be used in an event map:
  78. ///
  79. /// Template.tplName.events({
  80. /// 'click .elementClass': Popup.afterConfirm("popupName", function() {
  81. /// // What to do after the user has confirmed the action
  82. /// })
  83. /// });
  84. afterConfirm: function(name, action) {
  85. var self = this;
  86. return function(evt, tpl) {
  87. var context = this.currentData && this.currentData() || this;
  88. context.__afterConfirmAction = action;
  89. self.open(name).call(context, evt, tpl);
  90. };
  91. },
  92. /// The public reactive state of the popup.
  93. isOpen: function() {
  94. this._dep.changed();
  95. return !! this.current;
  96. },
  97. /// In case the popup was opened from a parent popup we can get back to it
  98. /// with this `Popup.back()` function. You can go back several steps at once
  99. /// by providing a number to this function, e.g. `Popup.back(2)`. In this case
  100. /// intermediate popup won't even be rendered on the DOM. If the number of
  101. /// steps back is greater than the popup stack size, the popup will be closed.
  102. back: function(n) {
  103. n = n || 1;
  104. var self = this;
  105. if (self._stack.length > n) {
  106. _.times(n, function() { self._stack.pop(); });
  107. self._dep.changed();
  108. } else {
  109. self.close();
  110. }
  111. },
  112. /// Close the current opened popup.
  113. close: function() {
  114. if (this.isOpen()) {
  115. Blaze.remove(this.current);
  116. this.current = null;
  117. var openerElement = this._getTopStack().openerElement;
  118. $(openerElement).removeClass('is-active');
  119. this._stack = [];
  120. }
  121. },
  122. // The template we use for every popup
  123. template: Template.popup,
  124. // We only want to display one popup at a time and we keep the view object in
  125. // this `Popup._current` variable. If there is no popup currently opened the
  126. // value is `null`.
  127. _current: null,
  128. // It's possible to open a sub-popup B from a popup A. In that case we keep
  129. // the data of popup A so we can return back to it. Every time we open a new
  130. // popup the stack grows, every time we go back the stack decrease, and if we
  131. // close the popup the stack is reseted to the empty stack [].
  132. _stack: [],
  133. // We invalidate this internal dependency every time the top of the stack has
  134. // changed and we want to render a popup with the new top-stack data.
  135. _dep: new Tracker.Dependency(),
  136. // An utility fonction that returns the top element of the internal stack
  137. _getTopStack: function() {
  138. return this._stack[this._stack.length - 1];
  139. },
  140. // We automatically calculate the popup offset from the reference element
  141. // position and dimensions. We also reactively use the window dimensions to
  142. // ensure that the popup is always visible on the screen.
  143. _getOffset: function(element) {
  144. var $element = $(element);
  145. return function() {
  146. windowResizeDep.depend();
  147. var offset = $element.offset();
  148. var popupWidth = 300 + 15;
  149. return {
  150. left: Math.min(offset.left, $(window).width() - popupWidth),
  151. top: offset.top + $element.outerHeight()
  152. };
  153. };
  154. },
  155. // We get the title from the translation files. Instead of returning the
  156. // result, we return a function that compute the result and since `TAPi18n.__`
  157. // is a reactive data source, the title will be changed reactively.
  158. _getTitle: function(popupName) {
  159. return function() {
  160. var translationKey = popupName + '-title';
  161. // XXX There is no public API to check if there is an available
  162. // translation for a given key. So we try to translate the key and if the
  163. // translation output equals the key input we deduce that no translation
  164. // was available and returns `false`. There is a (small) risk a false
  165. // positives.
  166. var title = TAPi18n.__(translationKey);
  167. return title !== translationKey ? title : false;
  168. };
  169. }
  170. };
  171. // We close a potential opened popup on any left click on the document, or go
  172. // one step back by pressing escape.
  173. EscapeActions.register('popup',
  174. function(evt) { Popup[evt.type === 'click' ? 'close' : 'back'](); },
  175. _.bind(Popup.isOpen, Popup), {
  176. noClickEscapeOn: '.js-pop-over'
  177. }
  178. );