Commit 6ffd3489 authored by Filipa Lacerda's avatar Filipa Lacerda Committed by Phil Hughes

Remove dropzoneInput from global namespace

parent 00c15cc2
/* eslint-disable func-names, object-shorthand, prefer-arrow-callback */ /* eslint-disable func-names, object-shorthand, prefer-arrow-callback */
/* global Dropzone */ import Dropzone from 'dropzone';
import '../lib/utils/url_utility'; import '../lib/utils/url_utility';
import { HIDDEN_CLASS } from '../lib/utils/constants'; import { HIDDEN_CLASS } from '../lib/utils/constants';
import csrf from '../lib/utils/csrf'; import csrf from '../lib/utils/csrf';
......
/* eslint-disable func-names, space-before-function-paren, wrap-iife, max-len, one-var, no-var, one-var-declaration-per-line, no-unused-vars, camelcase, quotes, no-useless-concat, prefer-template, quote-props, comma-dangle, object-shorthand, consistent-return, prefer-arrow-callback */ import Dropzone from 'dropzone';
/* global Dropzone */
import _ from 'underscore'; import _ from 'underscore';
import './preview_markdown'; import './preview_markdown';
import csrf from './lib/utils/csrf'; import csrf from './lib/utils/csrf';
window.DropzoneInput = (function() { export default function dropzoneInput(form) {
function DropzoneInput(form) {
const divHover = '<div class="div-dropzone-hover"></div>'; const divHover = '<div class="div-dropzone-hover"></div>';
const iconPaperclip = '<i class="fa fa-paperclip div-dropzone-icon"></i>'; const iconPaperclip = '<i class="fa fa-paperclip div-dropzone-icon"></i>';
const $attachButton = form.find('.button-attach-file'); const $attachButton = form.find('.button-attach-file');
...@@ -28,11 +26,7 @@ window.DropzoneInput = (function() { ...@@ -28,11 +26,7 @@ window.DropzoneInput = (function() {
let uploadFile; let uploadFile;
formTextarea.wrap('<div class="div-dropzone"></div>'); formTextarea.wrap('<div class="div-dropzone"></div>');
formTextarea.on('paste', (function(_this) { formTextarea.on('paste', event => handlePaste(event));
return function(event) {
return handlePaste(event);
};
})(this));
// Add dropzone area to the form. // Add dropzone area to the form.
const $mdArea = formTextarea.closest('.md-area'); const $mdArea = formTextarea.closest('.md-area');
...@@ -53,23 +47,21 @@ window.DropzoneInput = (function() { ...@@ -53,23 +47,21 @@ window.DropzoneInput = (function() {
uploadMultiple: false, uploadMultiple: false,
headers: csrf.headers, headers: csrf.headers,
previewContainer: false, previewContainer: false,
processing: function() { processing: () => $('.div-dropzone-alert').alert('close'),
return $('.div-dropzone-alert').alert('close'); dragover: () => {
},
dragover: function() {
$mdArea.addClass('is-dropzone-hover'); $mdArea.addClass('is-dropzone-hover');
form.find('.div-dropzone-hover').css('opacity', 0.7); form.find('.div-dropzone-hover').css('opacity', 0.7);
}, },
dragleave: function() { dragleave: () => {
$mdArea.removeClass('is-dropzone-hover'); $mdArea.removeClass('is-dropzone-hover');
form.find('.div-dropzone-hover').css('opacity', 0); form.find('.div-dropzone-hover').css('opacity', 0);
}, },
drop: function() { drop: () => {
$mdArea.removeClass('is-dropzone-hover'); $mdArea.removeClass('is-dropzone-hover');
form.find('.div-dropzone-hover').css('opacity', 0); form.find('.div-dropzone-hover').css('opacity', 0);
formTextarea.focus(); formTextarea.focus();
}, },
success: function(header, response) { success(header, response) {
const processingFileCount = this.getQueuedFiles().length + this.getUploadingFiles().length; const processingFileCount = this.getQueuedFiles().length + this.getUploadingFiles().length;
const shouldPad = processingFileCount >= 1; const shouldPad = processingFileCount >= 1;
...@@ -78,7 +70,7 @@ window.DropzoneInput = (function() { ...@@ -78,7 +70,7 @@ window.DropzoneInput = (function() {
if (!processingFileCount) $attachButton.removeClass('hide'); if (!processingFileCount) $attachButton.removeClass('hide');
addFileToForm(response.link.url); addFileToForm(response.link.url);
}, },
error: function(file, errorMessage = 'Attaching the file failed.', xhr) { error: (file, errorMessage = 'Attaching the file failed.', xhr) => {
// If 'error' event is fired by dropzone, the second parameter is error message. // If 'error' event is fired by dropzone, the second parameter is error message.
// If the 'errorMessage' parameter is empty, the default error message is set. // If the 'errorMessage' parameter is empty, the default error message is set.
// If the 'error' event is fired by backend (xhr) error response, the third parameter is // If the 'error' event is fired by backend (xhr) error response, the third parameter is
...@@ -94,11 +86,11 @@ window.DropzoneInput = (function() { ...@@ -94,11 +86,11 @@ window.DropzoneInput = (function() {
$attachButton.addClass('hide'); $attachButton.addClass('hide');
$cancelButton.addClass('hide'); $cancelButton.addClass('hide');
}, },
totaluploadprogress: function(totalUploadProgress) { totaluploadprogress(totalUploadProgress) {
updateAttachingMessage(this.files, $attachingFileMessage); updateAttachingMessage(this.files, $attachingFileMessage);
$uploadProgress.text(Math.round(totalUploadProgress) + '%'); $uploadProgress.text(`${Math.round(totalUploadProgress)}%`);
}, },
sending: function(file) { sending: () => {
// DOM elements already exist. // DOM elements already exist.
// Instead of dynamically generating them, // Instead of dynamically generating them,
// we just either hide or show them. // we just either hide or show them.
...@@ -107,19 +99,19 @@ window.DropzoneInput = (function() { ...@@ -107,19 +99,19 @@ window.DropzoneInput = (function() {
$uploadingProgressContainer.removeClass('hide'); $uploadingProgressContainer.removeClass('hide');
$cancelButton.removeClass('hide'); $cancelButton.removeClass('hide');
}, },
removedfile: function() { removedfile: () => {
$attachButton.removeClass('hide'); $attachButton.removeClass('hide');
$cancelButton.addClass('hide'); $cancelButton.addClass('hide');
$uploadingProgressContainer.addClass('hide'); $uploadingProgressContainer.addClass('hide');
$uploadingErrorContainer.addClass('hide'); $uploadingErrorContainer.addClass('hide');
}, },
queuecomplete: function() { queuecomplete: () => {
$('.dz-preview').remove(); $('.dz-preview').remove();
$('.markdown-area').trigger('input'); $('.markdown-area').trigger('input');
$uploadingProgressContainer.addClass('hide'); $uploadingProgressContainer.addClass('hide');
$cancelButton.addClass('hide'); $cancelButton.addClass('hide');
} },
}); });
const child = $(dropzone[0]).children('textarea'); const child = $(dropzone[0]).children('textarea');
...@@ -144,10 +136,11 @@ window.DropzoneInput = (function() { ...@@ -144,10 +136,11 @@ window.DropzoneInput = (function() {
e.preventDefault(); e.preventDefault();
// 'true' parameter of removeAllFiles() cancels uploading of files that are being uploaded at the moment. // 'true' parameter of removeAllFiles() cancels
// uploading of files that are being uploaded at the moment.
dropzoneInstance.removeAllFiles(true); dropzoneInstance.removeAllFiles(true);
failedFiles.map((failedFile, i) => { failedFiles.map((failedFile) => {
const file = failedFile; const file = failedFile;
if (file.status === Dropzone.ERROR) { if (file.status === Dropzone.ERROR) {
...@@ -158,27 +151,25 @@ window.DropzoneInput = (function() { ...@@ -158,27 +151,25 @@ window.DropzoneInput = (function() {
return dropzoneInstance.addFile(file); return dropzoneInstance.addFile(file);
}); });
}); });
// eslint-disable-next-line consistent-return
handlePaste = function(event) { handlePaste = (event) => {
var filename, image, pasteEvent, text; const pasteEvent = event.originalEvent;
pasteEvent = event.originalEvent;
if (pasteEvent.clipboardData && pasteEvent.clipboardData.items) { if (pasteEvent.clipboardData && pasteEvent.clipboardData.items) {
image = isImage(pasteEvent); const image = isImage(pasteEvent);
if (image) { if (image) {
event.preventDefault(); event.preventDefault();
filename = getFilename(pasteEvent) || 'image.png'; const filename = getFilename(pasteEvent) || 'image.png';
text = `{{${filename}}}`; const text = `{{${filename}}}`;
pasteText(text); pasteText(text);
return uploadFile(image.getAsFile(), filename); return uploadFile(image.getAsFile(), filename);
} }
} }
}; };
isImage = function(data) { isImage = (data) => {
var i, item; let i = 0;
i = 0;
while (i < data.clipboardData.items.length) { while (i < data.clipboardData.items.length) {
item = data.clipboardData.items[i]; const item = data.clipboardData.items[i];
if (item.type.indexOf('image') !== -1) { if (item.type.indexOf('image') !== -1) {
return item; return item;
} }
...@@ -187,16 +178,17 @@ window.DropzoneInput = (function() { ...@@ -187,16 +178,17 @@ window.DropzoneInput = (function() {
return false; return false;
}; };
pasteText = function(text, shouldPad) { pasteText = (text, shouldPad) => {
var afterSelection, beforeSelection, caretEnd, caretStart, textEnd; let formattedText = text;
var formattedText = text; if (shouldPad) {
if (shouldPad) formattedText += "\n\n"; formattedText += '\n\n';
}
const textarea = child.get(0); const textarea = child.get(0);
caretStart = textarea.selectionStart; const caretStart = textarea.selectionStart;
caretEnd = textarea.selectionEnd; const caretEnd = textarea.selectionEnd;
textEnd = $(child).val().length; const textEnd = $(child).val().length;
beforeSelection = $(child).val().substring(0, caretStart); const beforeSelection = $(child).val().substring(0, caretStart);
afterSelection = $(child).val().substring(caretEnd, textEnd); const afterSelection = $(child).val().substring(caretEnd, textEnd);
$(child).val(beforeSelection + formattedText + afterSelection); $(child).val(beforeSelection + formattedText + afterSelection);
textarea.setSelectionRange(caretStart + formattedText.length, caretEnd + formattedText.length); textarea.setSelectionRange(caretStart + formattedText.length, caretEnd + formattedText.length);
textarea.style.height = `${textarea.scrollHeight}px`; textarea.style.height = `${textarea.scrollHeight}px`;
...@@ -204,56 +196,41 @@ window.DropzoneInput = (function() { ...@@ -204,56 +196,41 @@ window.DropzoneInput = (function() {
return formTextarea.trigger('input'); return formTextarea.trigger('input');
}; };
addFileToForm = function(path) { addFileToForm = (path) => {
$(form).append('<input type="hidden" name="files[]" value="' + _.escape(path) + '">'); $(form).append(`<input type="hidden" name="files[]" value="${_.escape(path)}">`);
}; };
getFilename = function(e) { getFilename = (e) => {
var value; let value;
if (window.clipboardData && window.clipboardData.getData) { if (window.clipboardData && window.clipboardData.getData) {
value = window.clipboardData.getData('Text'); value = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) { } else if (e.clipboardData && e.clipboardData.getData) {
value = e.clipboardData.getData('text/plain'); value = e.clipboardData.getData('text/plain');
} }
value = value.split("\r"); value = value.split('\r');
return value[0]; return value[0];
}; };
const showSpinner = function(e) { const showSpinner = () => $uploadingProgressContainer.removeClass('hide');
return $uploadingProgressContainer.removeClass('hide');
};
const closeSpinner = function() { const closeSpinner = () => $uploadingProgressContainer.addClass('hide');
return $uploadingProgressContainer.addClass('hide');
};
const showError = function(message) { const showError = (message) => {
$uploadingErrorContainer.removeClass('hide'); $uploadingErrorContainer.removeClass('hide');
$uploadingErrorMessage.html(message); $uploadingErrorMessage.html(message);
}; };
const closeAlertMessage = function() { const closeAlertMessage = () => form.find('.div-dropzone-alert').alert('close');
return form.find('.div-dropzone-alert').alert('close');
};
const insertToTextArea = function(filename, url) { const insertToTextArea = (filename, url) => {
const $child = $(child); const $child = $(child);
$child.val(function(index, val) { $child.val((index, val) => val.replace(`{{${filename}}}`, url));
return val.replace(`{{${filename}}}`, url);
});
$child.trigger('change'); $child.trigger('change');
}; };
const appendToTextArea = function(url) { uploadFile = (item, filename) => {
return $(child).val(function(index, val) { const formData = new FormData();
return val + url + "\n";
});
};
uploadFile = function(item, filename) {
var formData;
formData = new FormData();
formData.append('file', item, filename); formData.append('file', item, filename);
return $.ajax({ return $.ajax({
url: uploadsPath, url: uploadsPath,
...@@ -263,33 +240,27 @@ window.DropzoneInput = (function() { ...@@ -263,33 +240,27 @@ window.DropzoneInput = (function() {
processData: false, processData: false,
contentType: false, contentType: false,
headers: csrf.headers, headers: csrf.headers,
beforeSend: function() { beforeSend: () => {
showSpinner(); showSpinner();
return closeAlertMessage(); return closeAlertMessage();
}, },
success: function(e, textStatus, response) { success: (e, text, response) => {
return insertToTextArea(filename, response.responseJSON.link.markdown); const md = response.responseJSON.link.markdown;
insertToTextArea(filename, md);
}, },
error: function(response) { error: response => showError(response.responseJSON.message),
return showError(response.responseJSON.message); complete: () => closeSpinner(),
},
complete: function() {
return closeSpinner();
}
}); });
}; };
updateAttachingMessage = (files, messageContainer) => { updateAttachingMessage = (files, messageContainer) => {
let attachingMessage; let attachingMessage;
const filesCount = files.filter(function(file) { const filesCount = files.filter(file => file.status === 'uploading' || file.status === 'queued').length;
return file.status === 'uploading' ||
file.status === 'queued';
}).length;
// Dinamycally change uploading files text depending on files number in // Dinamycally change uploading files text depending on files number in
// dropzone files queue. // dropzone files queue.
if (filesCount > 1) { if (filesCount > 1) {
attachingMessage = 'Attaching ' + filesCount + ' files -'; attachingMessage = `Attaching ${filesCount} files -`;
} else { } else {
attachingMessage = 'Attaching a file -'; attachingMessage = 'Attaching a file -';
} }
...@@ -297,12 +268,9 @@ window.DropzoneInput = (function() { ...@@ -297,12 +268,9 @@ window.DropzoneInput = (function() {
messageContainer.text(attachingMessage); messageContainer.text(attachingMessage);
}; };
form.find('.markdown-selector').click(function(e) { form.find('.markdown-selector').click(function onMarkdownClick(e) {
e.preventDefault(); e.preventDefault();
$(this).closest('.gfm-form').find('.div-dropzone').click(); $(this).closest('.gfm-form').find('.div-dropzone').click();
formTextarea.focus(); formTextarea.focus();
}); });
} }
return DropzoneInput;
})();
/* global DropzoneInput */
/* global autosize */ /* global autosize */
import GfmAutoComplete from './gfm_auto_complete'; import GfmAutoComplete from './gfm_auto_complete';
import dropzoneInput from './dropzone_input';
export default class GLForm { export default class GLForm {
constructor(form, enableGFM = false) { constructor(form, enableGFM = false) {
...@@ -41,7 +41,7 @@ export default class GLForm { ...@@ -41,7 +41,7 @@ export default class GLForm {
mergeRequests: this.enableGFM, mergeRequests: this.enableGFM,
labels: this.enableGFM, labels: this.enableGFM,
}); });
new DropzoneInput(this.form); // eslint-disable-line no-new dropzoneInput(this.form);
autosize(this.textarea); autosize(this.textarea);
} }
// form and textarea event listeners // form and textarea event listeners
......
...@@ -13,7 +13,6 @@ import $ from 'jquery'; ...@@ -13,7 +13,6 @@ import $ from 'jquery';
import _ from 'underscore'; import _ from 'underscore';
import Cookies from 'js-cookie'; import Cookies from 'js-cookie';
import autosize from 'vendor/autosize'; import autosize from 'vendor/autosize';
import Dropzone from 'dropzone';
import 'vendor/jquery.caret'; // required by jquery.atwho import 'vendor/jquery.caret'; // required by jquery.atwho
import 'vendor/jquery.atwho'; import 'vendor/jquery.atwho';
import AjaxCache from '~/lib/utils/ajax_cache'; import AjaxCache from '~/lib/utils/ajax_cache';
...@@ -22,13 +21,11 @@ import CommentTypeToggle from './comment_type_toggle'; ...@@ -22,13 +21,11 @@ import CommentTypeToggle from './comment_type_toggle';
import GLForm from './gl_form'; import GLForm from './gl_form';
import loadAwardsHandler from './awards_handler'; import loadAwardsHandler from './awards_handler';
import './autosave'; import './autosave';
import './dropzone_input';
import TaskList from './task_list'; import TaskList from './task_list';
import { ajaxPost, isInViewport, getPagePath, scrollToElement, isMetaKey } from './lib/utils/common_utils'; import { ajaxPost, isInViewport, getPagePath, scrollToElement, isMetaKey } from './lib/utils/common_utils';
import imageDiffHelper from './image_diff/helpers/index'; import imageDiffHelper from './image_diff/helpers/index';
window.autosize = autosize; window.autosize = autosize;
window.Dropzone = Dropzone;
function normalizeNewlines(str) { function normalizeNewlines(str) {
return str.replace(/\r\n/g, '\n'); return str.replace(/\r\n/g, '\n');
......
...@@ -11,8 +11,6 @@ import Dropzone from 'dropzone'; ...@@ -11,8 +11,6 @@ import Dropzone from 'dropzone';
import 'mousetrap'; import 'mousetrap';
import 'mousetrap/plugins/pause/mousetrap-pause'; import 'mousetrap/plugins/pause/mousetrap-pause';
window.Dropzone = Dropzone;
// //
// ### Events // ### Events
// //
......
import 'dropzone';
import BlobFileDropzone from '~/blob/blob_file_dropzone'; import BlobFileDropzone from '~/blob/blob_file_dropzone';
describe('BlobFileDropzone', () => { describe('BlobFileDropzone', () => {
......
/* eslint-disable space-before-function-paren, no-var, one-var, one-var-declaration-per-line, object-shorthand, comma-dangle, no-return-assign, new-cap, max-len */ /* eslint-disable space-before-function-paren, no-var, one-var, one-var-declaration-per-line, object-shorthand, comma-dangle, no-return-assign, new-cap, max-len */
/* global Dropzone */
/* global Mousetrap */ /* global Mousetrap */
import Dropzone from 'dropzone';
import ZenMode from '~/zen_mode'; import ZenMode from '~/zen_mode';
(function() { (function() {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment