debian-mirror-gitlab/app/assets/javascripts/behaviors/quick_submit.js

78 lines
2 KiB
JavaScript
Raw Normal View History

2018-05-09 12:01:36 +05:30
import $ from 'jquery';
2017-08-17 22:00:37 +05:30
import '../commons/bootstrap';
2018-03-17 18:26:18 +05:30
import { isInIssuePage } from '../lib/utils/common_utils';
2017-08-17 22:00:37 +05:30
2016-09-29 09:46:39 +05:30
// 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>
//
2016-09-13 17:45:13 +05:30
2017-08-17 22:00:37 +05:30
function isMac() {
return navigator.userAgent.match(/Macintosh/);
}
2016-09-13 17:45:13 +05:30
2017-08-17 22:00:37 +05:30
function keyCodeIs(e, keyCode) {
if ((e.originalEvent && e.originalEvent.repeat) || e.repeat) {
return false;
}
return e.keyCode === keyCode;
}
2016-09-13 17:45:13 +05:30
2017-08-17 22:00:37 +05:30
$(document).on('keydown.quick_submit', '.js-quick-submit', (e) => {
// Enter
if (!keyCodeIs(e, 13)) {
return;
}
2016-09-13 17:45:13 +05:30
2017-08-17 22:00:37 +05:30
const onlyMeta = e.metaKey && !e.altKey && !e.ctrlKey && !e.shiftKey;
const onlyCtrl = e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey;
if (!onlyMeta && !onlyCtrl) {
return;
}
2016-09-13 17:45:13 +05:30
2017-08-17 22:00:37 +05:30
e.preventDefault();
const $form = $(e.target).closest('form');
2017-09-10 17:25:29 +05:30
const $submitButton = $form.find('input[type=submit], button[type=submit]').first();
2017-08-17 22:00:37 +05:30
2018-03-27 19:54:05 +05:30
if (!$submitButton.prop('disabled')) {
2017-08-17 22:00:37 +05:30
$submitButton.trigger('click', [e]);
2018-03-17 18:26:18 +05:30
if (!isInIssuePage()) {
$submitButton.disable();
}
2017-08-17 22:00:37 +05:30
}
});
// 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';
$this.tooltip({
container: 'body',
html: 'true',
placement: 'auto top',
title,
trigger: 'manual',
});
2018-05-09 12:01:36 +05:30
$this.tooltip('show').one('blur click', () => $this.tooltip('hide'));
2017-08-17 22:00:37 +05:30
});