implement publisher uploader as backbone view

This commit is contained in:
Florian Staudacher 2013-08-30 22:07:06 +02:00
parent 4090f134f2
commit 4da696253a
3 changed files with 140 additions and 79 deletions

View file

@ -0,0 +1,122 @@
// Uploader view for the publisher.
// Initializes the file uploader plugin and handles callbacks for the upload
// progress. Attaches previews of finished uploads to the publisher.
app.views.PublisherUploader = Backbone.View.extend({
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff'],
sizeLimit: 4194304, // bytes
initialize: function() {
this.uploader = new qq.FileUploaderBasic({
element: this.el,
button: this.el,
//debug: true,
action: '/photos',
params: { photo: { pending: true }},
allowedExtensions: this.allowedExtensions,
sizeLimit: this.sizeLimit,
messages: {
typeError: Diaspora.I18n.t('photo_uploader.invalid_ext'),
sizeError: Diaspora.I18n.t('photo_uploader.size_error'),
emptyError: Diaspora.I18n.t('photo_uploader.empty')
},
onProgress: _.bind(this.progressHandler, this),
onSubmit: _.bind(this.submitHandler, this),
onComplete: _.bind(this.uploadCompleteHandler, this)
});
this.options.publisher.el_photozone.on('click', '.x', _.bind(this._removePhoto, this));
},
progressHandler: function(id, fileName, loaded, total) {
var progress = Math.round(loaded / total * 100);
this.options.el_info.text(fileName + ' ' + progress + '%').fadeTo(200, 1);
},
submitHandler: function(id, fileName) {
this.$el.addClass('loading');
this._addPhotoPlaceholder();
},
// add photo placeholders to the publisher to indicate an upload in progress
_addPhotoPlaceholder: function() {
var publisher = this.options.publisher;
publisher.el_submit.attr('disabled', 'disabled');
publisher.el_preview.attr('disabled', 'disabled');
publisher.el_wrapper.addClass('with_attachments');
publisher.el_photozone.append(
'<li class="publisher_photo loading" style="position:relative;">' +
' <img src="'+Handlebars.helpers.imageUrl('ajax-loader2.gif')+'" alt="" />'+
'</li>'
);
},
uploadCompleteHandler: function(id, fileName, response) {
this.options.el_info.text(Diaspora.I18n.t('photo_uploader.completed', {file: fileName})).fadeTo(2000, 0);
var id = response.data.photo.id,
url = response.data.photo.unprocessed_image.url;
this._addFinishedPhoto(id, url);
},
// replace the first photo placeholder with the finished uploaded image and
// add the id to the publishers form
_addFinishedPhoto: function(id, url) {
var publisher = this.options.publisher;
// add form input element
publisher.$('.content_creation form').append(
'<input type="hidden", value="'+id+'" name="photos[]" />'
);
// replace placeholder
var placeholder = publisher.el_photozone.find('li.loading').first();
placeholder
.removeClass('loading')
.append(
'<div class="x">X</div>'+
'<div class="circle"></div>'
)
.find('img').attr({'src': url, 'data-id': id});
// no more placeholders? enable buttons
if( publisher.el_photozone.find('li.loading').length == 0 ) {
this.$el.removeClass('loading');
publisher.setButtonsEnabled(true);
}
},
// remove an already uploaded photo
_removePhoto: function(evt) {
var self = this;
var photo = $(evt.target).parents('.publisher_photo')
var img = photo.find('img');
photo.addClass('dim');
$.ajax({
url: '/photos/'+img.attr('data-id'),
dataType: 'json',
type: 'DELETE',
success: function() {
photo.fadeOut(400, function(){
photo.remove();
if( self.options.publisher.$('.publisher_photo').length == 0 ) {
// no more photos left...
self.options.publisher.el_wrapper.removeClass('with_attachments');
}
});
}
});
return false;
}
});

View file

@ -6,6 +6,7 @@
//= require ./publisher/services //= require ./publisher/services
//= require ./publisher/aspect_selector //= require ./publisher/aspect_selector
//= require ./publisher/getting_started //= require ./publisher/getting_started
//= require ./publisher/uploader
//= require jquery.textchange //= require jquery.textchange
app.views.Publisher = Backbone.View.extend(_.extend( app.views.Publisher = Backbone.View.extend(_.extend(
@ -88,6 +89,13 @@ app.views.Publisher = Backbone.View.extend(_.extend(
el_visibility: this.$('.public_toggle > .dropdown'), el_visibility: this.$('.public_toggle > .dropdown'),
el_stream: $('#gs-shim') el_stream: $('#gs-shim')
}); });
this.view_uploader = new app.views.PublisherUploader({
el: this.$('#file-upload'),
el_info: this.$('#fileInfo'),
publisher: this
});
}, },
// set the selected aspects in the dropdown by their ids // set the selected aspects in the dropdown by their ids
@ -309,14 +317,18 @@ app.views.Publisher = Backbone.View.extend(_.extend(
checkSubmitAvailability: function() { checkSubmitAvailability: function() {
if( this._submittable() ) { if( this._submittable() ) {
this.el_submit.removeAttr('disabled'); this.setButtonsEnabled(true);
this.el_preview.removeAttr('disabled');
} else { } else {
this.el_submit.attr('disabled','disabled'); this.setButtonsEnabled(false);
this.el_preview.attr('disabled','disabled');
} }
}, },
setButtonsEnabled: function(bool) {
bool = !bool;
this.el_submit.prop({disabled: bool});
this.el_preview.prop({disabled: bool});
},
// determine submit availability // determine submit availability
_submittable: function() { _submittable: function() {
var onlyWhitespaces = ($.trim(this.el_input.val()) === ''), var onlyWhitespaces = ($.trim(this.el_input.val()) === ''),

View file

@ -8,84 +8,11 @@
var aspectIds = "#{aspect_ids}".split(','); var aspectIds = "#{aspect_ids}".split(',');
var uploader = new qq.FileUploaderBasic({ var uploader = new qq.FileUploaderBasic({
element: document.getElementById('file-upload'),
params: {'photo' : {'pending' : 'true', 'aspect_ids' : aspectIds}, 'set_profile_image' : "#{set_profile_image if defined?(set_profile_image)}"}, params: {'photo' : {'pending' : 'true', 'aspect_ids' : aspectIds}, 'set_profile_image' : "#{set_profile_image if defined?(set_profile_image)}"},
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'tiff'],
action: "#{photos_path}",
debug: true,
button: document.getElementById('file-upload'),
sizeLimit: 4194304,
onProgress: function(id, fileName, loaded, total){
var progress = Math.round(loaded / total * 100 );
$('#fileInfo').text(fileName + ' ' + progress + '%').fadeTo(200, 1);
},
messages: {
typeError: "#{t('.invalid_ext')}",
sizeError: "#{t('.size_error')}",
emptyError: "#{t('.empty')}"
},
onSubmit: function(id, fileName){
$('#file-upload').addClass("loading");
$('#publisher').find("input[type='submit']").attr('disabled','disabled');
$('#publisher').find("button.post_preview_button").attr('disabled','disabled');
app.publisher.el_wrapper.addClass("with_attachments");
$('#photodropzone').append(
"<li class='publisher_photo loading' style='position:relative;'>" +
"#{escape_javascript(image_tag('ajax-loader2.gif'))}" +
"</li>"
);
},
onComplete: function(id, fileName, responseJSON) {
$('#fileInfo').text(Diaspora.I18n.t("photo_uploader.completed", file=fileName)).fadeTo(2000, 0);
var id = responseJSON.data.photo.id,
url = responseJSON.data.photo.unprocessed_image.url,
currentPlaceholder = $('li.loading').first();
app.publisher.el_wrapper.addClass("with_attachments");
$('#new_status_message').append("<input type='hidden' value='" + id + "' name='photos[]' />");
// replace image placeholders
var img = currentPlaceholder.find('img');
img.attr('src', url);
img.attr('data-id', id);
currentPlaceholder.removeClass('loading');
currentPlaceholder.append("<div class='x'>X</div>" +
"<div class='circle'></div>");
////
var publisher = $('#publisher'),
textarea = publisher.find('textarea');
publisher.find("input[type='submit']").removeAttr('disabled');
publisher.find("button.post_preview_button").removeAttr('disabled');
$('.x').bind('click', function(){
var photo = $(this).closest('.publisher_photo');
photo.addClass("dim");
$.ajax({url: "/photos/" + photo.children('img').attr('data-id'),
dataType: 'json',
type: 'DELETE',
success: function() {
photo.fadeOut(400, function(){
photo.remove();
if ( $('.publisher_photo').length == 0){
app.publisher.el_wrapper.removeClass("with_attachments");
}
});
}
});
});
},
onAllComplete: function(completed_files){
}
}); });
} }
createUploader(); // createUploader();