2
0

popup.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. // 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 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(
  82. self.template,
  83. () => {
  84. self._dep.depend();
  85. return { ...self._getTopStack(), stack: self._stack };
  86. },
  87. document.body,
  88. );
  89. } else {
  90. self._dep.changed();
  91. }
  92. };
  93. }
  94. /// This function returns a callback that can be used in an event map:
  95. /// Template.tplName.events({
  96. /// 'click .elementClass': Popup.afterConfirm("popupName", function() {
  97. /// // What to do after the user has confirmed the action
  98. /// }),
  99. /// });
  100. afterConfirm(name, action) {
  101. const self = this;
  102. return function(evt, tpl) {
  103. const context = (this.currentData && this.currentData()) || this;
  104. context.__afterConfirmAction = action;
  105. self.open(name).call(context, evt, tpl);
  106. };
  107. }
  108. /// The public reactive state of the popup.
  109. isOpen() {
  110. this._dep.changed();
  111. return Boolean(this.current);
  112. }
  113. /// In case the popup was opened from a parent popup we can get back to it
  114. /// with this `Popup.back()` function. You can go back several steps at once
  115. /// by providing a number to this function, e.g. `Popup.back(2)`. In this case
  116. /// intermediate popup won't even be rendered on the DOM. If the number of
  117. /// steps back is greater than the popup stack size, the popup will be closed.
  118. back(n = 1) {
  119. if (this._stack.length > n) {
  120. _.times(n, () => this._stack.pop());
  121. this._dep.changed();
  122. } else {
  123. this.close();
  124. }
  125. }
  126. /// Close the current opened popup.
  127. close() {
  128. if (this.isOpen()) {
  129. Blaze.remove(this.current);
  130. this.current = null;
  131. const openerElement = this._getTopStack().openerElement;
  132. $(openerElement).removeClass('is-active');
  133. this._stack = [];
  134. }
  135. }
  136. getOpenerComponent() {
  137. const { openerElement } = Template.parentData(4);
  138. return BlazeComponent.getComponentForElement(openerElement);
  139. }
  140. // An utility fonction that returns the top element of the internal stack
  141. _getTopStack() {
  142. return this._stack[this._stack.length - 1];
  143. }
  144. // We automatically calculate the popup offset from the reference element
  145. // position and dimensions. We also reactively use the window dimensions to
  146. // ensure that the popup is always visible on the screen.
  147. _getOffset(element) {
  148. const $element = $(element);
  149. return () => {
  150. Utils.windowResizeDep.depend();
  151. if (Utils.isMiniScreen()) return { left: 0, top: 0 };
  152. const offset = $element.offset();
  153. const popupWidth = 300 + 15;
  154. return {
  155. left: Math.min(offset.left, $(window).width() - popupWidth),
  156. top: offset.top + $element.outerHeight(),
  157. };
  158. };
  159. }
  160. // We get the title from the translation files. Instead of returning the
  161. // result, we return a function that compute the result and since `TAPi18n.__`
  162. // is a reactive data source, the title will be changed reactively.
  163. _getTitle(popupName) {
  164. return () => {
  165. const translationKey = `${popupName}-title`;
  166. // XXX There is no public API to check if there is an available
  167. // translation for a given key. So we try to translate the key and if the
  168. // translation output equals the key input we deduce that no translation
  169. // was available and returns `false`. There is a (small) risk a false
  170. // positives.
  171. const title = TAPi18n.__(translationKey);
  172. // when popup showed as full of small screen, we need a default header to clearly see [X] button
  173. const defaultTitle = Utils.isMiniScreen() ? '' : false;
  174. return title !== translationKey ? title : defaultTitle;
  175. };
  176. }
  177. })();
  178. // We close a potential opened popup on any left click on the document, or go
  179. // one step back by pressing escape.
  180. const escapeActions = ['back', 'close'];
  181. escapeActions.forEach(actionName => {
  182. EscapeActions.register(
  183. `popup-${actionName}`,
  184. () => Popup[actionName](),
  185. () => Popup.isOpen(),
  186. {
  187. noClickEscapeOn: '.js-pop-over,.js-open-card-title-popup,.js-open-inlined-form',
  188. enabledOnClick: actionName === 'close',
  189. },
  190. );
  191. });