summaryrefslogtreecommitdiffstats
path: root/client/lib/inlinedform.js
blob: 56768a13b91fc97ea9ceb05ffe3b551e750d59e6 (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
// A inlined form is used to provide a quick edition of single field for a given
// document. Clicking on a edit button should display the form to edit the field
// value. The form can then be submited, or just closed.
//
// When the form is closed we save non-submitted values in memory to avoid any
// data loss.
//
// Usage:
//
//   +inlineForm
//     // the content when the form is open
//   else
//     // the content when the form is close (optional)

// We can only have one inlined form element opened at a time
const currentlyOpenedForm = new ReactiveVar(null);

InlinedForm = BlazeComponent.extendComponent({
  template() {
    return 'inlinedForm';
  },

  onCreated() {
    this.isOpen = new ReactiveVar(false);
  },

  onDestroyed() {
    currentlyOpenedForm.set(null);
  },

  open(evt) {
    evt && evt.preventDefault();

    // Close currently opened form, if any
    EscapeActions.executeUpTo('inlinedForm');
    this.isOpen.set(true);
    currentlyOpenedForm.set(this);
  },

  close() {
    this.isOpen.set(false);
    currentlyOpenedForm.set(null);
  },

  getValue() {
    const input = this.find('textarea,input[type=text]');
    return this.isOpen.get() && input && input.value;
  },

  events() {
    return [{
      'click .js-close-inlined-form': this.close,
      'click .js-open-inlined-form': this.open,

      // Pressing Ctrl+Enter should submit the form
      'keydown form textarea'(evt) {
        if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) {
          this.find('button[type=submit]').click();
        }
      },

      // Close the inlined form when after its submission
      submit() {
        if (this.currentData().autoclose !== false) {
          Tracker.afterFlush(() => {
            this.close();
          });
        }
      },
    }];
  },
}).register('inlinedForm');

// Press escape to close the currently opened inlinedForm
EscapeActions.register('inlinedForm',
  () => { currentlyOpenedForm.get().close(); },
  () => { return currentlyOpenedForm.get() !== null; }, {
    noClickEscapeOn: '.js-inlined-form',
  }
);