popup.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. }
  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) && self._getTopStack()) {
  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 && this.currentData && this.currentData()) || (options && options.dataContextIfCurrentDataIsUndefined) || this,
  70. });
  71. const $contentWrapper = $('.content-wrapper')
  72. if ($contentWrapper.length > 0) {
  73. const contentWrapper = $contentWrapper[0];
  74. self._getTopStack().scrollTop = contentWrapper.scrollTop;
  75. // scroll from e.g. delete comment to the top (where the confirm button is)
  76. $contentWrapper.scrollTop(0);
  77. }
  78. // If there are no popup currently opened we use the Blaze API to render
  79. // one into the DOM. We use a reactive function as the data parameter that
  80. // return the complete along with its top element and depends on our
  81. // internal dependency that is being invalidated every time the top
  82. // element of the stack has changed and we want to update the popup.
  83. //
  84. // Otherwise if there is already a popup open we just need to invalidate
  85. // our internal dependency, and since we just changed the top element of
  86. // our internal stack, the popup will be updated with the new data.
  87. if (!self.isOpen()) {
  88. self.current = Blaze.renderWithData(
  89. self.template,
  90. () => {
  91. self._dep.depend();
  92. return { ...self._getTopStack(), stack: self._stack };
  93. },
  94. document.body,
  95. );
  96. } else {
  97. self._dep.changed();
  98. }
  99. };
  100. }
  101. /// This function returns a callback that can be used in an event map:
  102. /// Template.tplName.events({
  103. /// 'click .elementClass': Popup.afterConfirm("popupName", function() {
  104. /// // What to do after the user has confirmed the action
  105. /// }),
  106. /// });
  107. afterConfirm(name, action) {
  108. const self = this;
  109. return function(evt, tpl) {
  110. const context = (this.currentData && this.currentData()) || this;
  111. context.__afterConfirmAction = action;
  112. self.open(name).call(context, evt, tpl);
  113. };
  114. }
  115. /// The public reactive state of the popup.
  116. isOpen() {
  117. this._dep.changed();
  118. return Boolean(this.current);
  119. }
  120. /// In case the popup was opened from a parent popup we can get back to it
  121. /// with this `Popup.back()` function. You can go back several steps at once
  122. /// by providing a number to this function, e.g. `Popup.back(2)`. In this case
  123. /// intermediate popup won't even be rendered on the DOM. If the number of
  124. /// steps back is greater than the popup stack size, the popup will be closed.
  125. back(n = 1) {
  126. if (this._stack.length > n) {
  127. const $contentWrapper = $('.content-wrapper')
  128. if ($contentWrapper.length > 0) {
  129. const contentWrapper = $contentWrapper[0];
  130. const stack = this._stack[this._stack.length - n];
  131. // scrollTopMax and scrollLeftMax only available at Firefox (https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTopMax)
  132. const scrollTopMax = contentWrapper.scrollTopMax || contentWrapper.scrollHeight - contentWrapper.clientHeight;
  133. if (scrollTopMax && stack.scrollTop > scrollTopMax) {
  134. // sometimes scrollTopMax is lower than scrollTop, so i need this dirty hack
  135. setTimeout(() => {
  136. $contentWrapper.scrollTop(stack.scrollTop);
  137. }, 6);
  138. }
  139. // restore the old popup scroll position
  140. $contentWrapper.scrollTop(stack.scrollTop);
  141. }
  142. _.times(n, () => this._stack.pop());
  143. this._dep.changed();
  144. } else {
  145. this.close();
  146. }
  147. }
  148. /// Close the current opened popup.
  149. close() {
  150. if (this.isOpen()) {
  151. Blaze.remove(this.current);
  152. this.current = null;
  153. const openerElement = this._getTopStack().openerElement;
  154. $(openerElement).removeClass('is-active');
  155. this._stack = [];
  156. }
  157. }
  158. getOpenerComponent(n=4) {
  159. const { openerElement } = Template.parentData(n);
  160. return BlazeComponent.getComponentForElement(openerElement);
  161. }
  162. // An utility function that returns the top element of the internal stack
  163. _getTopStack() {
  164. return this._stack[this._stack.length - 1];
  165. }
  166. // We automatically calculate the popup offset from the reference element
  167. // position and dimensions. We also reactively use the window dimensions to
  168. // ensure that the popup is always visible on the screen.
  169. _getOffset(element) {
  170. const $element = $(element);
  171. return () => {
  172. Utils.windowResizeDep.depend();
  173. if (Utils.isMiniScreen()) return { left: 0, top: 0 };
  174. const offset = $element.offset();
  175. const popupWidth = 300 + 15;
  176. return {
  177. left: Math.min(offset.left, $(window).width() - popupWidth),
  178. top: offset.top + $element.outerHeight(),
  179. };
  180. };
  181. }
  182. // We get the title from the translation files. Instead of returning the
  183. // result, we return a function that compute the result and since `TAPi18n.__`
  184. // is a reactive data source, the title will be changed reactively.
  185. _getTitle(popupName) {
  186. return () => {
  187. const translationKey = `${popupName}-title`;
  188. // XXX There is no public API to check if there is an available
  189. // translation for a given key. So we try to translate the key and if the
  190. // translation output equals the key input we deduce that no translation
  191. // was available and returns `false`. There is a (small) risk a false
  192. // positives.
  193. const title = TAPi18n.__(translationKey);
  194. // when popup showed as full of small screen, we need a default header to clearly see [X] button
  195. const defaultTitle = Utils.isMiniScreen() ? '' : false;
  196. return title !== translationKey ? title : defaultTitle;
  197. };
  198. }
  199. })();
  200. // We close a potential opened popup on any left click on the document, or go
  201. // one step back by pressing escape.
  202. const escapeActions = ['back', 'close'];
  203. escapeActions.forEach(actionName => {
  204. EscapeActions.register(
  205. `popup-${actionName}`,
  206. () => Popup[actionName](),
  207. () => Popup.isOpen(),
  208. {
  209. noClickEscapeOn: '.js-pop-over,.js-open-card-title-popup,.js-open-inlined-form',
  210. enabledOnClick: actionName === 'close',
  211. },
  212. );
  213. });