popup.js 7.3 KB

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