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 var noticeItemID = $(noticeItem).attr('id');
160 var list = $("#notices_primary .notices:first")
163 var threaded = list.hasClass('threaded-notices');
164 if (threaded && data.in_reply_to_status_id) {
166 var parent = $('#notice-' + data.in_reply_to_status_id);
167 if (parent.length == 0) {
168 // @todo fetch the original, insert it, and finish the rest
170 // Check the parent notice to make sure it's not a reply itself.
171 // If so, use it's parent as the parent.
172 var parentList = parent.closest('.notices');
173 if (parentList.hasClass('threaded-replies')) {
174 parent = parentList.closest('.notice');
176 list = parent.find('.threaded-replies');
177 if (list.length == 0) {
178 list = $('<ul class="notices threaded-replies xoxo"></ul>');
185 var newNotice = $(noticeItem);
187 list.prepend(newNotice);
189 var placeholder = list.find('li.notice-reply-placeholder')
190 if (placeholder.length > 0) {
191 newNotice.insertBefore(placeholder)
193 newNotice.appendTo(list);
194 SN.U.NoticeInlineReplyPlaceholder(parent);
197 newNotice.css({display:"none"}).fadeIn(1000);
199 SN.U.NoticeReplyTo($('#'+noticeItemID));
200 SN.U.NoticeWithAttachment($('#'+noticeItemID));
205 * Check if the given notice is visible in the timeline currently.
206 * Used to avoid duplicate processing of notices that have been
207 * displayed by other means.
209 * @param {number} id: notice ID to check
215 isNoticeVisible: function(id) {
216 return ($("#notice-"+id).length > 0);
220 * Trims a notice off the end of the timeline if we have more than the
221 * maximum number of notices visible.
225 purgeLastNoticeItem: function() {
226 if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
227 $("#notices_primary .notice:last").remove();
232 * If the window/tab is in background, increment the counter of newly
233 * received notices and append it onto the window title.
235 * Has no effect if the window is in foreground.
239 updateWindowCounter: function() {
240 if (RealtimeUpdate._windowhasfocus === false) {
241 RealtimeUpdate._updatecounter += 1;
242 document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
247 * Clear the background update counter from the window title.
251 * @fixme could interfere with anything else trying similar tricks
253 removeWindowCounter: function() {
254 document.title = RealtimeUpdate._documenttitle;
258 * Builds a notice HTML block from JSON API-style data;
259 * loads data from server, so runs async.
261 * @param {Object} data: extended JSON API-formatted notice
262 * @param {function} callback: function(DOMNode) to receive new code
266 makeNoticeItem: function(data, callback)
268 var url = RealtimeUpdate._showurl.replace('0000000000', data.id);
269 $.get(url, {ajax: 1}, function(data, textStatus, xhr) {
270 var notice = $('li.notice:first', data);
272 var node = document._importNode(notice[0], true);
279 * Creates a favorite button.
281 * @param {number} id: notice ID to work with
282 * @param {String} session_key: session token for form CSRF protection
283 * @return {String} HTML fragment
285 * @fixme this replicates core StatusNet code, making maintenance harder
286 * @fixme sloppy HTML building (raw concat without escaping)
287 * @fixme no i18n support
291 makeFavoriteForm: function(id, session_key)
295 ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
297 "<legend>Favor this notice</legend>"+
298 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
299 "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
300 "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
307 * Creates a reply button.
309 * @param {number} id: notice ID to work with
310 * @param {String} nickname: nick of the user to whom we are replying
311 * @return {String} HTML fragment
313 * @fixme this replicates core StatusNet code, making maintenance harder
314 * @fixme sloppy HTML building (raw concat without escaping)
315 * @fixme no i18n support
319 makeReplyLink: function(id, nickname)
322 rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
327 * Creates a repeat button.
329 * @param {number} id: notice ID to work with
330 * @param {String} session_key: session token for form CSRF protection
331 * @return {String} HTML fragment
333 * @fixme this replicates core StatusNet code, making maintenance harder
334 * @fixme sloppy HTML building (raw concat without escaping)
335 * @fixme no i18n support
339 makeRepeatForm: function(id, session_key)
342 rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
344 "<legend>Repeat this notice?</legend>"+
345 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
346 "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
347 "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
355 * Creates a delete button.
357 * @param {number} id: notice ID to create a delete link for
358 * @return {String} HTML fragment
360 * @fixme this replicates core StatusNet code, making maintenance harder
361 * @fixme sloppy HTML building (raw concat without escaping)
362 * @fixme no i18n support
366 makeDeleteLink: function(id)
369 delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
371 dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
377 * Adds a control widget at the top of the timeline view, containing
378 * pause/play and popup buttons.
380 * @param {String} url: full URL to the popup window variant of this timeline page
381 * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
382 * @param {String} path: URL to the base directory containing the Realtime plugin,
383 * used to fetch resources if needed.
385 * @todo timeline and path parameters are unused and probably should be removed.
389 initActions: function(url, timeline, path)
391 $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
393 RealtimeUpdate._pluginPath = path;
395 RealtimeUpdate.initPlayPause();
396 RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
400 * Initialize the state of the play/pause controls.
402 * If the browser supports the localStorage interface, we'll attempt
403 * to retrieve a pause state from there; otherwise we default to paused.
407 initPlayPause: function()
409 if (typeof(localStorage) == 'undefined') {
410 RealtimeUpdate.showPause();
413 if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
414 RealtimeUpdate.showPlay();
417 RealtimeUpdate.showPause();
423 * Switch the realtime UI into paused state.
424 * Uses SN.msg i18n system for the button label and tooltip.
426 * State will be saved and re-used next time if the browser supports
427 * the localStorage interface (via setPause).
431 showPause: function()
433 RealtimeUpdate.setPause(false);
434 RealtimeUpdate.showQueuedNotices();
435 RealtimeUpdate.addNoticesHover();
437 $('#realtime_playpause').remove();
438 $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
439 $('#realtime_pause').text(SN.msg('realtime_pause'))
440 .attr('title', SN.msg('realtime_pause_tooltip'))
441 .bind('click', function() {
442 RealtimeUpdate.removeNoticesHover();
443 RealtimeUpdate.showPlay();
449 * Switch the realtime UI into play state.
450 * Uses SN.msg i18n system for the button label and tooltip.
452 * State will be saved and re-used next time if the browser supports
453 * the localStorage interface (via setPause).
459 RealtimeUpdate.setPause(true);
460 $('#realtime_playpause').remove();
461 $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
462 $('#realtime_play').text(SN.msg('realtime_play'))
463 .attr('title', SN.msg('realtime_play_tooltip'))
464 .bind('click', function() {
465 RealtimeUpdate.showPause();
471 * Update the internal pause/play state.
472 * Do not call directly; use showPause() and showPlay().
474 * State will be saved and re-used next time if the browser supports
475 * the localStorage interface.
477 * @param {boolean} state: true = paused, false = not paused
481 setPause: function(state)
483 RealtimeUpdate._paused = state;
484 if (typeof(localStorage) != 'undefined') {
485 localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
490 * Go through notices we have previously received while paused,
491 * dumping them into the timeline view.
493 * @fixme long timelines are not trimmed here as they are for things received while not paused
497 showQueuedNotices: function()
499 $.each(RealtimeUpdate._queuedNotices, function(i, n) {
500 RealtimeUpdate.insertNoticeItem(n);
503 RealtimeUpdate._queuedNotices = [];
505 RealtimeUpdate.removeQueuedCounter();
509 * Update the Realtime widget control's counter of queued notices to show
510 * the current count. This will be called after receiving and queueing
511 * a notice while paused.
515 updateQueuedCounter: function()
517 $('#realtime_playpause #queued_counter').html('('+RealtimeUpdate._queuedNotices.length+')');
521 * Clear the Realtime widget control's counter of queued notices.
525 removeQueuedCounter: function()
527 $('#realtime_playpause #queued_counter').empty();
531 * Set up event handlers on the timeline view to automatically pause
532 * when the mouse is over the timeline, as this indicates the user's
533 * desire to interact with the UI. (Which is hard to do when it's moving!)
537 addNoticesHover: function()
539 $('#notices_primary .notices').hover(
541 if (RealtimeUpdate._paused === false) {
542 RealtimeUpdate.showPlay();
546 if (RealtimeUpdate._paused === true) {
547 RealtimeUpdate.showPause();
554 * Tear down event handlers on the timeline view to automatically pause
555 * when the mouse is over the timeline.
557 * @fixme this appears to remove *ALL* event handlers from the timeline,
558 * which assumes that nobody else is adding any event handlers.
559 * Sloppy -- we should only remove the ones we add.
563 removeNoticesHover: function()
565 $('#notices_primary .notices').unbind();
569 * UI initialization, to be called from Realtime plugin code on regular
572 * Adds a button to the control widget at the top of the timeline view,
573 * allowing creation of a popup window with a more compact real-time
574 * view of the current timeline.
576 * @param {String} url: full URL to the popup window variant of this timeline page
577 * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
578 * @param {String} path: URL to the base directory containing the Realtime plugin,
579 * used to fetch resources if needed.
581 * @todo timeline and path parameters are unused and probably should be removed.
585 initAddPopup: function(url, timeline, path)
587 $('#realtime_timeline').append('<button id="realtime_popup"></button>');
588 $('#realtime_popup').text(SN.msg('realtime_popup'))
589 .attr('title', SN.msg('realtime_popup_tooltip'))
590 .bind('click', function() {
593 'toolbar=no,resizable=yes,scrollbars=yes,status=no,menubar=no,personalbar=no,location=no,width=500,height=550');
600 * UI initialization, to be called from Realtime plugin code on popup
601 * compact timeline pages.
603 * Sets up links in notices to open in a new window.
605 * @fixme fails to do the same for UI links like context view which will
606 * look bad in the tiny chromeless window.
610 initPopupWindow: function()
612 $('.notices .entry-title a, .notices .entry-content a').bind('click', function() {
613 window.open(this.href, '');
618 $('#showstream .entity_profile').css({'width':'69%'});