popup.js 7.6 KB

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