summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/behaviors/quick_submit.js
blob: 626f3503c915bbe6f90b32d9fdaaffa490c81ed1 (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
/* eslint-disable func-names, space-before-function-paren, one-var, no-var, one-var-declaration-per-line, prefer-arrow-callback, camelcase, consistent-return, quotes, object-shorthand, comma-dangle, max-len */

// Quick Submit behavior
//
// When a child field of a form with a `js-quick-submit` class receives a
// "Meta+Enter" (Mac) or "Ctrl+Enter" (Linux/Windows) key combination, the form
// is submitted.
//
import '../commons/bootstrap';

//
// ### Example Markup
//
//   <form action="/foo" class="js-quick-submit">
//     <input type="text" />
//     <textarea></textarea>
//     <input type="submit" value="Submit" />
//   </form>
//
(function() {
  var isMac, keyCodeIs;

  isMac = function() {
    return navigator.userAgent.match(/Macintosh/);
  };

  keyCodeIs = function(e, keyCode) {
    if ((e.originalEvent && e.originalEvent.repeat) || e.repeat) {
      return false;
    }
    return e.keyCode === keyCode;
  };

  $(document).on('keydown.quick_submit', '.js-quick-submit', function(e) {
    var $form, $submit_button;
    // Enter
    if (!keyCodeIs(e, 13)) {
      return;
    }
    if (!((e.metaKey && !e.altKey && !e.ctrlKey && !e.shiftKey) || (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey))) {
      return;
    }
    e.preventDefault();
    $form = $(e.target).closest('form');
    $submit_button = $form.find('input[type=submit], button[type=submit]');
    if ($submit_button.attr('disabled')) {
      return;
    }
    $submit_button.disable();
    return $form.submit();
  });

  // If the user tabs to a submit button on a `js-quick-submit` form, display a
  // tooltip to let them know they could've used the hotkey
  $(document).on('keyup.quick_submit', '.js-quick-submit input[type=submit], .js-quick-submit button[type=submit]', function(e) {
    var $this, title;
    // Tab
    if (!keyCodeIs(e, 9)) {
      return;
    }
    if (isMac()) {
      title = "You can also press &#8984;-Enter";
    } else {
      title = "You can also press Ctrl-Enter";
    }
    $this = $(this);
    return $this.tooltip({
      container: 'body',
      html: 'true',
      placement: 'auto top',
      title: title,
      trigger: 'manual'
    }).tooltip('show').one('blur', function() {
      return $this.tooltip('hide');
    });
  });
}).call(window);