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.
53 _windowhasfocus: true,
59 * Initialize the Realtime plugin UI on a page with a timeline view.
61 * This function is called from a JS fragment inserted by the PHP side
62 * of the Realtime plugin, and provides us with base information
63 * needed to build a near-replica of StatusNet's NoticeListItem output.
65 * Once the UI is initialized, a plugin subclass will need to actually
66 * feed data into the RealtimeUpdate object!
68 * @param {int} userid: local profile ID of the currently logged-in user
69 * @param {String} replyurl: URL for newnotice action, used when generating reply buttons
70 * @param {String} favorurl: URL for favor action, used when generating fave buttons
71 * @param {String} repeaturl: URL for repeat action, used when generating repeat buttons
72 * @param {String} deleteurl: URL template for deletenotice action, used when generating delete buttons.
73 * This URL contains a stub value of 0000000000 which will be replaced with the notice ID.
77 init: function(userid, replyurl, favorurl, repeaturl, deleteurl)
79 RealtimeUpdate._userid = userid;
80 RealtimeUpdate._replyurl = replyurl;
81 RealtimeUpdate._favorurl = favorurl;
82 RealtimeUpdate._repeaturl = repeaturl;
83 RealtimeUpdate._deleteurl = deleteurl;
85 RealtimeUpdate._documenttitle = document.title;
87 $(window).bind('focus', function(){ RealtimeUpdate._windowhasfocus = true; });
89 $(window).bind('blur', function() {
90 $('#notices_primary .notice').removeClass('mark-top');
92 $('#notices_primary .notice:first').addClass('mark-top');
94 RealtimeUpdate._updatecounter = 0;
95 document.title = RealtimeUpdate._documenttitle;
96 RealtimeUpdate._windowhasfocus = false;
103 * Accept a notice in a Twitter-API JSON style and either show it
104 * or queue it up, depending on whether the realtime display is
107 * The meat of a Realtime plugin subclass is to provide a substrate
108 * transport to receive data and shove it into this function. :)
110 * Note that the JSON data is extended from the standard API return
111 * with additional fields added by RealtimePlugin's PHP code.
113 * @param {Object} data: extended JSON API-formatted notice
115 * @fixme Ticket #2914: already-visible sent notices are still queued up
116 * when paused, inflating the queue count
120 receive: function(data)
122 if (RealtimeUpdate._paused === false) {
123 RealtimeUpdate.purgeLastNoticeItem();
125 RealtimeUpdate.insertNoticeItem(data);
128 RealtimeUpdate._queuedNotices.push(data);
130 RealtimeUpdate.updateQueuedCounter();
133 RealtimeUpdate.updateWindowCounter();
137 * Add a visible representation of the given notice at the top of
138 * the current timeline.
140 * If the notice is already in the timeline, nothing will be added.
142 * @param {Object} data: extended JSON API-formatted notice
144 * @fixme while core UI JS code is used to activate the AJAX UI controls,
145 * the actual production of HTML (in makeNoticeItem and its subs)
146 * duplicates core code without plugin hook points or i18n support.
150 insertNoticeItem: function(data) {
151 // Don't add it if it already exists
152 if ($("#notice-"+data.id).length > 0) {
156 var noticeItem = RealtimeUpdate.makeNoticeItem(data);
157 var noticeItemID = $(noticeItem).attr('id');
159 $("#notices_primary .notices").prepend(noticeItem);
160 $("#notices_primary .notice:first").css({display:"none"});
161 $("#notices_primary .notice:first").fadeIn(1000);
163 SN.U.NoticeReplyTo($('#'+noticeItemID));
164 SN.U.NoticeWithAttachment($('#'+noticeItemID));
168 * Trims a notice off the end of the timeline if we have more than the
169 * maximum number of notices visible.
173 purgeLastNoticeItem: function() {
174 if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
175 $("#notices_primary .notice:last").remove();
180 * If the window/tab is in background, increment the counter of newly
181 * received notices and append it onto the window title.
183 * Has no effect if the window is in foreground.
187 updateWindowCounter: function() {
188 if (RealtimeUpdate._windowhasfocus === false) {
189 RealtimeUpdate._updatecounter += 1;
190 document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
195 * Builds a notice HTML block from JSON API-style data.
197 * @param {Object} data: extended JSON API-formatted notice
198 * @return {String} HTML fragment
200 * @fixme this replicates core StatusNet code, making maintenance harder
201 * @fixme sloppy HTML building (raw concat without escaping)
202 * @fixme no i18n support
203 * @fixme local variables pollute global namespace
207 makeNoticeItem: function(data)
209 if (data.hasOwnProperty('retweeted_status')) {
210 original = data['retweeted_status'];
213 unique = repeat['id'];
214 responsible = repeat['user'];
219 responsible = data['user'];
223 html = data['html'].replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/&/g,'&');
224 source = data['source'].replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/&/g,'&');
226 ni = "<li class=\"hentry notice\" id=\"notice-"+unique+"\">"+
227 "<div class=\"entry-title\">"+
228 "<span class=\"vcard author\">"+
229 "<a href=\""+user['profile_url']+"\" class=\"url\" title=\""+user['name']+"\">"+
230 "<img src=\""+user['profile_image_url']+"\" class=\"avatar photo\" width=\"48\" height=\"48\" alt=\""+user['screen_name']+"\"/>"+
231 "<span class=\"nickname fn\">"+user['screen_name']+"</span>"+
234 "<p class=\"entry-content\">"+html+"</p>"+
236 "<div class=\"entry-content\">"+
237 "<a class=\"timestamp\" rel=\"bookmark\" href=\""+data['url']+"\" >"+
238 "<abbr class=\"published\" title=\""+data['created_at']+"\">a few seconds ago</abbr>"+
240 "<span class=\"source\">"+
242 "<span class=\"device\">"+source+"</span>"+ // may have a link
244 if (data['conversation_url']) {
245 ni = ni+" <a class=\"response\" href=\""+data['conversation_url']+"\">in context</a>";
250 ni = ni + "<span class=\"repeat vcard\">Repeated by " +
251 "<a href=\"" + ru['profile_url'] + "\" class=\"url\">" +
252 "<span class=\"nickname\">"+ ru['screen_name'] + "</span></a></span>";
257 ni = ni + "<div class=\"notice-options\">";
259 if (RealtimeUpdate._userid != 0) {
260 var input = $("form#form_notice fieldset input#token");
261 var session_key = input.val();
262 ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
263 ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
264 if (RealtimeUpdate._userid == responsible['id']) {
265 ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
266 } else if (RealtimeUpdate._userid != user['id']) {
267 ni = ni+RealtimeUpdate.makeRepeatForm(data['id'], session_key);
278 * Creates a favorite button.
280 * @param {number} id: notice ID to work with
281 * @param {String} session_key: session token for form CSRF protection
282 * @return {String} HTML fragment
284 * @fixme this replicates core StatusNet code, making maintenance harder
285 * @fixme sloppy HTML building (raw concat without escaping)
286 * @fixme no i18n support
290 makeFavoriteForm: function(id, session_key)
294 ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
296 "<legend>Favor this notice</legend>"+
297 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
298 "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
299 "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
306 * Creates a reply button.
308 * @param {number} id: notice ID to work with
309 * @param {String} nickname: nick of the user to whom we are replying
310 * @return {String} HTML fragment
312 * @fixme this replicates core StatusNet code, making maintenance harder
313 * @fixme sloppy HTML building (raw concat without escaping)
314 * @fixme no i18n support
318 makeReplyLink: function(id, nickname)
321 rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
326 * Creates a repeat button.
328 * @param {number} id: notice ID to work with
329 * @param {String} session_key: session token for form CSRF protection
330 * @return {String} HTML fragment
332 * @fixme this replicates core StatusNet code, making maintenance harder
333 * @fixme sloppy HTML building (raw concat without escaping)
334 * @fixme no i18n support
338 makeRepeatForm: function(id, session_key)
341 rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
343 "<legend>Repeat this notice?</legend>"+
344 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
345 "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
346 "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
354 * Creates a delete button.
356 * @param {number} id: notice ID to create a delete link for
357 * @return {String} HTML fragment
359 * @fixme this replicates core StatusNet code, making maintenance harder
360 * @fixme sloppy HTML building (raw concat without escaping)
361 * @fixme no i18n support
365 makeDeleteLink: function(id)
368 delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
370 dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
376 * Adds a control widget at the top of the timeline view, containing
377 * pause/play and popup buttons.
379 * @param {String} url: full URL to the popup window variant of this timeline page
380 * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
381 * @param {String} path: URL to the base directory containing the Realtime plugin,
382 * used to fetch resources if needed.
384 * @todo timeline and path parameters are unused and probably should be removed.
388 initActions: function(url, timeline, path)
390 $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
392 RealtimeUpdate._pluginPath = path;
394 RealtimeUpdate.initPlayPause();
395 RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
399 * Initialize the state of the play/pause controls.
401 * If the browser supports the localStorage interface, we'll attempt
402 * to retrieve a pause state from there; otherwise we default to paused.
406 initPlayPause: function()
408 if (typeof(localStorage) == 'undefined') {
409 RealtimeUpdate.showPause();
412 if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
413 RealtimeUpdate.showPlay();
416 RealtimeUpdate.showPause();
422 * Switch the realtime UI into paused state.
423 * Uses SN.msg i18n system for the button label and tooltip.
425 * State will be saved and re-used next time if the browser supports
426 * the localStorage interface (via setPause).
430 showPause: function()
432 RealtimeUpdate.setPause(false);
433 RealtimeUpdate.showQueuedNotices();
434 RealtimeUpdate.addNoticesHover();
436 $('#realtime_playpause').remove();
437 $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
438 $('#realtime_pause').text(SN.msg('realtime_pause'))
439 .attr('title', SN.msg('realtime_pause_tooltip'))
440 .bind('click', function() {
441 RealtimeUpdate.removeNoticesHover();
442 RealtimeUpdate.showPlay();
448 * Switch the realtime UI into play state.
449 * Uses SN.msg i18n system for the button label and tooltip.
451 * State will be saved and re-used next time if the browser supports
452 * the localStorage interface (via setPause).
458 RealtimeUpdate.setPause(true);
459 $('#realtime_playpause').remove();
460 $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
461 $('#realtime_play').text(SN.msg('realtime_play'))
462 .attr('title', SN.msg('realtime_play_tooltip'))
463 .bind('click', function() {
464 RealtimeUpdate.showPause();
470 * Update the internal pause/play state.
471 * Do not call directly; use showPause() and showPlay().
473 * State will be saved and re-used next time if the browser supports
474 * the localStorage interface.
476 * @param {boolean} state: true = paused, false = not paused
480 setPause: function(state)
482 RealtimeUpdate._paused = state;
483 if (typeof(localStorage) != 'undefined') {
484 localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
489 * Go through notices we have previously received while paused,
490 * dumping them into the timeline view.
492 * @fixme long timelines are not trimmed here as they are for things received while not paused
493 * @fixme Ticket #2913: the queued counter on the window title does not get cleared
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%'});