quick_submit.js 1.9 KB
Newer Older
1
import '../commons/bootstrap';
2

3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 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.
//
// ### Example Markup
//
//   <form action="/foo" class="js-quick-submit">
//     <input type="text" />
//     <textarea></textarea>
//     <input type="submit" value="Submit" />
//   </form>
//
Fatih Acet's avatar
Fatih Acet committed
17

18 19 20
function isMac() {
  return navigator.userAgent.match(/Macintosh/);
}
Fatih Acet's avatar
Fatih Acet committed
21

22 23 24 25 26 27
function keyCodeIs(e, keyCode) {
  if ((e.originalEvent && e.originalEvent.repeat) || e.repeat) {
    return false;
  }
  return e.keyCode === keyCode;
}
Fatih Acet's avatar
Fatih Acet committed
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42
$(document).on('keydown.quick_submit', '.js-quick-submit', (e) => {
  // Enter
  if (!keyCodeIs(e, 13)) {
    return;
  }

  const onlyMeta = e.metaKey && !e.altKey && !e.ctrlKey && !e.shiftKey;
  const onlyCtrl = e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey;
  if (!onlyMeta && !onlyCtrl) {
    return;
  }

  e.preventDefault();
  const $form = $(e.target).closest('form');
43
  const $submitButton = $form.find('input[type=submit], button[type=submit]').first();
44 45

  if (!$submitButton.attr('disabled')) {
46
    $submitButton.trigger('click', [e]);
47

48
    if (!gl.utils.isInIssuePage()) {
49 50
      $submitButton.disable();
    }
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  }
});

// 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 displayTooltip(e) {
  // Tab
  if (!keyCodeIs(e, 9)) {
    return;
  }

  const $this = $(this);
  const title = isMac() ?
    'You can also press &#8984;-Enter' :
    'You can also press Ctrl-Enter';
Fatih Acet's avatar
Fatih Acet committed
66

67 68 69 70 71 72
  $this.tooltip({
    container: 'body',
    html: 'true',
    placement: 'auto top',
    title,
    trigger: 'manual',
Fatih Acet's avatar
Fatih Acet committed
73
  });
74 75
  $this.tooltip('show').one('blur', () => $this.tooltip('hide'));
});