]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - js/util.js
Merge commit 'origin/0.9.x' into 0.9.x
[quix0rs-gnu-social.git] / js / util.js
1 /*
2  * StatusNet - a distributed open-source microblogging tool
3  * Copyright (C) 2008, StatusNet, Inc.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  * @category  UI interaction
19  * @package   StatusNet
20  * @author    Sarven Capadisli <csarven@status.net>
21  * @author    Evan Prodromou <evan@status.net>
22  * @copyright 2009 StatusNet, Inc.
23  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
24  * @link      http://status.net/
25  */
26
27 var SN = { // StatusNet
28     C: { // Config
29         I: { // Init
30             CounterBlackout: false,
31             MaxLength: 140,
32             PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
33             HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
34         },
35
36         S: { // Selector
37             Disabled: 'disabled',
38             Warning: 'warning',
39             Error: 'error',
40             Success: 'success',
41             Processing: 'processing',
42             CommandResult: 'command_result',
43             FormNotice: 'form_notice',
44             NoticeDataText: 'notice_data-text',
45             NoticeTextCount: 'notice_text-count',
46             NoticeInReplyTo: 'notice_in-reply-to',
47             NoticeDataAttach: 'notice_data-attach',
48             NoticeDataAttachSelected: 'notice_data-attach_selected',
49             NoticeActionSubmit: 'notice_action-submit',
50             NoticeLat: 'notice_data-lat',
51             NoticeLon: 'notice_data-lon',
52             NoticeLocationId: 'notice_data-location_id',
53             NoticeLocationNs: 'notice_data-location_ns'
54         }
55     },
56
57     U: { // Utils
58         FormNoticeEnhancements: function(form) {
59             form_id = form.attr('id');
60             $('#'+form_id+' #'+SN.C.S.NoticeDataText).unbind('keyup');
61             $('#'+form_id+' #'+SN.C.S.NoticeDataText).unbind('keydown');
62             if (maxLength > 0) {
63                 $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keyup', function(e) {
64                     SN.U.Counter(form);
65                 });
66                 // run once in case there's something in there
67                 SN.U.Counter(form);
68             }
69
70             $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keydown', function(e) {
71                 SN.U.SubmitOnReturn(e, form);
72             });
73
74             if($('body')[0].id != 'conversation') {
75                 $('#'+form_id+' textarea').focus();
76             }
77         },
78
79         SubmitOnReturn: function(event, el) {
80             if (event.keyCode == 13 || event.keyCode == 10) {
81                 el.submit();
82                 event.preventDefault();
83                 event.stopPropagation();
84                 $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
85                 $('body').focus();
86                 return false;
87             }
88             return true;
89         },
90
91         Counter: function(form) {
92             SN.C.I.FormNoticeCurrent = form;
93             form_id = form.attr('id');
94             if (typeof(maxLength) == "undefined") {
95                  maxLength = SN.C.I.MaxLength;
96             }
97
98             if (maxLength <= 0) {
99                 return;
100             }
101
102             var remaining = maxLength - $('#'+form_id+' #'+SN.C.S.NoticeDataText).val().length;
103             var counter = $('#'+form_id+' #'+SN.C.S.NoticeTextCount);
104
105             if (remaining.toString() != counter.text()) {
106                 if (!SN.C.I.CounterBlackout || remaining === 0) {
107                     if (counter.text() != String(remaining)) {
108                         counter.text(remaining);
109                     }
110                     if (remaining < 0) {
111                         form.addClass(SN.C.S.Warning);
112                     } else {
113                         form.removeClass(SN.C.S.Warning);
114                     }
115                     // Skip updates for the next 500ms.
116                     // On slower hardware, updating on every keypress is unpleasant.
117                     if (!SN.C.I.CounterBlackout) {
118                         SN.C.I.CounterBlackout = true;
119                         SN.C.I.FormNoticeCurrent = form;
120                         window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
121                     }
122                 }
123             }
124         },
125
126         ClearCounterBlackout: function(form) {
127             // Allow keyup events to poke the counter again
128             SN.C.I.CounterBlackout = false;
129             // Check if the string changed since we last looked
130             SN.U.Counter(form);
131         },
132
133         FormXHR: function(f) {
134             if (jQuery.data(f[0], "ElementData") === undefined) {
135                 jQuery.data(f[0], "ElementData", {Bind:'submit'});
136                 f.bind('submit', function(e) {
137                     form_id = $(this)[0].id;
138                     $.ajax({
139                         type: 'POST',
140                         dataType: 'xml',
141                         url: $(this)[0].action,
142                         data: $(this).serialize() + '&ajax=1',
143                         beforeSend: function(xhr) {
144                             $('#'+form_id).addClass(SN.C.S.Processing);
145                             $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
146                             $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
147                         },
148                         error: function (xhr, textStatus, errorThrown) {
149                             alert(errorThrown || textStatus);
150                         },
151                         success: function(data, textStatus) {
152                             if (typeof($('form', data)[0]) != 'undefined') {
153                                 form_new = document._importNode($('form', data)[0], true);
154                                 $('#'+form_id).replaceWith(form_new);
155                                 $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
156                             }
157                             else {
158                                 $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
159                             }
160                         }
161                     });
162                     return false;
163                 });
164             }
165         },
166
167         FormNoticeXHR: function(form) {
168             form_id = form.attr('id');
169             form.append('<input type="hidden" name="ajax" value="1"/>');
170             form.ajaxForm({
171                 dataType: 'xml',
172                 timeout: '60000',
173                 beforeSend: function(xhr) {
174                     if ($('#'+form_id+' #'+SN.C.S.NoticeDataText)[0].value.length === 0) {
175                         form.addClass(SN.C.S.Warning);
176                         return false;
177                     }
178                     form.addClass(SN.C.S.Processing);
179                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).addClass(SN.C.S.Disabled);
180                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).attr(SN.C.S.Disabled, SN.C.S.Disabled);
181                     return true;
182                 },
183                 error: function (xhr, textStatus, errorThrown) {
184                     form.removeClass(SN.C.S.Processing);
185                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
186                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
187                     $('#'+form_id+' .form_response').remove();
188                     if (textStatus == 'timeout') {
189                         form.append('<p class="form_response error">Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.</p>');
190                     }
191                     else {
192                         if ($('.'+SN.C.S.Error, xhr.responseXML).length > 0) {
193                             form.append(document._importNode($('.'+SN.C.S.Error, xhr.responseXML)[0], true));
194                         }
195                         else {
196                             if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
197                                 $('#'+form_id).resetForm();
198                                 $('#'+form_id+' #'+SN.C.S.NoticeDataAttachSelected).remove();
199                                 SN.U.FormNoticeEnhancements($('#'+form_id));
200                             }
201                             else {
202                                 form.append('<p class="form_response error">(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.</p>');
203                             }
204                         }
205                     }
206                 },
207                 success: function(data, textStatus) {
208                     $('#'+form_id+' .form_response').remove();
209                     var result;
210                     if ($('#'+SN.C.S.Error, data).length > 0) {
211                         result = document._importNode($('p', data)[0], true);
212                         result = result.textContent || result.innerHTML;
213                         form.append('<p class="form_response error">'+result+'</p>');
214                     }
215                     else {
216                         if($('body')[0].id == 'bookmarklet') {
217                             self.close();
218                         }
219
220                         if ($('#'+SN.C.S.CommandResult, data).length > 0) {
221                             result = document._importNode($('p', data)[0], true);
222                             result = result.textContent || result.innerHTML;
223                             form.append('<p class="form_response success">'+result+'</p>');
224                         }
225                         else {
226                             var notices = $('#notices_primary .notices');
227                             if (notices.length > 0) {
228                                 var notice = document._importNode($('li', data)[0], true);
229                                 if ($('#'+notice.id).length === 0) {
230                                     var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
231                                     var notice_irt = '#notices_primary #notice-'+notice_irt_value;
232                                     if($('body')[0].id == 'conversation') {
233                                         if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
234                                             $(notice_irt).append('<ul class="notices"></ul>');
235                                         }
236                                         $($(notice_irt+' .notices')[0]).append(notice);
237                                     }
238                                     else {
239                                         notices.prepend(notice);
240                                     }
241                                     $('#'+notice.id).css({display:'none'});
242                                     $('#'+notice.id).fadeIn(2500);
243                                     SN.U.NoticeWithAttachment($('#'+notice.id));
244                                     SN.U.NoticeReplyTo($('#'+notice.id));
245                                     SN.U.FormXHR($('#'+notice.id+' .form_favor'));
246                                 }
247                             }
248                             else {
249                                 result = document._importNode($('title', data)[0], true);
250                                 result_title = result.textContent || result.innerHTML;
251                                 form.append('<p class="form_response success">'+result_title+'</p>');
252                             }
253                         }
254                         $('#'+form_id).resetForm();
255                         $('#'+form_id+' #'+SN.C.S.NoticeDataAttachSelected).remove();
256                         SN.U.FormNoticeEnhancements($('#'+form_id));
257                     }
258                 },
259                 complete: function(xhr, textStatus) {
260                     form.removeClass(SN.C.S.Processing);
261                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled);
262                     $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
263                 }
264             });
265         },
266
267         NoticeReply: function() {
268             if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
269                 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
270             }
271         },
272
273         NoticeReplyTo: function(notice_item) {
274             var notice = notice_item[0];
275             var notice_reply = $('.notice_reply', notice)[0];
276
277             if (jQuery.data(notice_reply, "ElementData") === undefined) {
278                 jQuery.data(notice_reply, "ElementData", {Bind:'submit'});
279                 $(notice_reply).bind('click', function() {
280                     var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
281                     SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
282                     return false;
283                 });
284             }
285         },
286
287         NoticeReplySet: function(nick,id) {
288             if (nick.match(SN.C.I.PatternUsername)) {
289                 var text = $('#'+SN.C.S.NoticeDataText);
290                 if (text.length > 0) {
291                     replyto = '@' + nick + ' ';
292                     text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
293                     $('#'+SN.C.S.FormNotice+' #'+SN.C.S.NoticeInReplyTo).val(id);
294
295                     text[0].focus();
296                     if (text[0].setSelectionRange) {
297                         var len = text.val().length;
298                         text[0].setSelectionRange(len,len);
299                     }
300                 }
301             }
302         },
303
304         NoticeFavor: function() {
305             $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
306             $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
307         },
308
309         NoticeForward: function() {
310             $('.form_forward').each(function() { SN.U.FormXHR($(this)); });
311         },
312
313         NoticeAttachments: function() {
314             $('.notice a.attachment').each(function() {
315                 SN.U.NoticeWithAttachment($(this).closest('.notice'));
316             });
317         },
318
319         NoticeWithAttachment: function(notice) {
320             if ($('.attachment', notice).length === 0) {
321                 return;
322             }
323
324             var notice_id = notice.attr('id');
325
326             $.fn.jOverlay.options = {
327                 method : 'GET',
328                 data : '',
329                 url : '',
330                 color : '#000',
331                 opacity : '0.6',
332                 zIndex : 9999,
333                 center : false,
334                 imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
335                 bgClickToClose : true,
336                 success : function() {
337                     $('#jOverlayContent').append('<button class="close">&#215;</button>');
338                     $('#jOverlayContent button').click($.closeOverlay);
339                 },
340                 timeout : 0,
341                 autoHide : true,
342                 css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
343             };
344
345             $('#'+notice_id+' a.attachment').click(function() {
346                 $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
347                 return false;
348             });
349
350             var t;
351             $("body:not(#shownotice) #"+notice_id+" a.thumbnail").hover(
352                 function() {
353                     var anchor = $(this);
354                     $("a.thumbnail").children('img').hide();
355                     anchor.closest(".entry-title").addClass('ov');
356
357                     if (anchor.children('img').length === 0) {
358                         t = setTimeout(function() {
359                             $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
360                                 anchor.append(data);
361                             });
362                         }, 500);
363                     }
364                     else {
365                         anchor.children('img').show();
366                     }
367                 },
368                 function() {
369                     clearTimeout(t);
370                     $("a.thumbnail").children('img').hide();
371                     $(this).closest(".entry-title").removeClass('ov');
372                 }
373             );
374         },
375
376         NoticeDataAttach: function() {
377             NDA = $('#'+SN.C.S.NoticeDataAttach);
378             NDA.change(function() {
379                 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+$(this).val()+'</code> <button class="close">&#215;</button></div>';
380                 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
381                 if (NDAS.length > 0) {
382                     NDAS.replaceWith(S);
383                 }
384                 else {
385                     $('#'+SN.C.S.FormNotice).append(S);
386                 }
387                 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
388                     $('#'+SN.C.S.NoticeDataAttachSelected).remove();
389                     NDA.val('');
390                 });
391             });
392         },
393
394         NoticeLocationAttach: function() {
395             if(navigator.geolocation) navigator.geolocation.watchPosition(function(position) {
396                 $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
397                 $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
398             });
399         },
400
401         NewDirectMessage: function() {
402             NDM = $('.entity_send-a-message a');
403             NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
404             NDM.bind('click', function() {
405                 var NDMF = $('.entity_send-a-message form');
406                 if (NDMF.length === 0) {
407                     $(this).addClass('processing');
408                     $.get(NDM.attr('href'), null, function(data) {
409                         $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
410                         NDMF = $('.entity_send-a-message .form_notice');
411                         SN.U.FormNoticeXHR(NDMF);
412                         SN.U.FormNoticeEnhancements(NDMF);
413                         NDMF.append('<button class="close">&#215;</button>');
414                         $('.entity_send-a-message button').click(function(){
415                             NDMF.hide();
416                             return false;
417                         });
418                         NDM.removeClass('processing');
419                     });
420                 }
421                 else {
422                     NDMF.show();
423                     $('.entity_send-a-message textarea').focus();
424                 }
425                 return false;
426             });
427         }
428     },
429
430     Init: {
431         NoticeForm: function() {
432             if ($('body.user_in').length > 0) {
433                 $('.'+SN.C.S.FormNotice).each(function() {
434                     SN.U.FormNoticeXHR($(this));
435                     SN.U.FormNoticeEnhancements($(this));
436                 });
437
438                 SN.U.NoticeDataAttach();
439                 SN.U.NoticeLocationAttach();
440             }
441         },
442
443         Notices: function() {
444             if ($('body.user_in').length > 0) {
445                 SN.U.NoticeFavor();
446                 SN.U.NoticeForward();
447                 SN.U.NoticeReply();
448             }
449
450             SN.U.NoticeAttachments();
451         },
452
453         EntityActions: function() {
454             if ($('body.user_in').length > 0) {
455                 $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
456                 $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
457                 $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
458                 $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
459                 $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });
460             }
461         }
462     }
463 };
464
465 $(document).ready(function(){
466     if ($('.'+SN.C.S.FormNotice).length > 0) {
467         SN.Init.NoticeForm();
468     }
469     if ($('#content .notices').length > 0) {
470         SN.Init.Notices();
471     }
472     if ($('#content .entity_actions').length > 0) {
473         SN.Init.EntityActions();
474     }
475 });
476