popup.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import { TAPi18n } from '/imports/i18n';
  2. window.Popup = new (class {
  3. constructor() {
  4. // The template we use to render popups
  5. this.template = Template.popup;
  6. // We only want to display one popup at a time and we keep the view object
  7. // in this `Popup.current` variable. If there is no popup currently opened
  8. // the value is `null`.
  9. this.current = null;
  10. // It's possible to open a sub-popup B from a popup A. In that case we keep
  11. // the data of popup A so we can return back to it. Every time we open a new
  12. // popup the stack grows, every time we go back the stack decrease, and if
  13. // we close the popup the stack is reseted to the empty stack [].
  14. this._stack = [];
  15. // We invalidate this internal dependency every time the top of the stack
  16. // has changed and we want to re-render a popup with the new top-stack data.
  17. this._dep = new Tracker.Dependency();
  18. }
  19. /// This function returns a callback that can be used in an event map:
  20. /// Template.tplName.events({
  21. /// 'click .elementClass': Popup.open("popupName"),
  22. /// });
  23. /// The popup inherit the data context of its parent.
  24. open(name) {
  25. const self = this;
  26. const popupName = `${name}Popup`;
  27. function clickFromPopup(evt) {
  28. return $(evt.target).closest('.js-pop-over').length !== 0;
  29. }
  30. /** opens the popup
  31. * @param evt the current event
  32. * @param options options (dataContextIfCurrentDataIsUndefined use this dataContext if this.currentData() is undefined)
  33. */
  34. return function(evt, options) {
  35. // If a popup is already opened, clicking again on the opener element
  36. // should close it -- and interrupt the current `open` function.
  37. if (self.isOpen()) {
  38. const previousOpenerElement = self._getTopStack().openerElement;
  39. if (previousOpenerElement === evt.currentTarget) {
  40. self.close();
  41. return;
  42. } else {
  43. $(previousOpenerElement).removeClass('is-active');
  44. // Clean up previous popup content to prevent mixing
  45. self._cleanupPreviousPopupContent();
  46. }
  47. }
  48. // We determine the `openerElement` (the DOM element that is being clicked
  49. // and the one we take in reference to position the popup) from the event
  50. // if the popup has no parent, or from the parent `openerElement` if it
  51. // has one. This allows us to position a sub-popup exactly at the same
  52. // position than its parent.
  53. let openerElement;
  54. if (clickFromPopup(evt) && self._getTopStack()) {
  55. openerElement = self._getTopStack().openerElement;
  56. } else {
  57. // For Member Settings sub-popups, always start fresh to avoid content mixing
  58. if (popupName.includes('changeLanguage') || popupName.includes('changeAvatar') ||
  59. popupName.includes('editProfile') || popupName.includes('changePassword') ||
  60. popupName.includes('invitePeople') || popupName.includes('support')) {
  61. self._stack = [];
  62. }
  63. openerElement = evt.currentTarget;
  64. }
  65. $(openerElement).addClass('is-active');
  66. evt.preventDefault();
  67. // We push our popup data to the stack. The top of the stack is always
  68. // used as the data source for our current popup.
  69. self._stack.push({
  70. popupName,
  71. openerElement,
  72. hasPopupParent: clickFromPopup(evt),
  73. title: self._getTitle(popupName),
  74. depth: self._stack.length,
  75. offset: self._getOffset(openerElement),
  76. dataContext: (this && this.currentData && this.currentData()) || (options && options.dataContextIfCurrentDataIsUndefined) || this,
  77. });
  78. const $contentWrapper = $('.content-wrapper')
  79. if ($contentWrapper.length > 0) {
  80. const contentWrapper = $contentWrapper[0];
  81. self._getTopStack().scrollTop = contentWrapper.scrollTop;
  82. // scroll from e.g. delete comment to the top (where the confirm button is)
  83. $contentWrapper.scrollTop(0);
  84. }
  85. // If there are no popup currently opened we use the Blaze API to render
  86. // one into the DOM. We use a reactive function as the data parameter that
  87. // return the complete along with its top element and depends on our
  88. // internal dependency that is being invalidated every time the top
  89. // element of the stack has changed and we want to update the popup.
  90. //
  91. // Otherwise if there is already a popup open we just need to invalidate
  92. // our internal dependency, and since we just changed the top element of
  93. // our internal stack, the popup will be updated with the new data.
  94. if (!self.isOpen()) {
  95. self.current = Blaze.renderWithData(
  96. self.template,
  97. () => {
  98. self._dep.depend();
  99. return { ...self._getTopStack(), stack: self._stack };
  100. },
  101. document.body,
  102. );
  103. } else {
  104. self._dep.changed();
  105. }
  106. };
  107. }
  108. /// This function returns a callback that can be used in an event map:
  109. /// Template.tplName.events({
  110. /// 'click .elementClass': Popup.afterConfirm("popupName", function() {
  111. /// // What to do after the user has confirmed the action
  112. /// }),
  113. /// });
  114. afterConfirm(name, action) {
  115. const self = this;
  116. return function(evt, tpl) {
  117. const context = (this.currentData && this.currentData()) || this;
  118. context.__afterConfirmAction = action;
  119. self.open(name).call(context, evt, tpl);
  120. };
  121. }
  122. /// The public reactive state of the popup.
  123. isOpen() {
  124. this._dep.changed();
  125. return Boolean(this.current);
  126. }
  127. /// In case the popup was opened from a parent popup we can get back to it
  128. /// with this `Popup.back()` function. You can go back several steps at once
  129. /// by providing a number to this function, e.g. `Popup.back(2)`. In this case
  130. /// intermediate popup won't even be rendered on the DOM. If the number of
  131. /// steps back is greater than the popup stack size, the popup will be closed.
  132. back(n = 1) {
  133. if (this._stack.length > n) {
  134. const $contentWrapper = $('.content-wrapper')
  135. if ($contentWrapper.length > 0) {
  136. const contentWrapper = $contentWrapper[0];
  137. const stack = this._stack[this._stack.length - n];
  138. // scrollTopMax and scrollLeftMax only available at Firefox (https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTopMax)
  139. const scrollTopMax = contentWrapper.scrollTopMax || contentWrapper.scrollHeight - contentWrapper.clientHeight;
  140. if (scrollTopMax && stack.scrollTop > scrollTopMax) {
  141. // sometimes scrollTopMax is lower than scrollTop, so i need this dirty hack
  142. setTimeout(() => {
  143. $contentWrapper.scrollTop(stack.scrollTop);
  144. }, 6);
  145. }
  146. // restore the old popup scroll position
  147. $contentWrapper.scrollTop(stack.scrollTop);
  148. }
  149. _.times(n, () => this._stack.pop());
  150. this._dep.changed();
  151. } else {
  152. this.close();
  153. }
  154. }
  155. /// Close the current opened popup.
  156. close() {
  157. if (this.isOpen()) {
  158. Blaze.remove(this.current);
  159. this.current = null;
  160. const openerElement = this._getTopStack().openerElement;
  161. $(openerElement).removeClass('is-active');
  162. this._stack = [];
  163. // Clean up popup content when closing
  164. this._cleanupPreviousPopupContent();
  165. }
  166. }
  167. getOpenerComponent(n=4) {
  168. const { openerElement } = Template.parentData(n);
  169. return BlazeComponent.getComponentForElement(openerElement);
  170. }
  171. // An utility function that returns the top element of the internal stack
  172. _getTopStack() {
  173. return this._stack[this._stack.length - 1];
  174. }
  175. _cleanupPreviousPopupContent() {
  176. // Force a re-render to ensure proper cleanup
  177. if (this._dep) {
  178. this._dep.changed();
  179. }
  180. }
  181. // We automatically calculate the popup offset from the reference element
  182. // position and dimensions. We also reactively use the window dimensions to
  183. // ensure that the popup is always visible on the screen.
  184. _getOffset(element) {
  185. const $element = $(element);
  186. return () => {
  187. Utils.windowResizeDep.depend();
  188. if (Utils.isMiniScreen()) return { left: 0, top: 0 };
  189. const offset = $element.offset();
  190. const popupWidth = 300 + 15;
  191. return {
  192. left: Math.min(offset.left, $(window).width() - popupWidth),
  193. top: offset.top + $element.outerHeight(),
  194. };
  195. };
  196. }
  197. // We get the title from the translation files. Instead of returning the
  198. // result, we return a function that compute the result and since `TAPi18n.__`
  199. // is a reactive data source, the title will be changed reactively.
  200. _getTitle(popupName) {
  201. return () => {
  202. const translationKey = `${popupName}-title`;
  203. // XXX There is no public API to check if there is an available
  204. // translation for a given key. So we try to translate the key and if the
  205. // translation output equals the key input we deduce that no translation
  206. // was available and returns `false`. There is a (small) risk a false
  207. // positives.
  208. const title = TAPi18n.__(translationKey);
  209. // when popup showed as full of small screen, we need a default header to clearly see [X] button
  210. const defaultTitle = Utils.isMiniScreen() ? '' : false;
  211. return title !== translationKey ? title : defaultTitle;
  212. };
  213. }
  214. })();
  215. // We close a potential opened popup on any left click on the document, or go
  216. // one step back by pressing escape.
  217. const escapeActions = ['back', 'close'];
  218. escapeActions.forEach(actionName => {
  219. EscapeActions.register(
  220. `popup-${actionName}`,
  221. () => Popup[actionName](),
  222. () => Popup.isOpen(),
  223. {
  224. noClickEscapeOn: '.js-pop-over,.js-open-card-title-popup,.js-open-inlined-form',
  225. enabledOnClick: actionName === 'close',
  226. },
  227. );
  228. });