Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

61132 drag n drop files #574

Merged
merged 6 commits into from
Mar 4, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/assets/javascripts/fae/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
//= require fae/form/_form_manager
//= require fae/form/fae_chosen
//= require fae/form/fileinputer
//= require fae/form/drag_drop

//= require fae/navigation/sticky
//= require fae/navigation/_navigation
Expand Down
3 changes: 3 additions & 0 deletions app/assets/javascripts/fae/form/_ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ Fae.form.ajax = {
Fae.form.checkbox.setCheckboxAsActive();
Fae.form.select.init();
Fae.form.formManager.setupAllFields($wrapper.find('form'));
Fae.form.dragDrop.init();

// validate nested form fields on submit
Fae.form.validator.formValidate(this.$nested_form);
Expand Down Expand Up @@ -165,6 +166,7 @@ Fae.form.ajax = {

$parent.fadeOut(function(){
$parent.next('.asset-inputs').fadeIn();
$parent.remove();
});
}

Expand Down Expand Up @@ -273,6 +275,7 @@ Fae.form.ajax = {

$parent.fadeOut(function(){
$parent.next('.asset-inputs').fadeIn();
$parent.remove()
jaybones90 marked this conversation as resolved.
Show resolved Hide resolved
});
}
});
Expand Down
6 changes: 4 additions & 2 deletions app/assets/javascripts/fae/form/_form.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@ Fae.form = {
this.filtering.init();
this.slugger.init();
this.formManager.init();

// input type=file customization
// This doesn't work in IE. It's not worth figuring out why by this point. IE9 gets plain file uploader.
if (!FCH.IE9) {
$('.input.file').fileinputer();
}

// make all the hint areas
$('.hint').hinter();

this.dragDrop.init();
},

makeTwoColumnLabels: function() {
Expand Down
109 changes: 109 additions & 0 deletions app/assets/javascripts/fae/form/drag_drop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/* global Fae */

/**
* Fae form drag n drop uploads
* @namespace form.dragDrop
* @memberof form
*/
Fae.form.dragDrop = {

init: function () {
this.fileInputs = document.querySelectorAll('input[type="file"]');
if (this.fileInputs.length === 0) return;

this.bindListeners();
},

bindListeners() {

Array.from(this.fileInputs).forEach(input => {
const container = input.closest('.input.field');

['dragenter', 'dragover'].forEach((eventName) => {
container.addEventListener(eventName, this.highlight.bind(container));
});

['dragleave', 'drop'].forEach((eventName) => {
container.addEventListener(eventName, this.unhighlight.bind(container));
});

// This needed to be bound via jquery since tests have to use a simulated jquery event and native event listeners do not pickup on jquery events
$(container).on('drop', this.handleDrop.bind(this, container));
})
},

highlight(e) {
e.stopPropagation();
e.preventDefault();
this.classList.add('highlight');
},

unhighlight(e) {
e.stopPropagation();
e.preventDefault();
this.classList.remove('highlight');
},

handleDrop(inputContainer, e) {
// return the original event from the jquery event
if (e.originalEvent) {
e = e.originalEvent
jaybones90 marked this conversation as resolved.
Show resolved Hide resolved
}
const input = inputContainer.querySelector('input[type="file"]');
const fileList = e.dataTransfer.files;
const file = fileList[0];
const isValidFile = this.validatesFileSize(input, file);

if (isValidFile) {
this.attachFile(input, fileList);
this.addFileInfo(inputContainer, file);
}
},

attachFile(input, files) {
input.files = files;
},

addFileInfo(inputContainer, file) {
const deleteButton = inputContainer.querySelector('.asset-delete');

// only exists if image is already loaded into field
let label = inputContainer.querySelector('.asset-title');
if (!label) {
// else is a new image
label = inputContainer.querySelector('.asset-actions span');
}
label.innerText = file.name;
deleteButton.style.display = 'block';
},

validatesFileSize(input, file) {
const limit = parseInt(input.dataset.limit);
const fileSize = file.size / 1024 / 1024;

if (fileSize < limit) {
this.removeFileSizeError(input);
return true;
}

this.addFileSizeError(input, limit);
return false;
},

addFileSizeError(input, limit) {
const errorElem = document.createElement('span');
errorElem.innerText = input.dataset.exceeded.replace('###', limit);
errorElem.classList.add('error');
input.after(errorElem);
input.parentElement.classList.add('field_with_errors');
},

removeFileSizeError(input) {
const nextSibling = input.nextSibling;
if (nextSibling.classList.contains('error')) {
nextSibling.remove();
}
input.parentElement.classList.remove('field_with_errors');
}

};
8 changes: 8 additions & 0 deletions app/assets/stylesheets/fae/modules/forms/_base.scss
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,11 @@ input[type=email] {
margin-bottom: 10px;
}
}

.input.field {

&.highlight {
outline: 2px dashed green;
outline-offset: 1px;
}
}
2 changes: 2 additions & 0 deletions spec/dummy/config/initializers/fae.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

config.devise_mailer_sender = 'test@test.com'

config.max_image_upload_size = 1

# models to exclude from dashboard list
config.dashboard_exclusions = %w( Aroma PolyThing )

Expand Down
59 changes: 59 additions & 0 deletions spec/features/drag_drop_uploads_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
require 'spec_helper'

feature 'Drag and drop uploads for file fields' do

# uncomment to expose browser console error messages in terminal
# very helpful for debugging as not all errors show up when page.driver.enable_logging is enabled
# after(:each) do
# errors = [page.driver.error_messages, page.driver.console_messages]
# if errors.present?
# puts '-----------------------------'
# puts errors
# end
# end

before(:each) do
release = FactoryBot.create(:release)
admin_login
visit edit_admin_release_path(release)
end

def drop_image(image_field)
# uncomment to debug js errors
# page.driver.enable_logging

# Generate a fake input selector
page.execute_script <<-JS
$fakeFileInput = window.$('<input/>').attr(
{id: 'fakeFileInput', type:'file'}
).appendTo('body');
JS

# attach file to fake input
attach_file("fakeFileInput", 'spec/support/assets/test-2.jpg')

page.execute_script <<-JS
// Ideal solution would be using 'dataTransfer` object along with 'DragEvent' event in vanilla JS but Capybara webkit driver does not have access to either of those so jquery event must be used instead
var testEvent = jQuery.Event('drop', { dataTransfer : { files : $fakeFileInput.get(0).files } });
$('#{image_field}').trigger(testEvent)
JS
end


scenario 'should add image to input field when dropped', js: true do
drop_image('.hero_image')
expect(find('.hero_image .asset-actions span')).to have_content('test-2.jpg')
end

scenario 'should overwrite existing image when new image is dropped', js: true do
# make input visible so capybara can attach file
page.execute_script("$('#release_hero_image_attributes_asset').css({visibility: 'visible', position: 'static'}) ")
attach_file('release_hero_image_attributes_asset', 'spec/support/assets/test.jpg')
expect(find('.hero_image .asset-actions span')).to have_content('test.jpg')

drop_image('.hero_image')
expect(find('.hero_image .asset-actions span')).to have_content('test-2.jpg')
end


end
Binary file added spec/support/assets/test-2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.