popup.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. // return the the complete along with its top element and depends on our
  54. // internal dependency that is being invalidated every time the top
  55. // element of the 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 _.extend(self._stack[self._stack.length - 1], {
  64. stack: self._stack,
  65. containerTranslation: (self._stack.length - 1) * -300
  66. });
  67. }, document.body);
  68. } else {
  69. self._dep.changed();
  70. }
  71. };
  72. },
  73. /// This function returns a callback that can be used in an event map:
  74. ///
  75. /// Template.tplName.events({
  76. /// 'click .elementClass': Popup.afterConfirm("popupName", function() {
  77. /// // What to do after the user has confirmed the action
  78. /// })
  79. /// });
  80. afterConfirm: function(name, action) {
  81. var self = this;
  82. return function(evt, tpl) {
  83. var context = this;
  84. context.__afterConfirmAction = action;
  85. self.open(name).call(context, evt, tpl);
  86. };
  87. },
  88. /// The public reactive state of the popup.
  89. isOpen: function() {
  90. this._dep.changed();
  91. return !! this.current;
  92. },
  93. /// In case the popup was opened from a parent popup we can get back to it
  94. /// with this `Popup.back()` function. You can go back several steps at once
  95. /// by providing a number to this function, e.g. `Popup.back(2)`. In this case
  96. /// intermediate popup won't even be rendered on the DOM. If the number of
  97. /// steps back is greater than the popup stack size, the popup will be closed.
  98. back: function(n) {
  99. n = n || 1;
  100. var self = this;
  101. if (self._stack.length > n) {
  102. _.times(n, function() { self._stack.pop(); });
  103. self._dep.changed();
  104. } else {
  105. self.close();
  106. }
  107. },
  108. /// Close the current opened popup.
  109. close: function() {
  110. if (this.isOpen()) {
  111. Blaze.remove(this.current);
  112. this.current = null;
  113. this._stack = [];
  114. }
  115. },
  116. // The template we use for every popup
  117. template: Template.popup,
  118. // We only want to display one popup at a time and we keep the view object in
  119. // this `Popup._current` variable. If there is no popup currently opened the
  120. // value is `null`.
  121. _current: null,
  122. // It's possible to open a sub-popup B from a popup A. In that case we keep
  123. // the data of popup A so we can return back to it. Every time we open a new
  124. // popup the stack grows, every time we go back the stack decrease, and if we
  125. // close the popup the stack is reseted to the empty stack [].
  126. _stack: [],
  127. // We invalidate this internal dependency every time the top of the stack has
  128. // changed and we want to render a popup with the new top-stack data.
  129. _dep: new Tracker.Dependency(),
  130. // An utility fonction that returns the top element of the internal stack
  131. _getTopStack: function() {
  132. return this._stack[this._stack.length - 1];
  133. },
  134. // We use the blaze API to determine if the current popup has been opened from
  135. // a parent popup. The number we give to the `Template.parentData` has been
  136. // determined experimentally and is susceptible to change if you modify the
  137. // `Popup.template`
  138. _hasPopupParent: function() {
  139. var tryParentData = Template.parentData(3);
  140. return !! (tryParentData && tryParentData.__isPopup);
  141. },
  142. // We automatically calculate the popup offset from the reference element
  143. // position and dimensions. We also reactively use the window dimensions to
  144. // ensure that the popup is always visible on the screen.
  145. _getOffset: function(element) {
  146. var $element = $(element);
  147. return function() {
  148. windowResizeDep.depend();
  149. var offset = $element.offset();
  150. var popupWidth = 300 + 15;
  151. return {
  152. left: Math.min(offset.left, $(window).width() - popupWidth),
  153. top: offset.top + $element.outerHeight()
  154. };
  155. };
  156. },
  157. // We get the title from the translation files. Instead of returning the
  158. // result, we return a function that compute the result and since `TAPi18n.__`
  159. // is a reactive data source, the title will be changed reactively.
  160. _getTitle: function(popupName) {
  161. return function() {
  162. var translationKey = popupName + '-title';
  163. // XXX There is no public API to check if there is an available
  164. // translation for a given key. So we try to translate the key and if the
  165. // translation output equals the key input we deduce that no translation
  166. // was available and returns `false`. There is a (small) risk a false
  167. // positives.
  168. var title = TAPi18n.__(translationKey);
  169. return title !== translationKey ? title : false;
  170. };
  171. }
  172. };
  173. // We automatically close a potential opened popup on any left click on the
  174. // document. To avoid closing it unexpectedly we modify the bubbled event in
  175. // case the click event happen in the popup or in a button that open a popup.
  176. $(document).on('click', function(evt) {
  177. if (evt.which === 1 && ! (evt.originalEvent &&
  178. evt.originalEvent.clickInPopup)) {
  179. Popup.close();
  180. }
  181. });
  182. // Press escape to close the popup.
  183. var bindPopup = function(f) { return _.bind(f, Popup); };
  184. EscapeActions.register('popup',
  185. bindPopup(Popup.isOpen),
  186. bindPopup(Popup.close)
  187. );