popup.js 7.4 KB

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