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 NoticeInReplyTo: 'notice_in-reply-to',
54 NoticeLat: 'notice_data-lat',
55 NoticeLon: 'notice_data-lon',
56 NoticeLocationId: 'notice_data-location_id',
57 NoticeLocationNs: 'notice_data-location_ns',
58 NoticeGeoName: 'notice_data-geo_name',
59 NoticeDataGeo: 'notice_data-geo',
60 NoticeDataGeoCookie: 'NoticeDataGeo',
61 NoticeDataGeoSelected: 'notice_data-geo_selected',
62 StatusNetInstance:'StatusNetInstance'
67 * Map of localized message strings exported to script from the PHP
68 * side via Action::getScriptMessages().
70 * Retrieve them via SN.msg(); this array is an implementation detail.
77 * Grabs a localized string that's been previously exported to us
78 * from server-side code via Action::getScriptMessages().
80 * @example alert(SN.msg('coolplugin-failed'));
82 * @param {String} key: string key name to pull from message index
83 * @return matching localized message string
86 if (typeof SN.messages[key] == "undefined") {
87 return '[' + key + ']';
89 return SN.messages[key];
95 * Setup function -- DOES NOT trigger actions immediately.
97 * Sets up event handlers on the new notice form.
99 * @param {jQuery} form: jQuery object whose first matching element is the form
102 FormNoticeEnhancements: function(form) {
103 if (jQuery.data(form[0], 'ElementData') === undefined) {
104 MaxLength = form.find('.count').text();
105 if (typeof(MaxLength) == 'undefined') {
106 MaxLength = SN.C.I.MaxLength;
108 jQuery.data(form[0], 'ElementData', {MaxLength:MaxLength});
112 NDT = form.find('[name=status_textarea]');
114 NDT.bind('keyup', function(e) {
118 var delayedUpdate= function(e) {
119 // Cut and paste events fire *before* the operation,
120 // so we need to trigger an update in a little bit.
121 // This would be so much easier if the 'change' event
122 // actually fired every time the value changed. :P
123 window.setTimeout(function() {
127 // Note there's still no event for mouse-triggered 'delete'.
128 NDT.bind('cut', delayedUpdate)
129 .bind('paste', delayedUpdate);
132 form.find('.count').text(jQuery.data(form[0], 'ElementData').MaxLength);
137 * To be called from event handlers on the notice import form.
138 * Triggers an update of the remaining-characters counter.
140 * Additional counter updates will be suppressed during the
141 * next half-second to avoid flooding the layout engine with
142 * updates, followed by another automatic check.
144 * The maximum length is pulled from data established by
145 * FormNoticeEnhancements.
147 * @param {jQuery} form: jQuery object whose first element is the notice posting form
150 Counter: function(form) {
151 SN.C.I.FormNoticeCurrent = form;
153 var MaxLength = jQuery.data(form[0], 'ElementData').MaxLength;
155 if (MaxLength <= 0) {
159 var remaining = MaxLength - SN.U.CharacterCount(form);
160 var counter = form.find('.count');
162 if (remaining.toString() != counter.text()) {
163 if (!SN.C.I.CounterBlackout || remaining === 0) {
164 if (counter.text() != String(remaining)) {
165 counter.text(remaining);
168 form.addClass(SN.C.S.Warning);
170 form.removeClass(SN.C.S.Warning);
172 // Skip updates for the next 500ms.
173 // On slower hardware, updating on every keypress is unpleasant.
174 if (!SN.C.I.CounterBlackout) {
175 SN.C.I.CounterBlackout = true;
176 SN.C.I.FormNoticeCurrent = form;
177 window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
184 * Pull the count of characters in the current edit field.
185 * Plugins replacing the edit control may need to override this.
187 * @param {jQuery} form: jQuery object whose first element is the notice posting form
188 * @return number of chars
190 CharacterCount: function(form) {
191 return form.find('[name=status_textarea]').val().length;
195 * Called internally after the counter update blackout period expires;
196 * runs another update to make sure we didn't miss anything.
198 * @param {jQuery} form: jQuery object whose first element is the notice posting form
201 ClearCounterBlackout: function(form) {
202 // Allow keyup events to poke the counter again
203 SN.C.I.CounterBlackout = false;
204 // Check if the string changed since we last looked
209 * Helper function to rewrite default HTTP form action URLs to HTTPS
210 * so we can actually fetch them when on an SSL page in ssl=sometimes
213 * It would be better to output URLs that didn't hardcode protocol
214 * and hostname in the first place...
216 * @param {String} url
219 RewriteAjaxAction: function(url) {
220 // Quick hack: rewrite AJAX submits to HTTPS if they'd fail otherwise.
221 if (document.location.protocol == 'https:' && url.substr(0, 5) == 'http:') {
222 return url.replace(/^http:\/\/[^:\/]+/, 'https://' + document.location.host);
229 * Grabs form data and submits it asynchronously, with 'ajax=1'
230 * parameter added to the rest.
232 * If a successful response includes another form, that form
233 * will be extracted and copied in, replacing the original form.
234 * If there's no form, the first paragraph will be used.
236 * @fixme can sometimes explode confusingly if returnd data is bogus
237 * @fixme error handling is pretty vague
238 * @fixme can't submit file uploads
240 * @param {jQuery} form: jQuery object whose first element is a form
244 FormXHR: function(form) {
248 url: SN.U.RewriteAjaxAction(form.attr('action')),
249 data: form.serialize() + '&ajax=1',
250 beforeSend: function(xhr) {
252 .addClass(SN.C.S.Processing)
254 .addClass(SN.C.S.Disabled)
255 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
257 error: function (xhr, textStatus, errorThrown) {
258 alert(errorThrown || textStatus);
260 success: function(data, textStatus) {
261 if (typeof($('form', data)[0]) != 'undefined') {
262 form_new = document._importNode($('form', data)[0], true);
263 form.replaceWith(form_new);
266 form.replaceWith(document._importNode($('p', data)[0], true));
273 * Setup function -- DOES NOT trigger actions immediately.
275 * Sets up event handlers for special-cased async submission of the
276 * notice-posting form, including some pre-post validation.
278 * Unlike FormXHR() this does NOT submit the form immediately!
279 * It sets up event handlers so that any method of submitting the
280 * form (click on submit button, enter, submit() etc) will trigger
283 * Also unlike FormXHR(), this system will use a hidden iframe
284 * automatically to handle file uploads via <input type="file">
288 * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
289 * @fixme error handling is unreliable
290 * @fixme cookieValue is a global variable, but probably shouldn't be
291 * @fixme saving the location cache cookies should be split out
292 * @fixme some error messages are hardcoded english: needs i18n
293 * @fixme special-case for bookmarklet is confusing and uses a global var "self". Is this ok?
295 * @param {jQuery} form: jQuery object whose first element is a form
299 FormNoticeXHR: function(form) {
300 SN.C.I.NoticeDataGeo = {};
301 form.append('<input type="hidden" name="ajax" value="1"/>');
303 // Make sure we don't have a mixed HTTP/HTTPS submission...
304 form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
307 * Show a response feedback bit under the new-notice dialog.
309 * @param {String} cls: CSS class name to use ('error' or 'success')
310 * @param {String} text
313 var showFeedback = function(cls, text) {
315 $('<p class="form_response"></p>')
322 * Hide the previous response feedback, if any.
324 var removeFeedback = function() {
325 form.find('.form_response').remove();
331 beforeSend: function(formData) {
332 if (form.find('[name=status_textarea]').val() == '') {
333 form.addClass(SN.C.S.Warning);
337 .addClass(SN.C.S.Processing)
339 .addClass(SN.C.S.Disabled)
340 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
342 SN.U.normalizeGeoData(form);
346 error: function (xhr, textStatus, errorThrown) {
348 .removeClass(SN.C.S.Processing)
350 .removeClass(SN.C.S.Disabled)
351 .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
353 if (textStatus == 'timeout') {
355 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.');
358 var response = SN.U.GetResponseXML(xhr);
359 if ($('.'+SN.C.S.Error, response).length > 0) {
360 form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
363 if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
366 .find('.attach-status').remove();
367 SN.U.FormNoticeEnhancements(form);
371 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.');
376 success: function(data, textStatus) {
378 var errorResult = $('#'+SN.C.S.Error, data);
379 if (errorResult.length > 0) {
380 showFeedback('error', errorResult.text());
383 if($('body')[0].id == 'bookmarklet') {
384 // @fixme self is not referenced anywhere?
388 var commandResult = $('#'+SN.C.S.CommandResult, data);
389 if (commandResult.length > 0) {
390 showFeedback('success', commandResult.text());
393 // New notice post was successful. If on our timeline, show it!
394 var notice = document._importNode($('li', data)[0], true);
395 var notices = $('#notices_primary .notices:first');
396 if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
397 if ($('#'+notice.id).length === 0) {
398 var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
399 var notice_irt = '#notices_primary #notice-'+notice_irt_value;
400 if($('body')[0].id == 'conversation') {
401 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
402 $(notice_irt).append('<ul class="notices"></ul>');
404 $($(notice_irt+' .notices')[0]).append(notice);
407 notices.prepend(notice);
410 .css({display:'none'})
412 SN.U.NoticeWithAttachment($('#'+notice.id));
413 SN.U.NoticeReplyTo($('#'+notice.id));
417 // Not on a timeline that this belongs on?
418 // Just show a success message.
419 showFeedback('success', $('title', data).text());
423 form.find('[name=inreplyto]').val('');
424 form.find('.attach-status').remove();
425 SN.U.FormNoticeEnhancements(form);
428 complete: function(xhr, textStatus) {
430 .removeClass(SN.C.S.Processing)
432 .removeAttr(SN.C.S.Disabled)
433 .removeClass(SN.C.S.Disabled);
435 form.find('[name=lat]').val(SN.C.I.NoticeDataGeo.NLat);
436 form.find('[name=lon]').val(SN.C.I.NoticeDataGeo.NLon);
437 form.find('[name=location_ns]').val(SN.C.I.NoticeDataGeo.NLNS);
438 form.find('[name=location_id]').val(SN.C.I.NoticeDataGeo.NLID);
439 form.find('[name=notice_data-geo]').attr('checked', SN.C.I.NoticeDataGeo.NDG);
444 normalizeGeoData: function(form) {
445 SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val();
446 SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val();
447 SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val();
448 SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val();
449 SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').attr('checked'); // @fixme
451 var cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
453 if (cookieValue !== null && cookieValue != 'disabled') {
454 cookieValue = JSON.parse(cookieValue);
455 SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val(cookieValue.NLat).val();
456 SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val(cookieValue.NLon).val();
457 if (cookieValue.NLNS) {
458 SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val(cookieValue.NLNS).val();
459 SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val(cookieValue.NLID).val();
461 form.find('[name=location_ns]').val('');
462 form.find('[name=location_id]').val('');
465 if (cookieValue == 'disabled') {
466 SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').attr('checked', false).attr('checked');
469 SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').attr('checked', true).attr('checked');
474 * Fetch an XML DOM from an XHR's response data.
476 * Works around unavailable responseXML when document.domain
477 * has been modified by Meteor or other tools, in some but not
480 * @param {XMLHTTPRequest} xhr
481 * @return DOMDocument
483 GetResponseXML: function(xhr) {
485 return xhr.responseXML;
487 return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
492 * Setup function -- DOES NOT trigger actions immediately.
494 * Sets up event handlers on all visible notice's reply buttons to
495 * tweak the new-notice form with needed variables and focus it
498 * (This replaces the default reply button behavior to submit
499 * directly to a form which comes back with a specialized page
500 * with the form data prefilled.)
504 NoticeReply: function() {
505 if ($('#content .notice_reply').length > 0) {
506 $('#content .notice').each(function() { SN.U.NoticeReplyTo($(this)); });
511 * Setup function -- DOES NOT trigger actions immediately.
513 * Sets up event handlers on the given notice's reply button to
514 * tweak the new-notice form with needed variables and focus it
517 * (This replaces the default reply button behavior to submit
518 * directly to a form which comes back with a specialized page
519 * with the form data prefilled.)
521 * @param {jQuery} notice: jQuery object containing one or more notices
524 NoticeReplyTo: function(notice) {
525 notice.find('.notice_reply').live('click', function(e) {
527 var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
528 SN.U.NoticeInlineReplyTrigger(notice, '@' + nickname.text());
534 * Open up a notice's inline reply box.
536 * @param {jQuery} notice: jQuery object containing one notice
537 * @param {String} initialText
539 NoticeInlineReplyTrigger: function(notice, initialText) {
540 // Find the notice we're replying to...
541 var id = $($('.notice_id', notice)[0]).text();
542 var parentNotice = notice;
544 // Find the threaded replies view we'll be adding to...
545 var list = notice.closest('.notices');
546 if (list.hasClass('threaded-replies')) {
547 // We're replying to a reply; use reply form on the end of this list.
548 // We'll add our form at the end of this; grab the root notice.
549 parentNotice = list.closest('.notice');
551 // We're replying to a parent notice; pull its threaded list
552 // and we'll add on the end of it. Will add if needed.
553 list = $('ul.threaded-replies', notice);
554 if (list.length == 0) {
555 list = $('<ul class="notices threaded-replies xoxo"></ul>');
560 // See if the form's already open...
561 var replyForm = $('.notice-reply-form', list);
562 if (replyForm.length == 0) {
563 // Remove placeholder if any
564 $('li.notice-reply-placeholder').remove();
566 // Create the reply form entry at the end
567 var replyItem = $('li.notice-reply', list);
568 if (replyItem.length == 0) {
569 replyItem = $('<li class="notice-reply">' +
570 '<form class="notice-reply-form" method="post">' +
571 '<textarea name="status_textarea"></textarea>' +
572 '<div class="controls">' +
573 '<input type="hidden" name="token">' +
574 '<input type="hidden" name="inreplyto">' +
575 '<input type="submit" class="submit">' +
580 var baseForm = $('#form_notice');
581 replyForm = replyItem.find('form');
582 replyForm.attr('action', baseForm.attr('action'));
583 replyForm.find('input[name="token"]').val(baseForm.find('input[name=token]').val());
584 replyForm.find('input[type="submit"]').val(SN.msg('reply_submit'));
585 list.append(replyItem);
587 replyForm.find('textarea').blur(function() {
588 var textarea = $(this);
589 var txt = $.trim(textarea.val());
590 if (txt == '' || txt == textarea.data('initialText')) {
591 // Nothing to say? Begone!
593 if (list.find('li').length > 0) {
594 SN.U.NoticeInlineReplyPlaceholder(parentNotice);
600 replyForm.submit(function(event) {
601 var form = replyForm;
605 url: SN.U.RewriteAjaxAction(form.attr('action')),
606 data: form.serialize() + '&ajax=1',
607 beforeSend: function(xhr) {
609 .addClass(SN.C.S.Processing)
611 .addClass(SN.C.S.Disabled)
612 .attr(SN.C.S.Disabled, SN.C.S.Disabled)
615 .addClass(SN.C.S.Disabled)
616 .attr(SN.C.S.Disabled, SN.C.S.Disabled);
618 error: function (xhr, textStatus, errorThrown) {
619 alert(errorThrown || textStatus);
621 success: function(data, textStatus) {
622 var orig_li = $('li', data)[0];
624 var li = document._importNode(orig_li, true);
625 var id = $(li).attr('id');
626 if ($("#"+id).length == 0) {
627 replyItem.replaceWith(li);
628 SN.U.NoticeInlineReplyPlaceholder(parentNotice);
630 // Realtime came through before us...
636 event.preventDefault();
643 replyForm.find('input[name=inreplyto]').val(id);
646 var text = replyForm.find('textarea');
647 if (text.length == 0) {
652 replyto = initialText + ' ';
654 text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
655 text.data('initialText', $.trim(initialText + ''));
657 if (text[0].setSelectionRange) {
658 var len = text.val().length;
659 text[0].setSelectionRange(len,len);
664 * Setup function -- DOES NOT apply immediately.
666 * Sets up event handlers for favor/disfavor forms to submit via XHR.
667 * Uses 'live' rather than 'bind', so applies to future as well as present items.
669 NoticeFavor: function() {
670 $('.form_favor').live('click', function() { SN.U.FormXHR($(this)); return false; });
671 $('.form_disfavor').live('click', function() { SN.U.FormXHR($(this)); return false; });
674 NoticeInlineReplyPlaceholder: function(notice) {
675 var list = notice.find('ul.threaded-replies');
676 var placeholder = $('<li class="notice-reply-placeholder">' +
677 '<input class="placeholder">' +
679 placeholder.click(function() {
680 SN.U.NoticeInlineReplyTrigger(notice);
682 placeholder.find('input').val(SN.msg('reply_placeholder'));
683 list.append(placeholder);
687 * Setup function -- DOES NOT apply immediately.
689 * Sets up event handlers for favor/disfavor forms to submit via XHR.
690 * Uses 'live' rather than 'bind', so applies to future as well as present items.
692 NoticeInlineReplySetup: function() {
693 $('.threaded-replies').each(function() {
695 var notice = list.closest('.notice');
696 SN.U.NoticeInlineReplyPlaceholder(notice);
701 * Setup function -- DOES NOT trigger actions immediately.
703 * Sets up event handlers for repeat forms to toss up a confirmation
704 * popout before submitting.
706 * Uses 'live' rather than 'bind', so applies to future as well as present items.
708 NoticeRepeat: function() {
709 $('.form_repeat').live('click', function(e) {
712 SN.U.NoticeRepeatConfirmation($(this));
718 * Shows a confirmation dialog box variant of the repeat button form.
719 * This seems to use a technique where the repeat form contains
720 * _both_ a standalone button _and_ text and buttons for a dialog.
721 * The dialog will close after its copy of the form is submitted,
722 * or if you click its 'close' button.
724 * The dialog is created by duplicating the original form and changing
725 * its style; while clever, this is hard to generalize and probably
726 * duplicates a lot of unnecessary HTML output.
728 * @fixme create confirmation dialogs through a generalized interface
729 * that can be reused instead of hardcoded text and styles.
731 * @param {jQuery} form
733 NoticeRepeatConfirmation: function(form) {
734 var submit_i = form.find('.submit');
736 var submit = submit_i.clone();
738 .addClass('submit_dialogbox')
739 .removeClass('submit');
741 submit.bind('click', function() { SN.U.FormXHR(form); return false; });
746 .addClass('dialogbox')
747 .append('<button class="close">×</button>')
748 .closest('.notice-options')
751 form.find('button.close').click(function(){
755 .removeClass('dialogbox')
756 .closest('.notice-options')
757 .removeClass('opaque');
759 form.find('.submit_dialogbox').remove();
760 form.find('.submit').show();
767 * Setup function -- DOES NOT trigger actions immediately.
769 * Goes through all notices currently displayed and sets up attachment
770 * handling if needed.
772 NoticeAttachments: function() {
773 $('.notice a.attachment').each(function() {
774 SN.U.NoticeWithAttachment($(this).closest('.notice'));
779 * Setup function -- DOES NOT trigger actions immediately.
781 * Sets up special attachment link handling if needed. Currently this
782 * consists only of making the "more" button used for OStatus message
783 * cropping turn into an auto-expansion button that loads the full
784 * text from an attachment file.
786 * @param {jQuery} notice
788 NoticeWithAttachment: function(notice) {
789 if (notice.find('.attachment').length === 0) {
793 var attachment_more = notice.find('.attachment.more');
794 if (attachment_more.length > 0) {
795 $(attachment_more[0]).click(function() {
797 m.addClass(SN.C.S.Processing);
798 $.get(m.attr('href')+'/ajax', null, function(data) {
799 m.parent('.entry-content').html($(data).find('#attachment_view .entry-content').html());
803 }).attr('title', SN.msg('showmore_tooltip'));
808 * Setup function -- DOES NOT trigger actions immediately.
810 * Sets up event handlers for the file-attachment widget in the
811 * new notice form. When a file is selected, a box will be added
812 * below the text input showing the filename and, if supported
813 * by the browser, a thumbnail preview.
815 * This preview box will also allow removing the attachment
818 * @param {jQuery} form
820 NoticeDataAttach: function(form) {
821 var NDA = form.find('input[type=file]');
822 NDA.change(function(event) {
823 form.find('.attach-status').remove();
825 var filename = $(this).val();
827 // No file -- we've been tricked!
831 var attachStatus = $('<div class="attach-status '+SN.C.S.Success+'"><code></code> <button class="close">×</button></div>');
832 attachStatus.find('code').text(filename);
833 attachStatus.find('button').click(function(){
834 attachStatus.remove();
839 form.append(attachStatus);
841 if (typeof this.files == "object") {
842 // Some newer browsers will let us fetch the files for preview.
843 for (var i = 0; i < this.files.length; i++) {
844 SN.U.PreviewAttach(form, this.files[i]);
851 * Get PHP's MAX_FILE_SIZE setting for this form;
852 * used to apply client-side file size limit checks.
854 * @param {jQuery} form
855 * @return int max size in bytes; 0 or negative means no limit
857 maxFileSize: function(form) {
858 var max = $(form).find('input[name=MAX_FILE_SIZE]').attr('value');
860 return parseInt(max);
867 * For browsers with FileAPI support: make a thumbnail if possible,
868 * and append it into the attachment display widget.
871 * - Firefox 3.6.6, 4.0b7
872 * - Chrome 8.0.552.210
874 * Known ok metadata, can't get contents:
878 * - Opera 10.63, 11 beta (no input.files interface)
880 * @param {jQuery} form
883 * @todo use configured thumbnail size
884 * @todo detect pixel size?
885 * @todo should we render a thumbnail to a canvas and then use the smaller image?
887 PreviewAttach: function(form, file) {
888 var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
892 if (typeof window.createObjectURL != "undefined") {
894 * createObjectURL lets us reference the file directly from an <img>
895 * This produces a compact URL with an opaque reference to the file,
896 * which we can reference immediately.
898 * - Firefox 3.6.6: no
899 * - Firefox 4.0b7: no
901 * - Chrome 8.0.552.210: works!
903 blobAsDataURL = function(blob, callback) {
904 callback(window.createObjectURL(blob));
906 } else if (typeof window.FileReader != "undefined") {
908 * FileAPI's FileReader can build a data URL from a blob's contents,
909 * but it must read the file and build it asynchronously. This means
910 * we'll be passing a giant data URL around, which may be inefficient.
912 * - Firefox 3.6.6: works!
913 * - Firefox 4.0b7: works!
915 * - Chrome 8.0.552.210: works!
917 blobAsDataURL = function(blob, callback) {
918 var reader = new FileReader();
919 reader.onload = function(event) {
920 callback(reader.result);
922 reader.readAsDataURL(blob);
928 var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
929 if ($.inArray(file.type, imageTypes) == -1) {
930 // We probably don't know how to show the file.
934 var maxSize = 8 * 1024 * 1024;
935 if (file.size > maxSize) {
936 // Don't kill the browser trying to load some giant image.
941 blobAsDataURL(file, function(url) {
943 .attr('title', tooltip)
944 .attr('alt', tooltip)
946 .attr('style', 'height: 120px');
947 form.find('.attach-status').append(img);
950 var img = $('<div></div>').text(tooltip);
951 form.find('.attach-status').append(img);
956 * Setup function -- DOES NOT trigger actions immediately.
958 * Initializes state for the location-lookup features in the
959 * new-notice form. Seems to set up some event handlers for
960 * triggering lookups and using the new values.
962 * @param {jQuery} form
965 * @fixme there's not good visual state update here, so users have a
966 * hard time figuring out if it's working or fixing if it's wrong.
969 NoticeLocationAttach: function(form) {
970 // @fixme this should not be tied to the main notice form, as there may be multiple notice forms...
971 var NLat = form.find('[name=lat]')
972 var NLon = form.find('[name=lon]')
973 var NLNS = form.find('[name=location_ns]').val();
974 var NLID = form.find('[name=location_id]').val();
975 var NLN = $('#'+SN.C.S.NoticeGeoName).text(); // @fixme does this exist?
976 var NDGe = form.find('[name=notice_data-geo]');
978 function removeNoticeDataGeo(error) {
979 $('label[for='+SN.C.S.NoticeDataGeo+']')
980 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()))
981 .removeClass('checked');
983 form.find('[name=lat]').val('');
984 form.find('[name=lon]').val('');
985 form.find('[name=location_ns]').val('');
986 form.find('[name=location_id]').val('');
987 form.find('[name=notice_data-geo]').attr('checked', false);
989 $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
992 $('.geo_status_wrapper').removeClass('success').addClass('error');
993 $('.geo_status_wrapper .geo_status').text(error);
995 $('.geo_status_wrapper').remove();
999 function getJSONgeocodeURL(geocodeURL, data) {
1000 SN.U.NoticeGeoStatus('Looking up place name...');
1001 $.getJSON(geocodeURL, data, function(location) {
1004 if (typeof(location.location_ns) != 'undefined') {
1005 form.find('[name=location_ns]').val(location.location_ns);
1006 lns = location.location_ns;
1009 if (typeof(location.location_id) != 'undefined') {
1010 form.find('[name=location_id]').val(location.location_id);
1011 lid = location.location_id;
1014 if (typeof(location.name) == 'undefined') {
1015 NLN_text = data.lat + ';' + data.lon;
1018 NLN_text = location.name;
1021 SN.U.NoticeGeoStatus(NLN_text, data.lat, data.lon, location.url);
1022 $('label[for='+SN.C.S.NoticeDataGeo+']')
1023 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
1025 form.find('[name=lat]').val(data.lat);
1026 form.find('[name=lon]').val(data.lon);
1027 form.find('[name=location_ns]').val(lns);
1028 form.find('[name=location_id]').val(lid);
1029 form.find('[name=notice_data-geo]').attr('checked', true);
1041 $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
1045 if (NDGe.length > 0) {
1046 if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1047 NDGe.attr('checked', false);
1050 NDGe.attr('checked', true);
1053 var NGW = $('#notice_data-geo_wrap');
1054 var geocodeURL = NGW.attr('title');
1055 NGW.removeAttr('title');
1057 $('label[for='+SN.C.S.NoticeDataGeo+']')
1058 .attr('title', jQuery.trim($('label[for='+SN.C.S.NoticeDataGeo+']').text()));
1060 NDGe.change(function() {
1061 if ($('#'+SN.C.S.NoticeDataGeo).attr('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === null) {
1062 $('label[for='+SN.C.S.NoticeDataGeo+']')
1063 .attr('title', NoticeDataGeo_text.ShareDisable)
1064 .addClass('checked');
1066 if ($.cookie(SN.C.S.NoticeDataGeoCookie) === null || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
1067 if (navigator.geolocation) {
1068 SN.U.NoticeGeoStatus('Requesting location from browser...');
1069 navigator.geolocation.getCurrentPosition(
1070 function(position) {
1071 form.find('[name=lat]').val(position.coords.latitude);
1072 form.find('[name=lon]').val(position.coords.longitude);
1075 lat: position.coords.latitude,
1076 lon: position.coords.longitude,
1077 token: $('#token').val()
1080 getJSONgeocodeURL(geocodeURL, data);
1084 switch(error.code) {
1085 case error.PERMISSION_DENIED:
1086 removeNoticeDataGeo('Location permission denied.');
1089 //$('#'+SN.C.S.NoticeDataGeo).attr('checked', false);
1090 removeNoticeDataGeo('Location lookup timeout.');
1101 if (NLat.length > 0 && NLon.length > 0) {
1105 token: $('#token').val()
1108 getJSONgeocodeURL(geocodeURL, data);
1111 removeNoticeDataGeo();
1112 $('#'+SN.C.S.NoticeDataGeo).remove();
1113 $('label[for='+SN.C.S.NoticeDataGeo+']').remove();
1118 var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
1120 form.find('[name=lat]').val(cookieValue.NLat);
1121 form.find('[name=lon]').val(cookieValue.NLon);
1122 form.find('[name=location_ns]').val(cookieValue.NLNS);
1123 form.find('[name=location_id]').val(cookieValue.NLID);
1124 form.find('[name=notice_data-geo]').attr('checked', cookieValue.NDG);
1126 SN.U.NoticeGeoStatus(cookieValue.NLN, cookieValue.NLat, cookieValue.NLon, cookieValue.NLNU);
1127 $('label[for='+SN.C.S.NoticeDataGeo+']')
1128 .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
1129 .addClass('checked');
1133 removeNoticeDataGeo();
1140 * Create or update a geolocation status widget in this notice posting form.
1142 * @param {String} status
1143 * @param {String} lat (optional)
1144 * @param {String} lon (optional)
1145 * @param {String} url (optional)
1147 NoticeGeoStatus: function(status, lat, lon, url)
1149 var form = $('#form_notice');
1150 var wrapper = form.find('.geo_status_wrapper');
1151 if (wrapper.length == 0) {
1152 wrapper = $('<div class="'+SN.C.S.Success+' geo_status_wrapper"><button class="close" style="float:right">×</button><div class="geo_status"></div></div>');
1153 wrapper.find('button.close').click(function() {
1154 $('#'+SN.C.S.NoticeDataGeo).removeAttr('checked').change();
1156 form.append(wrapper);
1160 label = $('<a></a>').attr('href', url);
1162 label = $('<span></span>');
1166 var latlon = lat + ';' + lon;
1167 label.attr('title', latlon);
1172 wrapper.find('.geo_status').empty().append(label);
1176 * Setup function -- DOES NOT trigger actions immediately.
1178 * Initializes event handlers for the "Send direct message" link on
1179 * profile pages, setting it up to display a dialog box when clicked.
1181 * Unlike the repeat confirmation form, this appears to fetch
1182 * the form _from the original link target_, so the form itself
1183 * doesn't need to be in the current document.
1185 * @fixme breaks ability to open link in new window?
1187 NewDirectMessage: function() {
1188 NDM = $('.entity_send-a-message a');
1189 NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
1190 NDM.bind('click', function() {
1191 var NDMF = $('.entity_send-a-message form');
1192 if (NDMF.length === 0) {
1193 $(this).addClass(SN.C.S.Processing);
1194 $.get(NDM.attr('href'), null, function(data) {
1195 $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
1196 NDMF = $('.entity_send-a-message .form_notice');
1197 SN.U.FormNoticeXHR(NDMF);
1198 SN.U.FormNoticeEnhancements(NDMF);
1199 NDMF.append('<button class="close">×</button>');
1200 $('.entity_send-a-message button').click(function(){
1204 NDM.removeClass(SN.C.S.Processing);
1209 $('.entity_send-a-message textarea').focus();
1216 * Return a date object with the current local time on the
1217 * given year, month, and day.
1219 * @param {number} year: 4-digit year
1220 * @param {number} month: 0 == January
1221 * @param {number} day: 1 == 1
1224 GetFullYear: function(year, month, day) {
1225 var date = new Date();
1226 date.setFullYear(year, month, day);
1232 * Some sort of object interface for storing some structured
1233 * information in a cookie.
1235 * Appears to be used to save the last-used login nickname?
1236 * That's something that browsers usually take care of for us
1237 * these days, do we really need to do it? Does anything else
1238 * use this interface?
1240 * @fixme what is this?
1241 * @fixme should this use non-cookie local storage when available?
1243 StatusNetInstance: {
1245 * @fixme what is this?
1247 Set: function(value) {
1248 var SNI = SN.U.StatusNetInstance.Get();
1250 value = $.extend(SNI, value);
1254 SN.C.S.StatusNetInstance,
1255 JSON.stringify(value),
1258 expires: SN.U.GetFullYear(2029, 0, 1)
1263 * @fixme what is this?
1266 var cookieValue = $.cookie(SN.C.S.StatusNetInstance);
1267 if (cookieValue !== null) {
1268 return JSON.parse(cookieValue);
1274 * @fixme what is this?
1276 Delete: function() {
1277 $.cookie(SN.C.S.StatusNetInstance, null);
1282 * Check if the current page is a timeline where the current user's
1283 * posts should be displayed immediately on success.
1285 * @fixme this should be done in a saner way, with machine-readable
1286 * info about what page we're looking at.
1288 * @param {DOMElement} notice: HTML chunk with formatted notice
1291 belongsOnTimeline: function(notice) {
1292 var action = $("body").attr('id');
1293 if (action == 'public') {
1297 var profileLink = $('#nav_profile a').attr('href');
1299 var authorUrl = $(notice).find('.entry-title .author a.url').attr('href');
1300 if (authorUrl == profileLink) {
1301 if (action == 'all' || action == 'showstream') {
1302 // Posts always show on your own friends and profile streams.
1308 // @fixme tag, group, reply timelines should be feasible as well.
1309 // Mismatch between id-based and name-based user/group links currently complicates
1310 // the lookup, since all our inline mentions contain the absolute links but the
1311 // UI links currently on the page use malleable names.
1319 * If user is logged in, run setup code for the new notice form:
1324 * - file upload events
1326 NoticeForm: function() {
1327 if ($('body.user_in').length > 0) {
1328 $('.'+SN.C.S.FormNotice).each(function() {
1330 SN.U.NoticeLocationAttach(form);
1331 SN.U.FormNoticeXHR(form);
1332 SN.U.FormNoticeEnhancements(form);
1333 SN.U.NoticeDataAttach(form);
1339 * Run setup code for notice timeline views items:
1341 * - AJAX submission for fave/repeat/reply (if logged in)
1342 * - Attachment link extras ('more' links)
1344 Notices: function() {
1345 if ($('body.user_in').length > 0) {
1347 SN.U.NoticeRepeat();
1349 SN.U.NoticeInlineReplySetup();
1352 SN.U.NoticeAttachments();
1356 * Run setup code for user & group profile page header area if logged in:
1358 * - AJAX submission for sub/unsub/join/leave/nudge
1359 * - AJAX form popup for direct-message
1361 EntityActions: function() {
1362 if ($('body.user_in').length > 0) {
1363 $('.form_user_subscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1364 $('.form_user_unsubscribe').live('click', function() { SN.U.FormXHR($(this)); return false; });
1365 $('.form_group_join').live('click', function() { SN.U.FormXHR($(this)); return false; });
1366 $('.form_group_leave').live('click', function() { SN.U.FormXHR($(this)); return false; });
1367 $('.form_user_nudge').live('click', function() { SN.U.FormXHR($(this)); return false; });
1369 SN.U.NewDirectMessage();
1374 * Run setup code for login form:
1376 * - loads saved last-used-nickname from cookie
1377 * - sets event handler to save nickname to cookie on submit
1379 * @fixme is this necessary? Browsers do their own form saving these days.
1382 if (SN.U.StatusNetInstance.Get() !== null) {
1383 var nickname = SN.U.StatusNetInstance.Get().Nickname;
1384 if (nickname !== null) {
1385 $('#form_login #nickname').val(nickname);
1389 $('#form_login').bind('submit', function() {
1390 SN.U.StatusNetInstance.Set({Nickname: $('#form_login #nickname').val()});
1396 * Add logic to any file upload forms to handle file size limits,
1397 * on browsers that support basic FileAPI.
1399 UploadForms: function () {
1400 $('input[type=file]').change(function(event) {
1401 if (typeof this.files == "object" && this.files.length > 0) {
1403 for (var i = 0; i < this.files.length; i++) {
1404 size += this.files[i].size;
1407 var max = SN.U.maxFileSize($(this.form));
1408 if (max > 0 && size > max) {
1409 var msg = 'File too large: maximum upload size is %d bytes.';
1410 alert(msg.replace('%d', max));
1414 event.preventDefault();
1424 * Run initialization functions on DOM-ready.
1426 * Note that if we're waiting on other scripts to load, this won't happen
1427 * until that's done. To load scripts asynchronously without delaying setup,
1428 * don't start them loading until after DOM-ready time!
1430 $(document).ready(function(){
1431 SN.Init.UploadForms();
1432 if ($('.'+SN.C.S.FormNotice).length > 0) {
1433 SN.Init.NoticeForm();
1435 if ($('#content .notices').length > 0) {
1438 if ($('#content .entity_actions').length > 0) {
1439 SN.Init.EntityActions();
1441 if ($('#form_login').length > 0) {