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() {
88 RealtimeUpdate._windowhasfocus = true;
90 // Clear the counter on the window title when we focus in.
91 RealtimeUpdate._updatecounter = 0;
92 RealtimeUpdate.removeWindowCounter();
95 $(window).bind('blur', function() {
96 $('#notices_primary .notice').removeClass('mark-top');
98 $('#notices_primary .notice:first').addClass('mark-top');
100 // While we're in the background, received messages will increment
101 // a counter that we put on the window title. This will cause some
102 // browsers to also flash or mark the tab or window title bar until
103 // you seek attention (eg Firefox 4 pinned app tabs).
104 RealtimeUpdate._windowhasfocus = false;
111 * Accept a notice in a Twitter-API JSON style and either show it
112 * or queue it up, depending on whether the realtime display is
115 * The meat of a Realtime plugin subclass is to provide a substrate
116 * transport to receive data and shove it into this function. :)
118 * Note that the JSON data is extended from the standard API return
119 * with additional fields added by RealtimePlugin's PHP code.
121 * @param {Object} data: extended JSON API-formatted notice
125 receive: function(data)
127 if (RealtimeUpdate.isNoticeVisible(data.id)) {
128 // Probably posted by the user in this window, and so already
129 // shown by the AJAX form handler. Ignore it.
132 if (RealtimeUpdate._paused === false) {
133 RealtimeUpdate.purgeLastNoticeItem();
135 RealtimeUpdate.insertNoticeItem(data);
138 RealtimeUpdate._queuedNotices.push(data);
140 RealtimeUpdate.updateQueuedCounter();
143 RealtimeUpdate.updateWindowCounter();
147 * Add a visible representation of the given notice at the top of
148 * the current timeline.
150 * If the notice is already in the timeline, nothing will be added.
152 * @param {Object} data: extended JSON API-formatted notice
154 * @fixme while core UI JS code is used to activate the AJAX UI controls,
155 * the actual production of HTML (in makeNoticeItem and its subs)
156 * duplicates core code without plugin hook points or i18n support.
160 insertNoticeItem: function(data) {
161 // Don't add it if it already exists
162 if (RealtimeUpdate.isNoticeVisible(data.id)) {
166 var noticeItem = RealtimeUpdate.makeNoticeItem(data);
167 var noticeItemID = $(noticeItem).attr('id');
169 $("#notices_primary .notices").prepend(noticeItem);
170 $("#notices_primary .notice:first").css({display:"none"});
171 $("#notices_primary .notice:first").fadeIn(1000);
173 SN.U.NoticeReplyTo($('#'+noticeItemID));
174 SN.U.NoticeWithAttachment($('#'+noticeItemID));
178 * Check if the given notice is visible in the timeline currently.
179 * Used to avoid duplicate processing of notices that have been
180 * displayed by other means.
182 * @param {number} id: notice ID to check
188 isNoticeVisible: function(id) {
189 return ($("#notice-"+id).length > 0);
193 * Trims a notice off the end of the timeline if we have more than the
194 * maximum number of notices visible.
198 purgeLastNoticeItem: function() {
199 if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
200 $("#notices_primary .notice:last").remove();
205 * If the window/tab is in background, increment the counter of newly
206 * received notices and append it onto the window title.
208 * Has no effect if the window is in foreground.
212 updateWindowCounter: function() {
213 if (RealtimeUpdate._windowhasfocus === false) {
214 RealtimeUpdate._updatecounter += 1;
215 document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
220 * Clear the background update counter from the window title.
224 * @fixme could interfere with anything else trying similar tricks
226 removeWindowCounter: function() {
227 document.title = RealtimeUpdate._documenttitle;
231 * Builds a notice HTML block from JSON API-style data.
233 * @param {Object} data: extended JSON API-formatted notice
234 * @return {String} HTML fragment
236 * @fixme this replicates core StatusNet code, making maintenance harder
237 * @fixme sloppy HTML building (raw concat without escaping)
238 * @fixme no i18n support
239 * @fixme local variables pollute global namespace
243 makeNoticeItem: function(data)
245 if (data.hasOwnProperty('retweeted_status')) {
246 original = data['retweeted_status'];
249 unique = repeat['id'];
250 responsible = repeat['user'];
255 responsible = data['user'];
259 html = data['html'].replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/&/g,'&');
260 source = data['source'].replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/&/g,'&');
262 ni = "<li class=\"hentry notice\" id=\"notice-"+unique+"\">"+
263 "<div class=\"entry-title\">"+
264 "<span class=\"vcard author\">"+
265 "<a href=\""+user['profile_url']+"\" class=\"url\" title=\""+user['name']+"\">"+
266 "<img src=\""+user['profile_image_url']+"\" class=\"avatar photo\" width=\"48\" height=\"48\" alt=\""+user['screen_name']+"\"/>"+
267 "<span class=\"nickname fn\">"+user['screen_name']+"</span>"+
270 "<p class=\"entry-content\">"+html+"</p>"+
272 "<div class=\"entry-content\">"+
273 "<a class=\"timestamp\" rel=\"bookmark\" href=\""+data['url']+"\" >"+
274 "<abbr class=\"published\" title=\""+data['created_at']+"\">a few seconds ago</abbr>"+
276 "<span class=\"source\">"+
278 "<span class=\"device\">"+source+"</span>"+ // may have a link
280 if (data['conversation_url']) {
281 ni = ni+" <a class=\"response\" href=\""+data['conversation_url']+"\">in context</a>";
286 ni = ni + "<span class=\"repeat vcard\">Repeated by " +
287 "<a href=\"" + ru['profile_url'] + "\" class=\"url\">" +
288 "<span class=\"nickname\">"+ ru['screen_name'] + "</span></a></span>";
293 ni = ni + "<div class=\"notice-options\">";
295 if (RealtimeUpdate._userid != 0) {
296 var input = $("form#form_notice fieldset input#token");
297 var session_key = input.val();
298 ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
299 ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
300 if (RealtimeUpdate._userid == responsible['id']) {
301 ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
302 } else if (RealtimeUpdate._userid != user['id']) {
303 ni = ni+RealtimeUpdate.makeRepeatForm(data['id'], session_key);
314 * Creates a favorite button.
316 * @param {number} id: notice ID to work with
317 * @param {String} session_key: session token for form CSRF protection
318 * @return {String} HTML fragment
320 * @fixme this replicates core StatusNet code, making maintenance harder
321 * @fixme sloppy HTML building (raw concat without escaping)
322 * @fixme no i18n support
326 makeFavoriteForm: function(id, session_key)
330 ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
332 "<legend>Favor this notice</legend>"+
333 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
334 "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
335 "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
342 * Creates a reply button.
344 * @param {number} id: notice ID to work with
345 * @param {String} nickname: nick of the user to whom we are replying
346 * @return {String} HTML fragment
348 * @fixme this replicates core StatusNet code, making maintenance harder
349 * @fixme sloppy HTML building (raw concat without escaping)
350 * @fixme no i18n support
354 makeReplyLink: function(id, nickname)
357 rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
362 * Creates a repeat button.
364 * @param {number} id: notice ID to work with
365 * @param {String} session_key: session token for form CSRF protection
366 * @return {String} HTML fragment
368 * @fixme this replicates core StatusNet code, making maintenance harder
369 * @fixme sloppy HTML building (raw concat without escaping)
370 * @fixme no i18n support
374 makeRepeatForm: function(id, session_key)
377 rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
379 "<legend>Repeat this notice?</legend>"+
380 "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
381 "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
382 "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
390 * Creates a delete button.
392 * @param {number} id: notice ID to create a delete link for
393 * @return {String} HTML fragment
395 * @fixme this replicates core StatusNet code, making maintenance harder
396 * @fixme sloppy HTML building (raw concat without escaping)
397 * @fixme no i18n support
401 makeDeleteLink: function(id)
404 delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
406 dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
412 * Adds a control widget at the top of the timeline view, containing
413 * pause/play and popup buttons.
415 * @param {String} url: full URL to the popup window variant of this timeline page
416 * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
417 * @param {String} path: URL to the base directory containing the Realtime plugin,
418 * used to fetch resources if needed.
420 * @todo timeline and path parameters are unused and probably should be removed.
424 initActions: function(url, timeline, path)
426 $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
428 RealtimeUpdate._pluginPath = path;
430 RealtimeUpdate.initPlayPause();
431 RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
435 * Initialize the state of the play/pause controls.
437 * If the browser supports the localStorage interface, we'll attempt
438 * to retrieve a pause state from there; otherwise we default to paused.
442 initPlayPause: function()
444 if (typeof(localStorage) == 'undefined') {
445 RealtimeUpdate.showPause();
448 if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
449 RealtimeUpdate.showPlay();
452 RealtimeUpdate.showPause();
458 * Switch the realtime UI into paused state.
459 * Uses SN.msg i18n system for the button label and tooltip.
461 * State will be saved and re-used next time if the browser supports
462 * the localStorage interface (via setPause).
466 showPause: function()
468 RealtimeUpdate.setPause(false);
469 RealtimeUpdate.showQueuedNotices();
470 RealtimeUpdate.addNoticesHover();
472 $('#realtime_playpause').remove();
473 $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
474 $('#realtime_pause').text(SN.msg('realtime_pause'))
475 .attr('title', SN.msg('realtime_pause_tooltip'))
476 .bind('click', function() {
477 RealtimeUpdate.removeNoticesHover();
478 RealtimeUpdate.showPlay();
484 * Switch the realtime UI into play state.
485 * Uses SN.msg i18n system for the button label and tooltip.
487 * State will be saved and re-used next time if the browser supports
488 * the localStorage interface (via setPause).
494 RealtimeUpdate.setPause(true);
495 $('#realtime_playpause').remove();
496 $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
497 $('#realtime_play').text(SN.msg('realtime_play'))
498 .attr('title', SN.msg('realtime_play_tooltip'))
499 .bind('click', function() {
500 RealtimeUpdate.showPause();
506 * Update the internal pause/play state.
507 * Do not call directly; use showPause() and showPlay().
509 * State will be saved and re-used next time if the browser supports
510 * the localStorage interface.
512 * @param {boolean} state: true = paused, false = not paused
516 setPause: function(state)
518 RealtimeUpdate._paused = state;
519 if (typeof(localStorage) != 'undefined') {
520 localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
525 * Go through notices we have previously received while paused,
526 * dumping them into the timeline view.
528 * @fixme long timelines are not trimmed here as they are for things received while not paused
532 showQueuedNotices: function()
534 $.each(RealtimeUpdate._queuedNotices, function(i, n) {
535 RealtimeUpdate.insertNoticeItem(n);
538 RealtimeUpdate._queuedNotices = [];
540 RealtimeUpdate.removeQueuedCounter();
544 * Update the Realtime widget control's counter of queued notices to show
545 * the current count. This will be called after receiving and queueing
546 * a notice while paused.
550 updateQueuedCounter: function()
552 $('#realtime_playpause #queued_counter').html('('+RealtimeUpdate._queuedNotices.length+')');
556 * Clear the Realtime widget control's counter of queued notices.
560 removeQueuedCounter: function()
562 $('#realtime_playpause #queued_counter').empty();
566 * Set up event handlers on the timeline view to automatically pause
567 * when the mouse is over the timeline, as this indicates the user's
568 * desire to interact with the UI. (Which is hard to do when it's moving!)
572 addNoticesHover: function()
574 $('#notices_primary .notices').hover(
576 if (RealtimeUpdate._paused === false) {
577 RealtimeUpdate.showPlay();
581 if (RealtimeUpdate._paused === true) {
582 RealtimeUpdate.showPause();
589 * Tear down event handlers on the timeline view to automatically pause
590 * when the mouse is over the timeline.
592 * @fixme this appears to remove *ALL* event handlers from the timeline,
593 * which assumes that nobody else is adding any event handlers.
594 * Sloppy -- we should only remove the ones we add.
598 removeNoticesHover: function()
600 $('#notices_primary .notices').unbind();
604 * UI initialization, to be called from Realtime plugin code on regular
607 * Adds a button to the control widget at the top of the timeline view,
608 * allowing creation of a popup window with a more compact real-time
609 * view of the current timeline.
611 * @param {String} url: full URL to the popup window variant of this timeline page
612 * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
613 * @param {String} path: URL to the base directory containing the Realtime plugin,
614 * used to fetch resources if needed.
616 * @todo timeline and path parameters are unused and probably should be removed.
620 initAddPopup: function(url, timeline, path)
622 $('#realtime_timeline').append('<button id="realtime_popup"></button>');
623 $('#realtime_popup').text(SN.msg('realtime_popup'))
624 .attr('title', SN.msg('realtime_popup_tooltip'))
625 .bind('click', function() {
628 'toolbar=no,resizable=yes,scrollbars=yes,status=no,menubar=no,personalbar=no,location=no,width=500,height=550');
635 * UI initialization, to be called from Realtime plugin code on popup
636 * compact timeline pages.
638 * Sets up links in notices to open in a new window.
640 * @fixme fails to do the same for UI links like context view which will
641 * look bad in the tiny chromeless window.
645 initPopupWindow: function()
647 $('.notices .entry-title a, .notices .entry-content a').bind('click', function() {
648 window.open(this.href, '');
653 $('#showstream .entity_profile').css({'width':'69%'});