2 * StatusNet - a distributed open-source microblogging tool
3 * Copyright (C) 2008, StatusNet, Inc.
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.
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.
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/>.
18 * @category UI interaction
20 * @author Sarven Capadisli <csarven@status.net>
21 * @author Evan Prodromou <evan@status.net>
22 * @author Brion Vibber <brion@status.net>
23 * @copyright 2009,2010 StatusNet, Inc.
24 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
25 * @link http://status.net/
28 var SN = { // StatusNet
31 CounterBlackout: false,
33 PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
34 HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
38 * @fixme are these worth the trouble? They seem to mostly just duplicate
39 * themselves while slightly obscuring the actual selector, so it's hard
40 * to pop over to the HTML and find something.
42 * In theory, minification could reduce them to shorter variable names,
43 * but at present that doesn't happen with yui-compressor.
50 Processing: 'processing',
51 CommandResult: 'command_result',
52 FormNotice: 'form_notice',
53 NoticeDataText: 'notice_data-text',
54 NoticeTextCount: 'notice_text-count',
55 NoticeInReplyTo: 'notice_in-reply-to',
56 NoticeDataAttach: 'notice_data-attach',
57 NoticeDataAttachSelected: 'notice_data-attach_selected',
58 NoticeActionSubmit: 'notice_action-submit',
59 NoticeLat: 'notice_data-lat',
60 NoticeLon: 'notice_data-lon',
61 NoticeLocationId: 'notice_data-location_id',
62 NoticeLocationNs: 'notice_data-location_ns',
63 NoticeGeoName: 'notice_data-geo_name',
64 NoticeDataGeo: 'notice_data-geo',
65 NoticeDataGeoCookie: 'NoticeDataGeo',
66 NoticeDataGeoSelected: 'notice_data-geo_selected',
67 StatusNetInstance:'StatusNetInstance'
72 * Map of localized message strings exported to script from the PHP
73 * side via Action::getScriptMessages().
75 * Retrieve them via SN.msg(); this array is an implementation detail.
82 * Grabs a localized string that's been previously exported to us
83 * from server-side code via Action::getScriptMessages().
85 * @example alert(SN.msg('coolplugin-failed'));
87 * @param {String} key: string key name to pull from message index
88 * @return matching localized message string
91 if (typeof SN.messages[key] == "undefined") {
92 return '[' + key + ']';
94 return SN.messages[key];
100 * Setup function -- DOES NOT trigger actions immediately.
102 * Sets up event handlers on the new notice form.
104 * @param {jQuery} form: jQuery object whose first matching element is the form
107 FormNoticeEnhancements: function(form) {
108 if (jQuery.data(form[0], 'ElementData') === undefined) {
109 MaxLength = form.find('#'+SN.C.S.NoticeTextCount).text();
110 if (typeof(MaxLength) == 'undefined') {
111 MaxLength = SN.C.I.MaxLength;
113 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
117 NDT = form.find('#'+SN.C.S.NoticeDataText);
119 NDT.bind('keyup', function(e) {
123 var delayedUpdate= function(e) {
124 // Cut and paste events fire *before* the operation,
125 // so we need to trigger an update in a little bit.
126 // This would be so much easier if the 'change' event
127 // actually fired every time the value changed. :P
128 window.setTimeout(function() {
132 // Note there's still no event for mouse-triggered 'delete'.
133 NDT.bind('cut', delayedUpdate)
134 .bind('paste', delayedUpdate);
136 NDT.bind('keydown', function(e) {
137 SN.U.SubmitOnReturn(e, form);
141 form.find('#'+SN.C.S.NoticeTextCount).text(jQuery.data(form[0], 'ElementData').MaxLength);
144 if ($('body')[0].id != 'conversation' && window.location.hash.length === 0 && $(window).scrollTop() == 0) {
145 form.find('textarea').focus();
150 * To be called from keydown event handler on the notice import form.
151 * Checks if return or enter key was pressed, and if so attempts to
152 * submit the form and cancel standard processing of the enter key.
154 * @param {Event} event
155 * @param {jQuery} el: jQuery object whose first element is the notice posting form
157 * @return {boolean} whether to cancel the event? Does this actually pass through?
160 SubmitOnReturn: function(event, el) {
161 if (event.keyCode == 13 || event.keyCode == 10) {
163 event.preventDefault();
164 event.stopPropagation();
165 $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
173 * To be called from event handlers on the notice import form.
174 * Triggers an update of the remaining-characters counter.
176 * Additional counter updates will be suppressed during the
177 * next half-second to avoid flooding the layout engine with
178 * updates, followed by another automatic check.
180 * The maximum length is pulled from data established by
181 * FormNoticeEnhancements.
183 * @param {jQuery} form: jQuery object whose first element is the notice posting form
186 Counter: function(form) {
187 SN.C.I.FormNoticeCurrent = form;
189 var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
191 if (MaxLength <= 0) {
195 var remaining = MaxLength - SN.U.CharacterCount(form);
196 var counter = form.find('#'+SN.C.S.NoticeTextCount);
198 if (remaining.toString() != counter.text()) {
199 if (!SN.C.I.CounterBlackout || remaining === 0) {
200 if (counter.text() != String(remaining)) {
201 counter.text(remaining);
204 form.addClass(SN.C.S.Warning);
206 form.removeClass(SN.C.S.Warning);
208 // Skip updates for the next 500ms.
209 // On slower hardware, updating on every keypress is unpleasant.
210 if (!SN.C.I.CounterBlackout) {
211 SN.C.I.CounterBlackout = true;
212 SN.C.I.FormNoticeCurrent = form;
213 window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
220 * Pull the count of characters in the current edit field.
221 * Plugins replacing the edit control may need to override this.
223 * @param {jQuery} form: jQuery object whose first element is the notice posting form
224 * @return number of chars
226 CharacterCount: function(form) {
227 return form.find('#'+SN.C.S.NoticeDataText).val().length;
231 * Called internally after the counter update blackout period expires;
232 * runs another update to make sure we didn't miss anything.
234 * @param {jQuery} form: jQuery object whose first element is the notice posting form
237 ClearCounterBlackout: function(form) {
238 // Allow keyup events to poke the counter again
239 SN.C.I.CounterBlackout = false;
240 // Check if the string changed since we last looked
245 * Helper function to rewrite default HTTP form action URLs to HTTPS
246 * so we can actually fetch them when on an SSL page in ssl=sometimes
249 * It would be better to output URLs that didn't hardcode protocol
250 * and hostname in the first place...
252 * @param {String} url
255 RewriteAjaxAction: function(url) {
256 // Quick hack: rewrite AJAX submits to HTTPS if they'd fail otherwise.
257 if (document.location.protocol == 'https:' && url.substr(0, 5) == 'http:') {
258 return url.replace(/^http:\/\/[^:\/]+/, 'https://' + document.location.host);
265 * Grabs form data and submits it asynchronously, with 'ajax=1'
266 * parameter added to the rest.
268 * If a successful response includes another form, that form
269 * will be extracted and copied in, replacing the original form.
270 * If there's no form, the first paragraph will be used.
272 * @fixme can sometimes explode confusingly if returnd data is bogus
273 * @fixme error handling is pretty vague
274 * @fixme can't submit file uploads
276 * @param {jQuery} form: jQuery object whose first element is a form
280 FormXHR: function(form) {
284 url: SN.U.RewriteAjaxAction(form.attr('action')),
285 data: form.serialize() + '&ajax=1',
286 beforeSend: function(xhr) {
288 .addClass(SN.C.S.Processing)
290 .addClass(SN.C.S.Disabled)
291 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
293 error: function (xhr, textStatus, errorThrown) {
294 alert(errorThrown || textStatus);
296 success: function(data, textStatus) {
297 if (typeof($('form', data)[0]) != 'undefined') {
298 form_new = document._importNode($('form', data)[0], true);
299 form.replaceWith(form_new);
302 form.replaceWith(document._importNode($('p', data)[0], true));
309 * Setup function -- DOES NOT trigger actions immediately.
311 * Sets up event handlers for special-cased async submission of the
312 * notice-posting form, including some pre-post validation.
314 * Unlike FormXHR() this does NOT submit the form immediately!
315 * It sets up event handlers so that any method of submitting the
316 * form (click on submit button, enter, submit() etc) will trigger
319 * Also unlike FormXHR(), this system will use a hidden iframe
320 * automatically to handle file uploads via <input type="file">
324 * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
325 * @fixme error handling is unreliable
326 * @fixme cookieValue is a global variable, but probably shouldn't be
327 * @fixme saving the location cache cookies should be split out
328 * @fixme some error messages are hardcoded english: needs i18n
329 * @fixme special-case for bookmarklet is confusing and uses a global var "self". Is this ok?
331 * @param {jQuery} form: jQuery object whose first element is a form
335 FormNoticeXHR: function(form) {
336 SN.C.I.NoticeDataGeo = {};
337 form.append('<input type="hidden" name="ajax" value="1"/>');
339 // Make sure we don't have a mixed HTTP/HTTPS submission...
340 form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
343 * Show a response feedback bit under the new-notice dialog.
345 * @param {String} cls: CSS class name to use ('error' or 'success')
346 * @param {String} text
349 var showFeedback = function(cls, text) {
351 $('<p class="form_response"></p>')
358 * Hide the previous response feedback, if any.
360 var removeFeedback = function() {
361 form.find('.form_response').remove();
367 beforeSend: function(formData) {
368 if (form.find('#'+SN.C.S.NoticeDataText)[0].value.length === 0) {
369 form.addClass(SN.C.S.Warning);
373 .addClass(SN.C.S.Processing)
374 .find('#'+SN.C.S.NoticeActionSubmit)
375 .addClass(SN.C.S.Disabled)
376 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
378 SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val();
379 SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val();
380 SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
381 SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val();
382 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked');
384 cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
386 if (cookieValue !== null && cookieValue != 'disabled') {
387 cookieValue = JSON.parse(cookieValue);
388 SN.C.I.NoticeDataGeo.NLat = $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat).val();
389 SN.C.I.NoticeDataGeo.NLon = $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon).val();
390 if ($('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS)) {
391 SN.C.I.NoticeDataGeo.NLNS = $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS).val();
392 SN.C.I.NoticeDataGeo.NLID = $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID).val();
395 if (cookieValue == 'disabled') {
396 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', false).attr('checked');
399 SN.C.I.NoticeDataGeo.NDG = $('#'+SN.C.S.NoticeDataGeo).attr('checked', true).attr('checked');
404 error: function (xhr, textStatus, errorThrown) {
406 .removeClass(SN.C.S.Processing)
407 .find('#'+SN.C.S.NoticeActionSubmit)
408 .removeClass(SN.C.S.Disabled)
409 .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
411 if (textStatus == 'timeout') {
413 showFeedback('error', 'Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.');
416 var response = SN.U.GetResponseXML(xhr);
417 if ($('.'+SN.C.S.Error, response).length > 0) {
418 form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
421 if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
424 .find('#'+SN.C.S.NoticeDataAttachSelected).remove();
425 SN.U.FormNoticeEnhancements(form);
429 showFeedback('error', '(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
434 success: function(data, textStatus) {
436 var errorResult = $('#'+SN.C.S.Error, data);
437 if (errorResult.length > 0) {
438 showFeedback('error', errorResult.text());
441 if($('body')[0].id == 'bookmarklet') {
442 // @fixme self is not referenced anywhere?
446 var commandResult = $('#'+SN.C.S.CommandResult, data);
447 if (commandResult.length > 0) {
448 showFeedback('success', commandResult.text());
451 // New notice post was successful. If on our timeline, show it!
452 var notice = document._importNode($('li', data)[0], true);
453 var notices = $('#notices_primary .notices:first');
454 if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
455 if ($('#'+notice.id).length === 0) {
456 var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
457 var notice_irt = '#notices_primary #notice-'+notice_irt_value;
458 if($('body')[0].id == 'conversation') {
459 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
460 $(notice_irt).append('<ul class="notices"></ul>');
462 $($(notice_irt+' .notices')[0]).append(notice);
465 notices.prepend(notice);
468 .css({display:'none'})
470 SN.U.NoticeWithAttachment($('#'+notice.id));
471 SN.U.NoticeReplyTo($('#'+notice.id));
475 // Not on a timeline that this belongs on?
476 // Just show a success message.
477 showFeedback('success', $('title', data).text());
481 form.find('#'+SN.C.S.NoticeInReplyTo).val('');
482 form.find('#'+SN.C.S.NoticeDataAttachSelected).remove();
483 SN.U.FormNoticeEnhancements(form);
486 complete: function(xhr, textStatus) {
488 .removeClass(SN.C.S.Processing)
489 .find('#'+SN.C.S.NoticeActionSubmit)
490 .removeAttr(SN.C.S.Disabled)
491 .removeClass(SN.C.S.Disabled);
493 $('#'+SN.C.S.NoticeLat).val(SN.C.I.NoticeDataGeo.NLat);
494 $('#'+SN.C.S.NoticeLon).val(SN.C.I.NoticeDataGeo.NLon);
495 if ($('#'+SN.C.S.NoticeLocationNs)) {
496 $('#'+SN.C.S.NoticeLocationNs).val(SN.C.I.NoticeDataGeo.NLNS);
497 $('#'+SN.C.S.NoticeLocationId).val(SN.C.I.NoticeDataGeo.NLID);
499 $('#'+SN.C.S.NoticeDataGeo).attr('checked', SN.C.I.NoticeDataGeo.NDG);
505 * Fetch an XML DOM from an XHR's response data.
507 * Works around unavailable responseXML when document.domain
508 * has been modified by Meteor or other tools, in some but not
511 * @param {XMLHTTPRequest} xhr
512 * @return DOMDocument
514 GetResponseXML: function(xhr) {
516 return xhr.responseXML;
518 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
523 * Setup function -- DOES NOT trigger actions immediately.
525 * Sets up event handlers on all visible notice's reply buttons to
526 * tweak the new-notice form with needed variables and focus it
529 * (This replaces the default reply button behavior to submit
530 * directly to a form which comes back with a specialized page
531 * with the form data prefilled.)
535 NoticeReply: function() {
536 if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
537 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
542 * Setup function -- DOES NOT trigger actions immediately.
544 * Sets up event handlers on the given notice's reply button to
545 * tweak the new-notice form with needed variables and focus it
548 * (This replaces the default reply button behavior to submit
549 * directly to a form which comes back with a specialized page
550 * with the form data prefilled.)
552 * @param {jQuery} notice: jQuery object containing one or more notices
555 NoticeReplyTo: function(notice) {
556 notice.find('.notice_reply').live('click', function(e) {
558 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
559 /* SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text()); */
560 SN.U.NoticeInlineReplyTrigger(notice, '@' + nickname.text());
566 * Open up a notice's inline reply box.
568 * @param {jQuery} notice: jQuery object containing one notice
569 * @param {String} initialText
571 NoticeInlineReplyTrigger: function(notice, initialText) {
572 // Find the notice we're replying to...
573 var id = $($('.notice_id', notice)[0]).text();
574 var parentNotice = notice;
576 // Find the threaded replies view we'll be adding to...
577 var list = notice.closest('.notices');
578 if (list.hasClass('threaded-replies')) {
579 // We're replying to a reply; use reply form on the end of this list.
580 // We'll add our form at the end of this; grab the root notice.
581 parentNotice = list.closest('.notice');
583 // We're replying to a parent notice; pull its threaded list
584 // and we'll add on the end of it. Will add if needed.
585 list = $('ul.threaded-replies', notice);
586 if (list.length == 0) {
587 list = $('<ul class="notices threaded-replies xoxo"></ul>');
592 // See if the form's already open...
593 var replyForm = $('.notice-reply-form', list);
594 if (replyForm.length == 0) {
595 // Remove placeholder if any
596 $('li.notice-reply-placeholder').remove();
598 // Create the reply form entry at the end
599 var replyItem = $('li.notice-reply', list);
600 if (replyItem.length == 0) {
601 replyItem = $('<li class="notice-reply">' +
602 '<form class="notice-reply-form" method="post">' +
603 '<textarea name="status_textarea"></textarea>' +
604 '<div class="controls">' +
605 '<input type="hidden" name="token">' +
606 '<input type="hidden" name="inreplyto">' +
607 '<input type="submit" class="submit">' +
612 var baseForm = $('#form_notice');
613 replyForm = replyItem.find('form');
614 replyForm.attr('action', baseForm.attr('action'));
615 replyForm.find('input[name="token"]').val(baseForm.find('input[name=token]').val());
616 replyForm.find('input[type="submit"]').val(SN.msg('reply_submit'));
617 list.append(replyItem);
619 replyForm.find('textarea').blur(function() {
620 var textarea = $(this);
621 var txt = $.trim(textarea.val());
622 if (txt == '' || txt == textarea.data('initialText')) {
623 // Nothing to say? Begone!
625 if (list.find('li').length > 0) {
626 SN.U.NoticeInlineReplyPlaceholder(parentNotice);
632 replyForm.submit(function(event) {
633 var form = replyForm;
637 url: SN.U.RewriteAjaxAction(form.attr('action')),
638 data: form.serialize() + '&ajax=1',
639 beforeSend: function(xhr) {
641 .addClass(SN.C.S.Processing)
643 .addClass(SN.C.S.Disabled)
644 .attr(SN.C.S.Disabled, SN.C.S.Disabled)
647 .addClass(SN.C.S.Disabled)
648 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
650 error: function (xhr, textStatus, errorThrown) {
651 alert(errorThrown || textStatus);
653 success: function(data, textStatus) {
654 var orig_li = $('li', data)[0];
656 var li = document._importNode(orig_li, true);
657 var id = $(li).attr('id');
658 if ($("#"+id).length == 0) {
659 replyItem.replaceWith(li);
660 SN.U.NoticeInlineReplyPlaceholder(parentNotice);
662 // Realtime came through before us...
668 event.preventDefault();
675 replyForm.find('input[name=inreplyto]').val(id);
678 var text = replyForm.find('textarea');
679 if (text.length == 0) {
684 replyto = initialText + ' ';
686 text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
687 text.data('initialText', $.trim(initialText + ''));
689 if (text[0].setSelectionRange) {
690 var len = text.val().length;
691 text[0].setSelectionRange(len,len);
697 * Updates the new notice posting form with bits for replying to the
698 * given user. Adds replyto parameter to the form, and a "@foo" to the
701 * @fixme replyto is a global variable, but probably shouldn't be
703 * @param {String} nick
706 NoticeReplySet: function(nick,id) {
707 if (nick.match(SN.C.I.PatternUsername)) {
708 var text = $('#'+SN.C.S.NoticeDataText);
709 if (text.length > 0) {
710 replyto = '@' + nick + ' ';
711 text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
712 $('#'+SN.C.S.FormNotice+' #'+SN.C.S.NoticeInReplyTo).val(id);
715 if (text[0].setSelectionRange) {
716 var len = text.val().length;
717 text[0].setSelectionRange(len,len);
724 * Setup function -- DOES NOT apply immediately.
726 * Sets up event handlers for favor/disfavor forms to submit via XHR.
727 * Uses 'live' rather than 'bind', so applies to future as well as present items.
729 NoticeFavor: function() {
730 $('.form_favor').live('click', function() { SN.U.FormXHR($(this)); return false; });
731 $('.form_disfavor').live('click', function() { SN.U.FormXHR($(this)); return false; });
734 NoticeInlineReplyPlaceholder: function(notice) {
735 var list = notice.find('ul.threaded-replies');
736 var placeholder = $('<li class="notice-reply-placeholder">' +
737 '<input class="placeholder">' +
739 placeholder.click(function() {
740 SN.U.NoticeInlineReplyTrigger(notice);
742 placeholder.find('input').val(SN.msg('reply_comment'));
743 list.append(placeholder);
747 * Setup function -- DOES NOT apply immediately.
749 * Sets up event handlers for favor/disfavor forms to submit via XHR.
750 * Uses 'live' rather than 'bind', so applies to future as well as present items.
752 NoticeInlineReplySetup: function() {
753 $('.threaded-replies').each(function() {
755 var notice = list.closest('.notice');
756 SN.U.NoticeInlineReplyPlaceholder(notice);
761 * Setup function -- DOES NOT trigger actions immediately.
763 * Sets up event handlers for repeat forms to toss up a confirmation
764 * popout before submitting.
766 * Uses 'live' rather than 'bind', so applies to future as well as present items.
768 NoticeRepeat: function() {
769 $('.form_repeat').live('click', function(e) {
772 SN.U.NoticeRepeatConfirmation($(this));
778 * Shows a confirmation dialog box variant of the repeat button form.
779 * This seems to use a technique where the repeat form contains
780 * _both_ a standalone button _and_ text and buttons for a dialog.
781 * The dialog will close after its copy of the form is submitted,
782 * or if you click its 'close' button.
784 * The dialog is created by duplicating the original form and changing
785 * its style; while clever, this is hard to generalize and probably
786 * duplicates a lot of unnecessary HTML output.
788 * @fixme create confirmation dialogs through a generalized interface
789 * that can be reused instead of hardcoded text and styles.
791 * @param {jQuery} form
793 NoticeRepeatConfirmation: function(form) {
794 var submit_i = form.find('.submit');
796 var submit = submit_i.clone();
798 .addClass('submit_dialogbox')
799 .removeClass('submit');
801 submit.bind('click', function() { SN.U.FormXHR(form); return false; });
806 .addClass('dialogbox')
807 .append('<button class="close">×</button>')
808 .closest('.notice-options')
811 form.find('button.close').click(function(){
815 .removeClass('dialogbox')
816 .closest('.notice-options')
817 .removeClass('opaque');
819 form.find('.submit_dialogbox').remove();
820 form.find('.submit').show();
827 * Setup function -- DOES NOT trigger actions immediately.
829 * Goes through all notices currently displayed and sets up attachment
830 * handling if needed.
832 NoticeAttachments: function() {
833 $('.notice a.attachment').each(function() {
834 SN.U.NoticeWithAttachment($(this).closest('.notice'));
839 * Setup function -- DOES NOT trigger actions immediately.
841 * Sets up special attachment link handling if needed. Currently this
842 * consists only of making the "more" button used for OStatus message
843 * cropping turn into an auto-expansion button that loads the full
844 * text from an attachment file.
846 * @param {jQuery} notice
848 NoticeWithAttachment: function(notice) {
849 if (notice.find('.attachment').length === 0) {
853 var attachment_more = notice.find('.attachment.more');
854 if (attachment_more.length > 0) {
855 $(attachment_more[0]).click(function() {
857 m.addClass(SN.C.S.Processing);
858 $.get(m.attr('href')+'/ajax', null, function(data) {
859 m.parent('.entry-content').html($(data).find('#attachment_view .entry-content').html());
863 }).attr('title', SN.msg('showmore_tooltip'));
868 * Setup function -- DOES NOT trigger actions immediately.
870 * Sets up event handlers for the file-attachment widget in the
871 * new notice form. When a file is selected, a box will be added
872 * below the text input showing the filename and, if supported
873 * by the browser, a thumbnail preview.
875 * This preview box will also allow removing the attachment
878 NoticeDataAttach: function() {
879 NDA = $('#'+SN.C.S.NoticeDataAttach);
880 NDA.change(function(event) {
881 var filename = $(this).val();
883 // No file -- we've been tricked!
884 $('#'+SN.C.S.NoticeDataAttachSelected).remove();
888 // @fixme appending filename straight in is potentially unsafe
889 S = '<div id="'+SN.C.S.NoticeDataAttachSelected+'" class="'+SN.C.S.Success+'"><code>'+filename+'</code> <button class="close">×</button></div>';
890 NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
891 if (NDAS.length > 0) {
895 $('#'+SN.C.S.FormNotice).append(S);
897 $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
898 $('#'+SN.C.S.NoticeDataAttachSelected).remove();
903 if (typeof this.files == "object") {
904 // Some newer browsers will let us fetch the files for preview.
905 for (var i = 0; i < this.files.length; i++) {
906 SN.U.PreviewAttach(this.files[i]);
913 * Get PHP's MAX_FILE_SIZE setting for this form;
914 * used to apply client-side file size limit checks.
916 * @param {jQuery} form
917 * @return int max size in bytes; 0 or negative means no limit
919 maxFileSize: function(form) {
920 var max = $(form).find('input[name=MAX_FILE_SIZE]').attr('value');
922 return parseInt(max);
929 * For browsers with FileAPI support: make a thumbnail if possible,
930 * and append it into the attachment display widget.
933 * - Firefox 3.6.6, 4.0b7
934 * - Chrome 8.0.552.210
936 * Known ok metadata, can't get contents:
940 * - Opera 10.63, 11 beta (no input.files interface)
944 * @todo use configured thumbnail size
945 * @todo detect pixel size?
946 * @todo should we render a thumbnail to a canvas and then use the smaller image?
948 PreviewAttach: function(file) {
949 var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
953 if (typeof window.createObjectURL != "undefined") {
955 * createObjectURL lets us reference the file directly from an <img>
956 * This produces a compact URL with an opaque reference to the file,
957 * which we can reference immediately.
959 * - Firefox 3.6.6: no
960 * - Firefox 4.0b7: no
962 * - Chrome 8.0.552.210: works!
964 blobAsDataURL = function(blob, callback) {
965 callback(window.createObjectURL(blob));
967 } else if (typeof window.FileReader != "undefined") {
969 * FileAPI's FileReader can build a data URL from a blob's contents,
970 * but it must read the file and build it asynchronously. This means
971 * we'll be passing a giant data URL around, which may be inefficient.
973 * - Firefox 3.6.6: works!
974 * - Firefox 4.0b7: works!
976 * - Chrome 8.0.552.210: works!
978 blobAsDataURL = function(blob, callback) {
979 var reader = new FileReader();
980 reader.onload = function(event) {
981 callback(reader.result);
983 reader.readAsDataURL(blob);
989 var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
990 if ($.inArray(file.type, imageTypes) == -1) {
991 // We probably don't know how to show the file.
995 var maxSize = 8 * 1024 * 1024;
996 if (file.size > maxSize) {
997 // Don't kill the browser trying to load some giant image.
1002 blobAsDataURL(file, function(url) {
1003 var img = $('<img>')
1004 .attr('title', tooltip)
1005 .attr('alt', tooltip)
1007 .attr('style', 'height: 120px');
1008 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
1011 var img = $('<div></div>').text(tooltip);
1012 $('#'+SN.C.S.NoticeDataAttachSelected).append(img);
1017 * Setup function -- DOES NOT trigger actions immediately.
1019 * Initializes state for the location-lookup features in the
1020 * new-notice form. Seems to set up some event handlers for
1021 * triggering lookups and using the new values.
1024 * @fixme there's not good visual state update here, so users have a
1025 * hard time figuring out if it's working or fixing if it's wrong.
1028 NoticeLocationAttach: function() {
1029 var NLat = $('#'+SN.C.S.NoticeLat).val();
1030 var NLon = $('#'+SN.C.S.NoticeLon).val();
1031 var NLNS = $('#'+SN.C.S.NoticeLocationNs).val();
1032 var NLID = $('#'+SN.C.S.NoticeLocationId).val();
1033 var NLN = $('#'+SN.C.S.NoticeGeoName).text();
1034 var NDGe = $('#'+SN.C.S.NoticeDataGeo);
1036 function removeNoticeDataGeo() {
1037 $('label[for='+SN.C.S.NoticeDataGeo+']')
1038 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
1039 .removeClass('checked');
1041 $('#'+SN.C.S.NoticeLat).val('');
1042 $('#'+SN.C.S.NoticeLon).val('');
1043 $('#'+SN.C.S.NoticeLocationNs).val('');
1044 $('#'+SN.C.S.NoticeLocationId).val('');
1045 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
1047 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
1050 function getJSONgeocodeURL(geocodeURL, data) {
1051 $.getJSON(geocodeURL, data, function(location) {
1054 if (typeof(location.location_ns) != 'undefined') {
1055 $('#'+SN.C.S.NoticeLocationNs).val(location.location_ns);
1056 lns = location.location_ns;
1059 if (typeof(location.location_id) != 'undefined') {
1060 $('#'+SN.C.S.NoticeLocationId).val(location.location_id);
1061 lid = location.location_id;
1064 if (typeof(location.name) == 'undefined') {
1065 NLN_text = data.lat + ';' + data.lon;
1068 NLN_text = location.name;
1071 $('label[for='+SN.C.S.NoticeDataGeo+']')
1072 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
1074 $('#'+SN.C.S.NoticeLat).val(data.lat);
1075 $('#'+SN.C.S.NoticeLon).val(data.lon);
1076 $('#'+SN.C.S.NoticeLocationNs).val(lns);
1077 $('#'+SN.C.S.NoticeLocationId).val(lid);
1078 $('#'+SN.C.S.NoticeDataGeo).attr('checked', true);
1090 $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
1094 if (NDGe.length > 0) {
1095 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1096 NDGe.attr('checked', false);
1099 NDGe.attr('checked', true);
1102 var NGW = $('#notice_data-geo_wrap');
1103 var geocodeURL = NGW.attr('title');
1104 NGW.removeAttr('title');
1106 $('label[for='+SN.C.S.NoticeDataGeo+']')
1107 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
1109 NDGe.change(function() {
1110 if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
1111 $('label[for='+SN.C.S.NoticeDataGeo+']')
1112 .attr('title', NoticeDataGeo_text.ShareDisable)
1113 .addClass('checked');
1115 if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1116 if (navigator.geolocation) {
1117 navigator.geolocation.getCurrentPosition(
1118 function(position) {
1119 $('#'+SN.C.S.NoticeLat).val(position.coords.latitude);
1120 $('#'+SN.C.S.NoticeLon).val(position.coords.longitude);
1123 lat: position.coords.latitude,
1124 lon: position.coords.longitude,
1125 token: $('#token').val()
1128 getJSONgeocodeURL(geocodeURL, data);
1132 switch(error.code) {
1133 case error.PERMISSION_DENIED:
1134 removeNoticeDataGeo();
1137 $('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
1148 if (NLat.length > 0 && NLon.length > 0) {
1152 token: $('#token').val()
1155 getJSONgeocodeURL(geocodeURL, data);
1158 removeNoticeDataGeo();
1159 $('#'+SN.C.S.NoticeDataGeo).remove();
1160 $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
1165 var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
1167 $('#'+SN.C.S.NoticeLat).val(cookieValue.NLat);
1168 $('#'+SN.C.S.NoticeLon).val(cookieValue.NLon);
1169 $('#'+SN.C.S.NoticeLocationNs).val(cookieValue.NLNS);
1170 $('#'+SN.C.S.NoticeLocationId).val(cookieValue.NLID);
1171 $('#'+SN.C.S.NoticeDataGeo).attr('checked', cookieValue.NDG);
1173 $('label[for='+SN.C.S.NoticeDataGeo+']')
1174 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
1175 .addClass('checked');
1179 removeNoticeDataGeo();
1186 * Setup function -- DOES NOT trigger actions immediately.
1188 * Initializes event handlers for the "Send direct message" link on
1189 * profile pages, setting it up to display a dialog box when clicked.
1191 * Unlike the repeat confirmation form, this appears to fetch
1192 * the form _from the original link target_, so the form itself
1193 * doesn't need to be in the current document.
1195 * @fixme breaks ability to open link in new window?
1197 NewDirectMessage: function() {
1198 NDM = $('.entity_send-a-message a');
1199 NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
1200 NDM.bind('click', function() {
1201 var NDMF = $('.entity_send-a-message form');
1202 if (NDMF.length === 0) {
1203 $(this).addClass(SN.C.S.Processing);
1204 $.get(NDM.attr('href'), null, function(data) {
1205 $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
1206 NDMF = $('.entity_send-a-message .form_notice');
1207 SN.U.FormNoticeXHR(NDMF);
1208 SN.U.FormNoticeEnhancements(NDMF);
1209 NDMF.append('<button class="close">×</button>');
1210 $('.entity_send-a-message button').click(function(){
1214 NDM.removeClass(SN.C.S.Processing);
1219 $('.entity_send-a-message textarea').focus();
1226 * Return a date object with the current local time on the
1227 * given year, month, and day.
1229 * @param {number} year: 4-digit year
1230 * @param {number} month: 0 == January
1231 * @param {number} day: 1 == 1
1234 GetFullYear: function(year, month, day) {
1235 var date = new Date();
1236 date.setFullYear(year, month, day);
1242 * Some sort of object interface for storing some structured
1243 * information in a cookie.
1245 * Appears to be used to save the last-used login nickname?
1246 * That's something that browsers usually take care of for us
1247 * these days, do we really need to do it? Does anything else
1248 * use this interface?
1250 * @fixme what is this?
1251 * @fixme should this use non-cookie local storage when available?
1253 StatusNetInstance: {
1255 * @fixme what is this?
1257 Set: function(value) {
1258 var SNI = SN.U.StatusNetInstance.Get();
1260 value = $.extend(SNI, value);
1264 SN.C.S.StatusNetInstance,
1265 JSON.stringify(value),
1268 expires: SN.U.GetFullYear(2029, 0, 1)
1273 * @fixme what is this?
1276 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1277 if (cookieValue !== null) {
1278 return JSON.parse(cookieValue);
1284 * @fixme what is this?
1286 Delete: function() {
1287 $.cookie(SN.C.S.StatusNetInstance, null);
1292 * Check if the current page is a timeline where the current user's
1293 * posts should be displayed immediately on success.
1295 * @fixme this should be done in a saner way, with machine-readable
1296 * info about what page we're looking at.
1298 * @param {DOMElement} notice: HTML chunk with formatted notice
1301 belongsOnTimeline: function(notice) {
1302 var action = $("body").attr('id');
1303 if (action == 'public') {
1307 var profileLink = $('#nav_profile a').attr('href');
1309 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
1310 if (authorUrl == profileLink) {
1311 if (action == 'all' || action == 'showstream') {
1312 // Posts always show on your own friends and profile streams.
1318 // @fixme tag, group, reply timelines should be feasible as well.
1319 // Mismatch between id-based and name-based user/group links currently complicates
1320 // the lookup, since all our inline mentions contain the absolute links but the
1321 // UI links currently on the page use malleable names.
1329 * If user is logged in, run setup code for the new notice form:
1334 * - file upload events
1336 NoticeForm: function() {
1337 if ($('body.user_in').length > 0) {
1338 SN.U.NoticeLocationAttach();
1340 $('.'+SN.C.S.FormNotice).each(function() {
1341 SN.U.FormNoticeXHR($(this));
1342 SN.U.FormNoticeEnhancements($(this));
1345 SN.U.NoticeDataAttach();
1350 * Run setup code for notice timeline views items:
1352 * - AJAX submission for fave/repeat/reply (if logged in)
1353 * - Attachment link extras ('more' links)
1355 Notices: function() {
1356 if ($('body.user_in').length > 0) {
1358 SN.U.NoticeRepeat();
1360 SN.U.NoticeInlineReplySetup();
1363 SN.U.NoticeAttachments();
1367 * Run setup code for user & group profile page header area if logged in:
1369 * - AJAX submission for sub/unsub/join/leave/nudge
1370 * - AJAX form popup for direct-message
1372 EntityActions: function() {
1373 if ($('body.user_in').length > 0) {
1374 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1375 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1376 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
1377 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
1378 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
1380 SN.U.NewDirectMessage();
1385 * Run setup code for login form:
1387 * - loads saved last-used-nickname from cookie
1388 * - sets event handler to save nickname to cookie on submit
1390 * @fixme is this necessary? Browsers do their own form saving these days.
1393 if (SN.U.StatusNetInstance.Get() !== null) {
1394 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1395 if (nickname !== null) {
1396 $('#form_login #nickname').val(nickname);
1400 $('#form_login').bind('submit', function() {
1401 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1407 * Add logic to any file upload forms to handle file size limits,
1408 * on browsers that support basic FileAPI.
1410 UploadForms: function () {
1411 $('input[type=file]').change(function(event) {
1412 if (typeof this.files == "object" && this.files.length > 0) {
1414 for (var i = 0; i < this.files.length; i++) {
1415 size += this.files[i].size;
1418 var max = SN.U.maxFileSize($(this.form));
1419 if (max > 0 && size > max) {
1420 var msg = 'File too large: maximum upload size is %d bytes.';
1421 alert(msg.replace('%d', max));
1425 event.preventDefault();
1435 * Run initialization functions on DOM-ready.
1437 * Note that if we're waiting on other scripts to load, this won't happen
1438 * until that's done. To load scripts asynchronously without delaying setup,
1439 * don't start them loading until after DOM-ready time!
1441 $(document).ready(function(){
1442 SN.Init.UploadForms();
1443 if ($('.'+SN.C.S.FormNotice).length > 0) {
1444 SN.Init.NoticeForm();
1446 if ($('#content .notices').length > 0) {
1449 if ($('#content .entity_actions').length > 0) {
1450 SN.Init.EntityActions();
1452 if ($('#form_login').length > 0) {