summaryrefslogtreecommitdiffstats
path: root/client/lib/popup.js
blob: 8a55c2df20918ad2cc21366f9d6300800abbcfce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
window.Popup = new (class {
  constructor() {
    // The template we use to render popups
    this.template = Template.popup;

    // We only want to display one popup at a time and we keep the view object
    // in this `Popup.current` variable. If there is no popup currently opened
    // the value is `null`.
    this.current = null;

    // It's possible to open a sub-popup B from a popup A. In that case we keep
    // the data of popup A so we can return back to it. Every time we open a new
    // popup the stack grows, every time we go back the stack decrease, and if
    // we close the popup the stack is reseted to the empty stack [].
    this._stack = [];

    // We invalidate this internal dependency every time the top of the stack
    // has changed and we want to re-render a popup with the new top-stack data.
    this._dep = new Tracker.Dependency();
  }

  /// This function returns a callback that can be used in an event map:
  ///   Template.tplName.events({
  ///     'click .elementClass': Popup.open("popupName"),
  ///   });
  /// The popup inherit the data context of its parent.
  open(name) {
    const self = this;
    const popupName = `${name}Popup`;
    function clickFromPopup(evt) {
      return $(evt.target).closest('.js-pop-over').length !== 0;
    }
    return function(evt) {
      // If a popup is already opened, clicking again on the opener element
      // should close it -- and interrupt the current `open` function.
      if (self.isOpen()) {
        const previousOpenerElement = self._getTopStack().openerElement;
        if (previousOpenerElement === evt.currentTarget) {
          self.close();
          return;
        } else {
          $(previousOpenerElement).removeClass('is-active');
        }
      }

      // We determine the `openerElement` (the DOM element that is being clicked
      // and the one we take in reference to position the popup) from the event
      // if the popup has no parent, or from the parent `openerElement` if it
      // has one. This allows us to position a sub-popup exactly at the same
      // position than its parent.
      let openerElement;
      if (clickFromPopup(evt)) {
        openerElement = self._getTopStack().openerElement;
      } else {
        self._stack = [];
        openerElement = evt.currentTarget;
      }
      $(openerElement).addClass('is-active');
      evt.preventDefault();

      // We push our popup data to the stack. The top of the stack is always
      // used as the data source for our current popup.
      self._stack.push({
        popupName,
        openerElement,
        hasPopupParent: clickFromPopup(evt),
        title: self._getTitle(popupName),
        depth: self._stack.length,
        offset: self._getOffset(openerElement),
        dataContext: (this && this.currentData && this.currentData()) || this,
      });

      // If there are no popup currently opened we use the Blaze API to render
      // one into the DOM. We use a reactive function as the data parameter that
      // return the complete along with its top element and depends on our
      // internal dependency that is being invalidated every time the top
      // element of the stack has changed and we want to update the popup.
      //
      // Otherwise if there is already a popup open we just need to invalidate
      // our internal dependency, and since we just changed the top element of
      // our internal stack, the popup will be updated with the new data.
      if (!self.isOpen()) {
        self.current = Blaze.renderWithData(
          self.template,
          () => {
            self._dep.depend();
            return { ...self._getTopStack(), stack: self._stack };
          },
          document.body,
        );
      } else {
        self._dep.changed();
      }
    };
  }

  /// This function returns a callback that can be used in an event map:
  ///   Template.tplName.events({
  ///     'click .elementClass': Popup.afterConfirm("popupName", function() {
  ///       // What to do after the user has confirmed the action
  ///     }),
  ///   });
  afterConfirm(name, action) {
    const self = this;

    return function(evt, tpl) {
      const context = (this.currentData && this.currentData()) || this;
      context.__afterConfirmAction = action;
      self.open(name).call(context, evt, tpl);
    };
  }

  /// The public reactive state of the popup.
  isOpen() {
    this._dep.changed();
    return Boolean(this.current);
  }

  /// In case the popup was opened from a parent popup we can get back to it
  /// with this `Popup.back()` function. You can go back several steps at once
  /// by providing a number to this function, e.g. `Popup.back(2)`. In this case
  /// intermediate popup won't even be rendered on the DOM. If the number of
  /// steps back is greater than the popup stack size, the popup will be closed.
  back(n = 1) {
    if (this._stack.length > n) {
      _.times(n, () => this._stack.pop());
      this._dep.changed();
    } else {
      this.close();
    }
  }

  /// Close the current opened popup.
  close() {
    if (this.isOpen()) {
      Blaze.remove(this.current);
      this.current = null;

      const openerElement = this._getTopStack().openerElement;
      $(openerElement).removeClass('is-active');

      this._stack = [];
    }
  }

  getOpenerComponent() {
    const { openerElement } = Template.parentData(4);
    return BlazeComponent.getComponentForElement(openerElement);
  }

  // An utility fonction that returns the top element of the internal stack
  _getTopStack() {
    return this._stack[this._stack.length - 1];
  }

  // We automatically calculate the popup offset from the reference element
  // position and dimensions. We also reactively use the window dimensions to
  // ensure that the popup is always visible on the screen.
  _getOffset(element) {
    const $element = $(element);
    return () => {
      Utils.windowResizeDep.depend();

      if (Utils.isMiniScreen()) return { left: 0, top: 0 };

      const offset = $element.offset();
      const popupWidth = 300 + 15;
      return {
        left: Math.min(offset.left, $(window).width() - popupWidth),
        top: offset.top + $element.outerHeight(),
      };
    };
  }

  // We get the title from the translation files. Instead of returning the
  // result, we return a function that compute the result and since `TAPi18n.__`
  // is a reactive data source, the title will be changed reactively.
  _getTitle(popupName) {
    return () => {
      const translationKey = `${popupName}-title`;

      // XXX There is no public API to check if there is an available
      // translation for a given key. So we try to translate the key and if the
      // translation output equals the key input we deduce that no translation
      // was available and returns `false`. There is a (small) risk a false
      // positives.
      const title = TAPi18n.__(translationKey);
      // when popup showed as full of small screen, we need a default header to clearly see [X] button
      const defaultTitle = Utils.isMiniScreen() ? '' : false;
      return title !== translationKey ? title : defaultTitle;
    };
  }
})();

// We close a potential opened popup on any left click on the document, or go
// one step back by pressing escape.
const escapeActions = ['back', 'close'];
escapeActions.forEach(actionName => {
  EscapeActions.register(
    `popup-${actionName}`,
    () => Popup[actionName](),
    () => Popup.isOpen(),
    {
      noClickEscapeOn: '.js-pop-over,.js-open-card-title-popup',
      enabledOnClick: actionName === 'close',
    },
  );
});

// Prevent @member mentions on Add Comment input field
// from closing card, part 5.
// This duplicate below of above popup function is needed, because at
// wekan/components/main/editor.js at bottom is popping up visible
// @member mention, and it seems to trigger closing also card popup,
// so in below closing popup is disabled.
window.PopupNoClose = new (class {
  constructor() {
    // The template we use to render popups
    this.template = Template.popup;

    // We only want to display one popup at a time and we keep the view object
    // in this `Popup.current` variable. If there is no popup currently opened
    // the value is `null`.
    this.current = null;

    // It's possible to open a sub-popup B from a popup A. In that case we keep
    // the data of popup A so we can return back to it. Every time we open a new
    // popup the stack grows, every time we go back the stack decrease, and if
    // we close the popup the stack is reseted to the empty stack [].
    this._stack = [];

    // We invalidate this internal dependency every time the top of the stack
    // has changed and we want to re-render a popup with the new top-stack data.
    this._dep = new Tracker.Dependency();
  }

  /// This function returns a callback that can be used in an event map:
  ///   Template.tplName.events({
  ///     'click .elementClass': Popup.open("popupName"),
  ///   });
  /// The popup inherit the data context of its parent.
  open(name) {
    const self = this;
    const popupName = `${name}Popup`;
    function clickFromPopup(evt) {
      return $(evt.target).closest('.js-pop-over').length !== 0;
    }
    return function(evt) {
      // If a popup is already opened, clicking again on the opener element
      // should close it -- and interrupt the current `open` function.
      /*
      if (self.isOpen()) {
        const previousOpenerElement = self._getTopStack().openerElement;
        if (previousOpenerElement === evt.currentTarget) {
          self.close();
          return;
        } else {
          $(previousOpenerElement).removeClass('is-active');
        }
      }
      */
      // We determine the `openerElement` (the DOM element that is being clicked
      // and the one we take in reference to position the popup) from the event
      // if the popup has no parent, or from the parent `openerElement` if it
      // has one. This allows us to position a sub-popup exactly at the same
      // position than its parent.
      let openerElement;
      if (clickFromPopup(evt)) {
        openerElement = self._getTopStack().openerElement;
      } else {
        self._stack = [];
        openerElement = evt.currentTarget;
      }
      $(openerElement).addClass('is-active');
      evt.preventDefault();

      // We push our popup data to the stack. The top of the stack is always
      // used as the data source for our current popup.
      self._stack.push({
        popupName,
        openerElement,
        hasPopupParent: clickFromPopup(evt),
        title: self._getTitle(popupName),
        depth: self._stack.length,
        offset: self._getOffset(openerElement),
        dataContext: (this && this.currentData && this.currentData()) || this,
      });

      // If there are no popup currently opened we use the Blaze API to render
      // one into the DOM. We use a reactive function as the data parameter that
      // return the complete along with its top element and depends on our
      // internal dependency that is being invalidated every time the top
      // element of the stack has changed and we want to update the popup.
      //
      // Otherwise if there is already a popup open we just need to invalidate
      // our internal dependency, and since we just changed the top element of
      // our internal stack, the popup will be updated with the new data.
      if (!self.isOpen()) {
        self.current = Blaze.renderWithData(
          self.template,
          () => {
            self._dep.depend();
            return { ...self._getTopStack(), stack: self._stack };
          },
          document.body,
        );
      } else {
        self._dep.changed();
      }
    };
  }

  /// This function returns a callback that can be used in an event map:
  ///   Template.tplName.events({
  ///     'click .elementClass': Popup.afterConfirm("popupName", function() {
  ///       // What to do after the user has confirmed the action
  ///     }),
  ///   });
  afterConfirm(name, action) {
    const self = this;

    return function(evt, tpl) {
      const context = (this.currentData && this.currentData()) || this;
      context.__afterConfirmAction = action;
      self.open(name).call(context, evt, tpl);
    };
  }

  /// The public reactive state of the popup.
  isOpen() {
    this._dep.changed();
    return Boolean(this.current);
  }

  /// In case the popup was opened from a parent popup we can get back to it
  /// with this `Popup.back()` function. You can go back several steps at once
  /// by providing a number to this function, e.g. `Popup.back(2)`. In this case
  /// intermediate popup won't even be rendered on the DOM. If the number of
  /// steps back is greater than the popup stack size, the popup will be closed.
  back(n = 1) {
    if (this._stack.length > n) {
      _.times(n, () => this._stack.pop());
      this._dep.changed();
    }
    // else {
    //  this.close();
    //}
  }

  /// Close the current opened popup.
  /*
  close() {
    if (this.isOpen()) {
      Blaze.remove(this.current);
      this.current = null;

      const openerElement = this._getTopStack().openerElement;
      $(openerElement).removeClass('is-active');

      this._stack = [];
    }
  }
  */

  getOpenerComponent() {
    const { openerElement } = Template.parentData(4);
    return BlazeComponent.getComponentForElement(openerElement);
  }

  // An utility fonction that returns the top element of the internal stack
  _getTopStack() {
    return this._stack[this._stack.length - 1];
  }

  // We automatically calculate the popup offset from the reference element
  // position and dimensions. We also reactively use the window dimensions to
  // ensure that the popup is always visible on the screen.
  _getOffset(element) {
    const $element = $(element);
    return () => {
      Utils.windowResizeDep.depend();

      if (Utils.isMiniScreen()) return { left: 0, top: 0 };

      const offset = $element.offset();
      const popupWidth = 300 + 15;
      return {
        left: Math.min(offset.left, $(window).width() - popupWidth),
        top: offset.top + $element.outerHeight(),
      };
    };
  }

  // We get the title from the translation files. Instead of returning the
  // result, we return a function that compute the result and since `TAPi18n.__`
  // is a reactive data source, the title will be changed reactively.
  _getTitle(popupName) {
    return () => {
      const translationKey = `${popupName}-title`;

      // XXX There is no public API to check if there is an available
      // translation for a given key. So we try to translate the key and if the
      // translation output equals the key input we deduce that no translation
      // was available and returns `false`. There is a (small) risk a false
      // positives.
      const title = TAPi18n.__(translationKey);
      // when popup showed as full of small screen, we need a default header to clearly see [X] button
      const defaultTitle = Utils.isMiniScreen() ? '' : false;
      return title !== translationKey ? title : defaultTitle;
    };
  }
})();