Welcome to mirror list, hosted at ThFree Co, Russian Federation.

publisher_view.js « views « app « javascripts « assets « app - github.com/diaspora/diaspora.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 876ad83399384968a55443c01d11ce7a0c8b2ee6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
/*   Copyright (c) 2010-2012, Diaspora Inc.  This file is
 *   licensed under the Affero General Public License version 3 or later.  See
 *   the COPYRIGHT file.
 */

//= require ./publisher/services_view
//= require ./publisher/aspect_selector_view
//= require ./publisher/aspect_selector_blueprint_view
//= require ./publisher/getting_started_view
//= require ./publisher/uploader_view
//= require jquery.textchange

app.views.Publisher = Backbone.View.extend({

  el : "#publisher",

  events : {
    "keydown #status_message_fake_text" : "keyDown",
    "focus textarea" : "open",
    "click #hide_publisher" : "clear",
    "submit form" : "createStatusMessage",
    "click #submit" : "createStatusMessage",
    "click .post_preview_button" : "createPostPreview",
    "textchange #status_message_fake_text": "handleTextchange",
    "click #locator" : "showLocation",
    "click #poll_creator" : "togglePollCreator",
    "click #hide_location" : "destroyLocation",
    "keypress #location_address" : "avoidEnter"
  },

  initialize : function(opts){
    this.standalone = opts ? opts.standalone : false;
    this.disabled   = false;

    // init shortcut references to the various elements
    this.el_input = this.$('#status_message_fake_text');
    this.el_hiddenInput = this.$('#status_message_text');
    this.el_wrapper = this.$('#publisher_textarea_wrapper');
    this.el_submit = this.$('input[type=submit], button#submit');
    this.el_preview = this.$('button.post_preview_button');
    this.el_photozone = this.$('#photodropzone');

    // init mentions plugin
    Mentions.initialize(this.el_input);

    // init autoresize plugin
    this.el_input.autoResize({ 'extraSpace' : 10, 'maxHeight' : Infinity });

    // sync textarea content
    if( this.el_hiddenInput.val() == "" ) {
      this.el_hiddenInput.val( this.el_input.val() );
    }

    // hide close and preview buttons, in case publisher is standalone
    // (e.g. bookmarklet, mentions popup)
    if( this.standalone ) {
      this.$('#hide_publisher').hide();
      this.el_preview.hide();
    }

    // this has to be here, otherwise for some reason the callback for the
    // textchange event won't be called in Backbone...
    this.el_input.bind('textchange', $.noop);

    var _this = this
    $('body').on('click', function(event){
      // if the click event is happened outside the publisher view, then try to close the box
      if( _this.el && $(event.target).closest('#publisher').attr('id') != _this.el.id){
          _this.tryClose()
        }
    });

    // close publisher on post
    this.on('publisher:add', function() {
      this.close();
      this.showSpinner(true);
    });
    
    // open publisher on post error
    this.on('publisher:error', function() {
      this.open();
      this.showSpinner(false);
    });

    // resetting the poll view 
    this.on('publisher:sync', function() {
      this.view_poll_creator.render();
    });

    this.initSubviews();
    return this;
  },

  initSubviews: function() {
    var form = this.$('.content_creation form');

    this.view_services = new app.views.PublisherServices({
      el:    this.$('#publisher_service_icons'),
      input: this.el_input,
      form:  form
    });

    this.view_aspect_selector = new app.views.PublisherAspectSelector({
      el: this.$('.public_toggle .aspect_dropdown'),
      form: form
    });

    this.view_aspect_selector_blueprint = new app.views.PublisherAspectSelectorBlueprint({
      el: this.$('.public_toggle > .dropdown'),
      form: form
    });

    this.view_getting_started = new app.views.PublisherGettingStarted({
      el_first_msg:  this.el_input,
      el_visibility: this.$('.public_toggle > .dropdown'),
      el_stream:     $('#gs-shim')
    });

    this.view_uploader = new app.views.PublisherUploader({
      el: this.$('#file-upload'),
      publisher: this
    });
    this.view_uploader.on('change', this.checkSubmitAvailability, this);

    this.view_poll_creator = new app.views.PublisherPollCreator({
      el: this.$('#publisher-poll-creator')
    });
    this.view_poll_creator.on('change', this.checkSubmitAvailability, this);
    this.view_poll_creator.render();

  },

  // set the selected aspects in the dropdown by their ids
  setSelectedAspects: function(ids) {
    this.view_aspect_selector.updateAspectsSelector(ids);
    this.view_aspect_selector_blueprint.updateAspectsSelector(ids);
  },

  // inject content into the publisher textarea
  setText: function(txt) {
    this.el_input.val(txt);
    this.el_hiddenInput.val(txt);

    this.el_input.trigger('input');
    this.handleTextchange();
  },

  // show the "getting started" popups around the publisher
  triggerGettingStarted: function() {
    this.view_getting_started.show();
  },

  createStatusMessage : function(evt) {
    this.setButtonsEnabled(false);
    var self = this;

    if(evt){ evt.preventDefault(); }

    // Auto-adding a poll answer always leaves an empty box when the user starts
    // typing in the last box. We'll delete the last one to avoid submitting an 
    // empty poll answer and failing validation.
    this.view_poll_creator.removeLastAnswer();

    //add missing mentions at end of post:
    this.handleTextchange();

    var serializedForm = $(evt.target).closest("form").serializeObject();
    // disable input while posting, must be after the form is serialized
    this.setInputEnabled(false);

    // lulz this code should be killed.
    var statusMessage = new app.models.Post();
    if( app.publisher ) app.publisher.trigger('publisher:add');

    statusMessage.save({
      "status_message" : {
        "text" : serializedForm["status_message[text]"]
      },
      "aspect_ids" : serializedForm["aspect_ids[]"],
      "photos" : serializedForm["photos[]"],
      "services" : serializedForm["services[]"],
      "location_address" : $("#location_address").val(),
      "location_coords" : serializedForm["location[coords]"],
      "poll_question" : serializedForm["poll_question"],
      "poll_answers" : serializedForm["poll_answers[]"]
    }, {
      url : "/status_messages",
      success : function() {
        if( app.publisher ) {
          app.publisher.$el.trigger('ajax:success');
          app.publisher.trigger('publisher:sync');
          self.view_poll_creator.trigger('publisher:sync');
        }

        if(app.stream) app.stream.addNow(statusMessage.toJSON());

        // clear state
        self.clear();

        // standalone means single-shot posting (until further notice)
        if( self.standalone ) self.setEnabled(false);
      },
      error: function(model, resp, options) {
        if( app.publisher ) app.publisher.trigger('publisher:error');
        self.setInputEnabled(true);
        Diaspora.page.flashMessages.render({ 'success':false, 'notice':resp.responseText });
        self.setButtonsEnabled(true);
        self.setInputEnabled(true);
      }
    });
  },

  // creates the location
  showLocation: function(){
    if($('#location').length == 0){
      $('#location_container').append('<div id="location"></div>');
      this.el_wrapper.addClass('with_location');
      this.view_locator = new app.views.Location();
    }
  },

  // destroys the location
  destroyLocation: function(){
    if(this.view_locator){
      this.view_locator.remove();
      this.el_wrapper.removeClass('with_location');
      delete this.view_locator;
    }
  },

  togglePollCreator: function(){
    this.view_poll_creator.$el.toggle();
    this.el_input.focus();
  },

  // avoid submitting form when pressing Enter key
  avoidEnter: function(evt){
    if(evt.keyCode == 13)
      return false;
  },

  createPostPreview : function(evt) {
    if(evt){ evt.preventDefault(); }

    //add missing mentions at end of post:
    this.handleTextchange();

    var serializedForm = $(evt.target).closest("form").serializeObject();

    var photos = new Array();
    $('li.publisher_photo img').each(function(){
      var file = $(this).attr('src').substring("/uploads/images/".length);
      photos.push(
        {
          "sizes":{
            "small" : "/uploads/images/thumb_small_" + file,
            "medium" : "/uploads/images/thumb_medium_" + file,
            "large" : "/uploads/images/scaled_full_" + file
          }
        }
      );
    });

    var mentioned_people = new Array();
    var regexp = new RegExp("@{\(\[\^\;\]\+\); \(\[\^\}\]\+\)}", "g");
    while(user=regexp.exec(serializedForm["status_message[text]"])){
      // user[1]: name, user[2]: handle
      var mentioned_user = Mentions.contacts.filter(function(item) { return item.handle == user[2];})[0];
      if(mentioned_user){
        mentioned_people.push({
          "id":mentioned_user["id"],
          "guid":mentioned_user["guid"],
          "name":user[1],
          "diaspora_id":user[2],
          "avatar":mentioned_user["avatar"]
        });
      }
    }

    var date = (new Date()).toISOString();

    var poll = undefined;
    var poll_question = serializedForm["poll_question"];
    var poll_answers_arry = _.flatten([serializedForm["poll_answers[]"]]);
    var poll_answers = _.map(poll_answers_arry, function(answer){
      if(answer) return { 'answer' : answer };
    });
    poll_answers = _.without(poll_answers, undefined);

    if(poll_question && poll_answers.length) {
      poll = {
        'question': poll_question,
        'poll_answers' : poll_answers,
        'participation_count': '0'
      };
    }

    var previewMessage = {
      "id" : 0,
      "text" : serializedForm["status_message[text]"],
      "public" : serializedForm["aspect_ids[]"]=="public",
      "created_at" : date,
      "interacted_at" : date,
      "post_type" : "StatusMessage",
      "author" : app.currentUser ? app.currentUser.attributes : {},
      "mentioned_people" : mentioned_people,
      "photos" : photos,
      "frame_name" : "status",
      "title" : serializedForm["status_message[text]"],
      "address" : $("#location_address").val(),
      "interactions" : {"likes":[],"reshares":[],"comments_count":0,"likes_count":0,"reshares_count":0},
      'poll': poll,
    };
    if(app.stream) {
      this.removePostPreview();
      app.stream.addNow(previewMessage);
      this.recentPreview=previewMessage;
      this.modifyPostPreview($('.stream_element:first',$('.stream_container')));
    }
  },

  modifyPostPreview : function(post) {
    post.addClass('post_preview');
    $('.collapsible',post).removeClass('collapsed').addClass('opened');
    $('a.delete.remove_post',post).hide();
    $('a.like, a.focus_comment_textarea',post).removeAttr("href");
    $('a.like',post).addClass("like_preview");
    $('a.like',post).removeClass("like");
    $('a.focus_comment_textarea',post).addClass("focus_comment_textarea_preview");
    $('a.focus_comment_textarea',post).removeClass("focus_comment_textarea");
    $('a',$('span.details.grey',post)).removeAttr("href");
  },

  removePostPreview : function() {
    if(app.stream && this.recentPreview){
        app.stream.items.remove(this.recentPreview);
        delete this.recentPreview;
    }
  },

  keyDown : function(evt) {
    if( evt.keyCode == 13 && evt.ctrlKey ) {
      this.$("form").submit();
      this.open();
      return false;
    }
  },

  clear : function() {
    // clear text(s)
    this.el_input.val('');
    this.el_hiddenInput.val('');

    // remove mentions
    this.el_input.mentionsInput('reset');

    // remove photos
    this.el_photozone.find('li').remove();
    this.$("input[name='photos[]']").remove();
    this.el_wrapper.removeClass("with_attachments");

    // empty upload-photo
    this.$('#fileInfo').empty();

    // close publishing area (CSS)
    this.close();

    // remove preview
    this.removePostPreview();

    // disable submitting
    this.checkSubmitAvailability();

    // hide spinner
    this.showSpinner(false);

    // enable input
    this.setInputEnabled(true);
    
    // enable buttons
    this.setButtonsEnabled(true);

    // clear location
    this.destroyLocation();

    // clear poll form
    this.view_poll_creator.clearInputs();

    // force textchange plugin to update lastValue
    this.el_input.data('lastValue', '');
    this.el_hiddenInput.data('lastValue', '');

    return this;
  },

  tryClose : function(){
    // if it is not submittable, close it.
    if( !this._submittable() ){
      this.close()
    }
  },

  open : function() {
    if( this.disabled ) return;

    // visually 'open' the publisher
    this.$el.removeClass('closed');
    this.el_wrapper.addClass('active');

    // fetch contacts for mentioning
    Mentions.fetchContacts();
    return this;
  },

  close : function() {
    $(this.el).addClass("closed");
    this.el_wrapper.removeClass("active");
    this.el_input.css('height', '');
    this.view_poll_creator.$el.hide();
    return this;
  },

  showSpinner: function(bool) {
    if (bool)
      this.$('#publisher_spinner').removeClass('hidden');
    else
      this.$('#publisher_spinner').addClass('hidden');
  },
  
  checkSubmitAvailability: function() {
    if( this._submittable() ) {
      this.setButtonsEnabled(true);
    } else {
      this.setButtonsEnabled(false);
    }
  },

  setEnabled: function(bool) {
    this.setInputEnabled(bool);
    this.disabled = !bool;

    this.handleTextchange();
  },

  setButtonsEnabled: function(bool) {
    bool = !bool;
    this.el_submit.prop({disabled: bool});
    this.el_preview.prop({disabled: bool});
  },

  setInputEnabled: function(bool) {
    bool = !bool;
    this.el_input.prop({disabled: bool});
    this.el_hiddenInput.prop({disabled: bool});
  },

  // determine submit availability
  _submittable: function() {
    var onlyWhitespaces = ($.trim(this.el_input.val()) === ''),
        isPhotoAttached = (this.el_photozone.children().length > 0),
        isValidPoll = this.view_poll_creator.validatePoll();

    return (!onlyWhitespaces || isPhotoAttached) && isValidPoll && !this.disabled;
  },

  handleTextchange: function() {
    var self = this;

    this.checkSubmitAvailability();
    this.el_input.mentionsInput("val", function(value){
      self.el_hiddenInput.val(value);
    });
  }

});

// jQuery helper for serializing a <form> into JSON
$.fn.serializeObject = function()
{
  var o = {};
  var a = this.serializeArray();
  $.each(a, function() {
    if (o[this.name] !== undefined) {
      if (!o[this.name].push) {
        o[this.name] = [o[this.name]];
      }
      o[this.name].push(this.value || '');
    } else {
      o[this.name] = this.value || '';
    }
  });
  return o;
};