2 * StatusNet - a distributed open-source microblogging tool
3 * Copyright (C) 2008, StatusNet, Inc.
5 * Add a notice encoded as JSON into the current timeline
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 * @author Evan Prodromou <evan@status.net>
23 * @author Sarven Capadisli <csarven@status.net>
24 * @copyright 2009 StatusNet, Inc.
25 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
26 * @link http://status.net/
30 * This is the UI portion of the Realtime plugin base class, handling
31 * queueing up and displaying of notices that have been received through
32 * other code in one of the subclassed plugin implementations such as
35 * Notices are passed in as JSON objects formatted per the Twitter-compatible
38 * @todo Currently we duplicate a lot of formatting and layout code from
39 * the PHP side of StatusNet, which makes it very difficult to maintain
40 * this package. Internationalization as well as newer features such
41 * as location data, customized source links for OStatus profiles,
42 * and image thumbnails are not yet supported in Realtime yet because
43 * they have not been implemented here.
50 _windowhasfocus: true,
56 * Initialize the Realtime plugin UI on a page with a timeline view.
58 * This function is called from a JS fragment inserted by the PHP side
59 * of the Realtime plugin, and provides us with base information
60 * needed to build a near-replica of StatusNet's NoticeListItem output.
62 * Once the UI is initialized, a plugin subclass will need to actually
63 * feed data into the RealtimeUpdate object!
65 * @param {int} userid: local profile ID of the currently logged-in user
66 * @param {String} showurl: URL for shownotice action, used when fetching formatting notices.
67 * This URL contains a stub value of 0000000000 which will be replaced with the notice ID.
71 init: function(userid, showurl)
73 RealtimeUpdate._userid = userid;
74 RealtimeUpdate._showurl = showurl;
76 RealtimeUpdate._documenttitle = document.title;
78 $(window).bind('focus', function() {
79 RealtimeUpdate._windowhasfocus = true;
81 // Clear the counter on the window title when we focus in.
82 RealtimeUpdate._updatecounter = 0;
83 RealtimeUpdate.removeWindowCounter();
86 $(window).bind('blur', function() {
87 $('#notices_primary .notice').removeClass('mark-top');
89 $('#notices_primary .notice:first').addClass('mark-top');
91 // While we're in the background, received messages will increment
92 // a counter that we put on the window title. This will cause some
93 // browsers to also flash or mark the tab or window title bar until
94 // you seek attention (eg Firefox 4 pinned app tabs).
95 RealtimeUpdate._windowhasfocus = false;
102 * Accept a notice in a Twitter-API JSON style and either show it
103 * or queue it up, depending on whether the realtime display is
106 * The meat of a Realtime plugin subclass is to provide a substrate
107 * transport to receive data and shove it into this function. :)
109 * Note that the JSON data is extended from the standard API return
110 * with additional fields added by RealtimePlugin's PHP code.
112 * @param {Object} data: extended JSON API-formatted notice
116 receive: function(data)
118 if (RealtimeUpdate.isNoticeVisible(data.id)) {
119 // Probably posted by the user in this window, and so already
120 // shown by the AJAX form handler. Ignore it.
123 if (RealtimeUpdate._paused === false) {
124 RealtimeUpdate.purgeLastNoticeItem();
126 RealtimeUpdate.insertNoticeItem(data);
129 RealtimeUpdate._queuedNotices.push(data);
131 RealtimeUpdate.updateQueuedCounter();
134 RealtimeUpdate.updateWindowCounter();
138 * Add a visible representation of the given notice at the top of
139 * the current timeline.
141 * If the notice is already in the timeline, nothing will be added.
143 * @param {Object} data: extended JSON API-formatted notice
145 * @fixme while core UI JS code is used to activate the AJAX UI controls,
146 * the actual production of HTML (in makeNoticeItem and its subs)
147 * duplicates core code without plugin hook points or i18n support.
151 insertNoticeItem: function(data) {
152 // Don't add it if it already exists
153 if (RealtimeUpdate.isNoticeVisible(data.id)) {
157 RealtimeUpdate.makeNoticeItem(data, function(noticeItem) {
158 // Check again in case it got shown while we were waiting for data...
159 if (RealtimeUpdate.isNoticeVisible(data.id)) {
162 var noticeItemID = $(noticeItem).attr('id');
164 var list = $("#notices_primary .notices:first")
167 var threaded = list.hasClass('threaded-notices');
168 if (threaded && data.in_reply_to_status_id) {
170 var parent = $('#notice-' + data.in_reply_to_status_id);
171 if (parent.length == 0) {
172 // @todo fetch the original, insert it, and finish the rest
174 // Check the parent notice to make sure it's not a reply itself.
175 // If so, use it's parent as the parent.
176 var parentList = parent.closest('.notices');
177 if (parentList.hasClass('threaded-replies')) {
178 parent = parentList.closest('.notice');
180 list = parent.find('.threaded-replies');
181 if (list.length == 0) {
182 list = $('<ul class="notices threaded-replies xoxo"></ul>');
184 SN.U.NoticeInlineReplyPlaceholder(parent);
190 var newNotice = $(noticeItem);
192 list.prepend(newNotice);
194 var placeholder = list.find('li.notice-reply-placeholder')
195 if (placeholder.length > 0) {
196 newNotice.insertBefore(placeholder)
198 newNotice.appendTo(list);
201 newNotice.css({display:"none"}).fadeIn(1000);
203 SN.U.NoticeReplyTo($('#'+noticeItemID));
204 SN.U.NoticeWithAttachment($('#'+noticeItemID));
209 * Check if the given notice is visible in the timeline currently.
210 * Used to avoid duplicate processing of notices that have been
211 * displayed by other means.
213 * @param {number} id: notice ID to check
219 isNoticeVisible: function(id) {
220 return ($("#notice-"+id).length > 0);
224 * Trims a notice off the end of the timeline if we have more than the
225 * maximum number of notices visible.
229 purgeLastNoticeItem: function() {
230 if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
231 $("#notices_primary .notice:last").remove();
236 * If the window/tab is in background, increment the counter of newly
237 * received notices and append it onto the window title.
239 * Has no effect if the window is in foreground.
243 updateWindowCounter: function() {
244 if (RealtimeUpdate._windowhasfocus === false) {
245 RealtimeUpdate._updatecounter += 1;
246 document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
251 * Clear the background update counter from the window title.
255 * @fixme could interfere with anything else trying similar tricks
257 removeWindowCounter: function() {
258 document.title = RealtimeUpdate._documenttitle;
262 * Builds a notice HTML block from JSON API-style data;
263 * loads data from server, so runs async.
265 * @param {Object} data: extended JSON API-formatted notice
266 * @param {function} callback: function(DOMNode) to receive new code
270 makeNoticeItem: function(data, callback)
272 var url = RealtimeUpdate._showurl.replace('0000000000', data.id);
273 $.get(url, {ajax: 1}, function(data, textStatus, xhr) {
274 var notice = $('li.notice:first', data);
276 var node = document._importNode(notice[0], true);
283 * Creates a favorite button.
285 * @param {number} id: notice ID to work with
286 * @param {String} session_key: session token for form CSRF protection
287 * @return {String} HTML fragment
289 * @fixme this replicates core StatusNet code, making maintenance harder
290 * @fixme sloppy HTML building (raw concat without escaping)
291 * @fixme no i18n support
295 makeFavoriteForm: function(id, session_key)
299 ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
301 "<legend>Favor this notice</legend>"+
302 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
303 "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
304 "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
311 * Creates a reply button.
313 * @param {number} id: notice ID to work with
314 * @param {String} nickname: nick of the user to whom we are replying
315 * @return {String} HTML fragment
317 * @fixme this replicates core StatusNet code, making maintenance harder
318 * @fixme sloppy HTML building (raw concat without escaping)
319 * @fixme no i18n support
323 makeReplyLink: function(id, nickname)
326 rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
331 * Creates a repeat button.
333 * @param {number} id: notice ID to work with
334 * @param {String} session_key: session token for form CSRF protection
335 * @return {String} HTML fragment
337 * @fixme this replicates core StatusNet code, making maintenance harder
338 * @fixme sloppy HTML building (raw concat without escaping)
339 * @fixme no i18n support
343 makeRepeatForm: function(id, session_key)
346 rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
348 "<legend>Repeat this notice?</legend>"+
349 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
350 "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
351 "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
359 * Creates a delete button.
361 * @param {number} id: notice ID to create a delete link for
362 * @return {String} HTML fragment
364 * @fixme this replicates core StatusNet code, making maintenance harder
365 * @fixme sloppy HTML building (raw concat without escaping)
366 * @fixme no i18n support
370 makeDeleteLink: function(id)
373 delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
375 dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
381 * Adds a control widget at the top of the timeline view, containing
382 * pause/play and popup buttons.
384 * @param {String} url: full URL to the popup window variant of this timeline page
385 * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
386 * @param {String} path: URL to the base directory containing the Realtime plugin,
387 * used to fetch resources if needed.
389 * @todo timeline and path parameters are unused and probably should be removed.
393 initActions: function(url, timeline, path)
395 $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
397 RealtimeUpdate._pluginPath = path;
399 RealtimeUpdate.initPlayPause();
400 RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
404 * Initialize the state of the play/pause controls.
406 * If the browser supports the localStorage interface, we'll attempt
407 * to retrieve a pause state from there; otherwise we default to paused.
411 initPlayPause: function()
413 if (typeof(localStorage) == 'undefined') {
414 RealtimeUpdate.showPause();
417 if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
418 RealtimeUpdate.showPlay();
421 RealtimeUpdate.showPause();
427 * Switch the realtime UI into paused state.
428 * Uses SN.msg i18n system for the button label and tooltip.
430 * State will be saved and re-used next time if the browser supports
431 * the localStorage interface (via setPause).
435 showPause: function()
437 RealtimeUpdate.setPause(false);
438 RealtimeUpdate.showQueuedNotices();
439 RealtimeUpdate.addNoticesHover();
441 $('#realtime_playpause').remove();
442 $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
443 $('#realtime_pause').text(SN.msg('realtime_pause'))
444 .attr('title', SN.msg('realtime_pause_tooltip'))
445 .bind('click', function() {
446 RealtimeUpdate.removeNoticesHover();
447 RealtimeUpdate.showPlay();
453 * Switch the realtime UI into play state.
454 * Uses SN.msg i18n system for the button label and tooltip.
456 * State will be saved and re-used next time if the browser supports
457 * the localStorage interface (via setPause).
463 RealtimeUpdate.setPause(true);
464 $('#realtime_playpause').remove();
465 $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
466 $('#realtime_play').text(SN.msg('realtime_play'))
467 .attr('title', SN.msg('realtime_play_tooltip'))
468 .bind('click', function() {
469 RealtimeUpdate.showPause();
475 * Update the internal pause/play state.
476 * Do not call directly; use showPause() and showPlay().
478 * State will be saved and re-used next time if the browser supports
479 * the localStorage interface.
481 * @param {boolean} state: true = paused, false = not paused
485 setPause: function(state)
487 RealtimeUpdate._paused = state;
488 if (typeof(localStorage) != 'undefined') {
489 localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
494 * Go through notices we have previously received while paused,
495 * dumping them into the timeline view.
497 * @fixme long timelines are not trimmed here as they are for things received while not paused
501 showQueuedNotices: function()
503 $.each(RealtimeUpdate._queuedNotices, function(i, n) {
504 RealtimeUpdate.insertNoticeItem(n);
507 RealtimeUpdate._queuedNotices = [];
509 RealtimeUpdate.removeQueuedCounter();
513 * Update the Realtime widget control's counter of queued notices to show
514 * the current count. This will be called after receiving and queueing
515 * a notice while paused.
519 updateQueuedCounter: function()
521 $('#realtime_playpause #queued_counter').html('('+RealtimeUpdate._queuedNotices.length+')');
525 * Clear the Realtime widget control's counter of queued notices.
529 removeQueuedCounter: function()
531 $('#realtime_playpause #queued_counter').empty();
535 * Set up event handlers on the timeline view to automatically pause
536 * when the mouse is over the timeline, as this indicates the user's
537 * desire to interact with the UI. (Which is hard to do when it's moving!)
541 addNoticesHover: function()
543 $('#notices_primary .notices').hover(
545 if (RealtimeUpdate._paused === false) {
546 RealtimeUpdate.showPlay();
550 if (RealtimeUpdate._paused === true) {
551 RealtimeUpdate.showPause();
558 * Tear down event handlers on the timeline view to automatically pause
559 * when the mouse is over the timeline.
561 * @fixme this appears to remove *ALL* event handlers from the timeline,
562 * which assumes that nobody else is adding any event handlers.
563 * Sloppy -- we should only remove the ones we add.
567 removeNoticesHover: function()
569 $('#notices_primary .notices').unbind();
573 * UI initialization, to be called from Realtime plugin code on regular
576 * Adds a button to the control widget at the top of the timeline view,
577 * allowing creation of a popup window with a more compact real-time
578 * view of the current timeline.
580 * @param {String} url: full URL to the popup window variant of this timeline page
581 * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
582 * @param {String} path: URL to the base directory containing the Realtime plugin,
583 * used to fetch resources if needed.
585 * @todo timeline and path parameters are unused and probably should be removed.
589 initAddPopup: function(url, timeline, path)
591 $('#realtime_timeline').append('<button id="realtime_popup"></button>');
592 $('#realtime_popup').text(SN.msg('realtime_popup'))
593 .attr('title', SN.msg('realtime_popup_tooltip'))
594 .bind('click', function() {
597 'toolbar=no,resizable=yes,scrollbars=yes,status=no,menubar=no,personalbar=no,location=no,width=500,height=550');
604 * UI initialization, to be called from Realtime plugin code on popup
605 * compact timeline pages.
607 * Sets up links in notices to open in a new window.
609 * @fixme fails to do the same for UI links like context view which will
610 * look bad in the tiny chromeless window.
614 initPopupWindow: function()
616 $('.notices .entry-title a, .notices .entry-content a').bind('click', function() {
617 window.open(this.href, '');
622 $('#showstream .entity_profile').css({'width':'69%'});