<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[23382] trunk: Heartbeat API: throttle down when the window looses focus or when the user is inactive, always send 'screen_id', change the interval settings to 'fast' (5sec), 'standard' (15sec) and 'slow' (60sec), the interval can be changed from PHP, see #23216</title>
</head>
<body>
<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; }
#msg dl a { font-weight: bold}
#msg dl a:link { color:#fc3; }
#msg dl a:active { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg > ul, #logmsg > ol { margin-left: 0; margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://core.trac.wordpress.org/changeset/23382">23382</a></dd>
<dt>Author</dt> <dd>azaozz</dd>
<dt>Date</dt> <dd>2013-02-03 07:03:27 +0000 (Sun, 03 Feb 2013)</dd>
</dl>
<h3>Log Message</h3>
<pre>Heartbeat API: throttle down when the window looses focus or when the user is inactive, always send 'screen_id', change the interval settings to 'fast' (5sec), 'standard' (15sec) and 'slow' (60sec), the interval can be changed from PHP, see <a href="http://core.trac.wordpress.org/ticket/23216">#23216</a></pre>
<h3>Modified Paths</h3>
<ul>
<li><a href="#trunkwpadminincludesajaxactionsphp">trunk/wp-admin/includes/ajax-actions.php</a></li>
<li><a href="#trunkwpincludesjsheartbeatjs">trunk/wp-includes/js/heartbeat.js</a></li>
</ul>
</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunkwpadminincludesajaxactionsphp"></a>
<div class="modfile"><h4>Modified: trunk/wp-admin/includes/ajax-actions.php (23381 => 23382)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/wp-admin/includes/ajax-actions.php        2013-02-02 17:02:01 UTC (rev 23381)
+++ trunk/wp-admin/includes/ajax-actions.php        2013-02-03 07:03:27 UTC (rev 23382)
</span><span class="lines">@@ -2074,10 +2074,13 @@
</span><span class="cx">
</span><span class="cx"> function wp_ajax_heartbeat() {
</span><span class="cx">         check_ajax_referer( 'heartbeat-nonce', '_nonce' );
</span><del>-        $response = array( 'pagenow' => '' );
</del><ins>+        $response = array();
</ins><span class="cx">
</span><del>-        if ( ! empty($_POST['pagenow']) )
-                $response['pagenow'] = sanitize_key($_POST['pagenow']);
</del><ins>+        // screenid is the same as $current_screen->id and the JS global 'pagenow'
+        if ( ! empty($_POST['screenid']) )
+                $screen_id = sanitize_key($_POST['screenid']);
+        else
+                $screen_id = 'site';
</ins><span class="cx">         
</span><span class="cx">         if ( ! empty($_POST['data']) ) {
</span><span class="cx">                 $data = (array) $_POST['data'];
</span><span class="lines">@@ -2087,16 +2090,20 @@
</span><span class="cx">
</span><span class="cx">                 // todo: separate filters: 'heartbeat_[action]' so we call different callbacks only when there is data for them,
</span><span class="cx">                 // or all callbacks listen to one filter and run when there is something for them in $data?
</span><del>-                $response = apply_filters( 'heartbeat_received', $response, $data );
</del><ins>+                $response = apply_filters( 'heartbeat_received', $response, $data, $screen_id );
</ins><span class="cx">         }
</span><span class="cx">
</span><del>-        $response = apply_filters( 'heartbeat_send', $response );
</del><ins>+        $response = apply_filters( 'heartbeat_send', $response, $screen_id );
</ins><span class="cx">
</span><span class="cx">         // Allow the transport to be replaced with long-polling easily
</span><del>-        do_action( 'heartbeat_tick', $response );
</del><ins>+        do_action( 'heartbeat_tick', $response, $screen_id );
</ins><span class="cx">
</span><del>-        // always send the current time acording to the server
-        $response['time'] = time();
</del><ins>+        // send the current time acording to the server
+        $response['servertime'] = time();
</ins><span class="cx">
</span><ins>+        // Change the interval, format: array( speed, ticks )
+        if ( isset($response['heartbeat_interval']) )
+                $response['heartbeat_interval'] = (array) $response['heartbeat_interval'];
+
</ins><span class="cx">         wp_send_json($response);
</span><span class="cx"> }
</span></span></pre></div>
<a id="trunkwpincludesjsheartbeatjs"></a>
<div class="modfile"><h4>Modified: trunk/wp-includes/js/heartbeat.js (23381 => 23382)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/wp-includes/js/heartbeat.js        2013-02-02 17:02:01 UTC (rev 23381)
+++ trunk/wp-includes/js/heartbeat.js        2013-02-03 07:03:27 UTC (rev 23382)
</span><span class="lines">@@ -9,14 +9,22 @@
</span><span class="cx">         var Heartbeat = function() {
</span><span class="cx">                 var self = this,
</span><span class="cx">                         running,
</span><del>-                        timeout,
</del><ins>+                        beat,
</ins><span class="cx">                         nonce,
</span><del>-                        screen = typeof pagenow != 'undefined' ? pagenow : '',
</del><ins>+                        screenid = typeof pagenow != 'undefined' ? pagenow : '',
</ins><span class="cx">                         settings,
</span><span class="cx">                         tick = 0,
</span><span class="cx">                         queue = {},
</span><span class="cx">                         interval,
</span><del>-                        lastconnect = 0;
</del><ins>+                        lastconnect = 0,
+                        connecting,
+                        countdown,
+                        tempInterval,
+                        hasFocus = true,
+                        isUserActive,
+                        userActiveEvents,
+                        winBlurTimeout,
+                        frameBlurTimeout = -1;
</ins><span class="cx">
</span><span class="cx">                 this.url = typeof ajaxurl != 'undefined' ? ajaxurl : 'wp-admin/admin-ajax.php';
</span><span class="cx">                 this.autostart = true;
</span><span class="lines">@@ -29,15 +37,22 @@
</span><span class="cx">                         nonce = settings.nonce || '';
</span><span class="cx">                         delete settings.nonce;
</span><span class="cx">
</span><del>-                        interval = settings.interval || 15000; // default interval
</del><ins>+                        interval = settings.interval || 15; // default interval
</ins><span class="cx">                         delete settings.interval;
</span><del>-                        
</del><ins>+                        // The interval can be from 5 to 60 sec.
+                        if ( interval < 5 )
+                                interval = 5;
+                        else if ( interval > 60 )
+                                interval = 60;
+
+                        interval = interval * 1000;
+
</ins><span class="cx">                         // todo: needed?
</span><del>-                        // 'pagenow' can be added from settings if not already defined
-                        screen = screen || settings.pagenow;
-                        delete settings.pagenow;
</del><ins>+                        // 'screenid' can be added from settings on the front-end where the JS global 'pagenow' is not set
+                        screenid = screenid || settings.screenid || 'site';
+                        delete settings.screenid;
</ins><span class="cx">
</span><del>-                        // Add public vars
</del><ins>+                        // Add or overwrite public vars
</ins><span class="cx">                         $.extend( this, settings );
</span><span class="cx">                 }
</span><span class="cx">
</span><span class="lines">@@ -48,14 +63,15 @@
</span><span class="cx">                         return (new Date()).getTime();
</span><span class="cx">                 }
</span><span class="cx">
</span><del>-                // Set error state and fire an event if it persists for over 3 min
</del><ins>+                // Set error state and fire an event if errors persist for over 2 min when the window has focus
+                // or 6 min when the window is in the background
</ins><span class="cx">                 function errorstate() {
</span><span class="cx">                         var since;
</span><span class="cx">
</span><span class="cx">                         if ( lastconnect ) {
</span><del>-                                since = time() - lastconnect;
</del><ins>+                                since = time() - lastconnect, duration = hasFocus ? 120000 : 360000;
</ins><span class="cx">
</span><del>-                                if ( since > 180000 ) {
</del><ins>+                                if ( since > duration ) {
</ins><span class="cx">                                         self.connectionLost = true;
</span><span class="cx">                                         $(document).trigger( 'heartbeat-connection-lost', parseInt(since / 1000) );
</span><span class="cx">                                 } else if ( self.connectionLost ) {
</span><span class="lines">@@ -70,106 +86,302 @@
</span><span class="cx">                         tick = time();
</span><span class="cx">
</span><span class="cx">                         data.data = $.extend( {}, queue );
</span><del>-                        queue = {};
</del><span class="cx">
</span><span class="cx">                         data.interval = interval / 1000;
</span><span class="cx">                         data._nonce = nonce;
</span><span class="cx">                         data.action = 'heartbeat';
</span><del>-                        data.pagenow = screen;
</del><ins>+                        data.screenid = screenid;
+                        data.has_focus = hasFocus;
</ins><span class="cx">
</span><del>-                        self.xhr = $.post( self.url, data, function(r){
</del><ins>+                        connecting = true;
+                        self.xhr = $.post( self.url, data, 'json' )
+                        .done( function( data, textStatus, jqXHR ) {
+                                var interval;
+
+                                // Clear the data queue
+                                queue = {};
+
+                                // Clear error state
</ins><span class="cx">                                 lastconnect = time();
</span><del>-                                // Clear error state
</del><span class="cx">                                 if ( self.connectionLost )
</span><span class="cx">                                         errorstate();
</span><del>-                                
-                                self.tick(r);
-                        }, 'json' ).always( function(){
</del><ins>+
+                                // Change the interval from PHP
+                                interval = data.heartbeat_interval;
+                                delete data.heartbeat_interval;
+
+                                self.tick( data, textStatus, jqXHR );
+
+                                // do this last, can trigger the next XHR
+                                if ( interval )
+                                        self.interval.apply( self, data.heartbeat_interval );
+                        }).always( function(){
+                                connecting = false;
</ins><span class="cx">                                 next();
</span><del>-                        }).fail( function(r){
</del><ins>+                        }).fail( function( jqXHR, textStatus, error ){
</ins><span class="cx">                                 errorstate();
</span><del>-                                self.error(r);
</del><ins>+                                self.error( jqXHR, textStatus, error );
</ins><span class="cx">                         });
</span><span class="cx">                 };
</span><span class="cx">
</span><span class="cx">                 function next() {
</span><del>-                        var delta = time() - tick;
</del><ins>+                        var delta = time() - tick, t = interval;
</ins><span class="cx">
</span><span class="cx">                         if ( !running )
</span><span class="cx">                                 return;
</span><span class="cx">
</span><del>-                        if ( delta < interval ) {
-                                timeout = window.setTimeout(
</del><ins>+                        if ( !hasFocus ) {
+                                t = 120000; // 2 min
+                        } else if ( countdown && tempInterval ) {
+                                t = tempInterval;
+                                countdown--;
+                        }
+
+                        window.clearTimeout(beat);
+
+                        if ( delta < t ) {
+                                beat = window.setTimeout(
</ins><span class="cx">                                         function(){
</span><span class="cx">                                                 if ( running )
</span><span class="cx">                                                         connect();
</span><span class="cx">                                         },
</span><del>-                                        interval - delta
</del><ins>+                                        t - delta
</ins><span class="cx">                                 );
</span><span class="cx">                         } else {
</span><del>-                                window.clearTimeout(timeout); // this has already expired?
</del><span class="cx">                                 connect();
</span><span class="cx">                         }
</span><del>-                };
</del><ins>+                }
</ins><span class="cx">
</span><del>-                this.interval = function(seconds) {
-                        if ( seconds ) {
-                                // Limit
-                                if ( 5 > seconds || seconds > 60 )
-                                        return false;
</del><ins>+                function blurred() {
+                        window.clearTimeout(winBlurTimeout);
+                        window.clearTimeout(frameBlurTimeout);
+                        winBlurTimeout = frameBlurTimeout = 0;
</ins><span class="cx">
</span><del>-                                interval = seconds * 1000;
-                        } else if ( seconds === 0 ) {
-                                // Allow long polling to be turned on
-                                interval = 0;
</del><ins>+                        hasFocus = false;
+
+                        // temp debug
+                        if ( self.debug )
+                                console.log('### blurred(), slow down...')
+                }
+
+                function focused() {
+                        window.clearTimeout(winBlurTimeout);
+                        window.clearTimeout(frameBlurTimeout);
+                        winBlurTimeout = frameBlurTimeout = 0;
+
+                        isUserActive = time();
+
+                        if ( hasFocus )
+                                return;
+
+                        hasFocus = true;
+                        window.clearTimeout(beat);
+
+                        if ( !connecting )
+                                next();
+
+                        // temp debug
+                        if ( self.debug )
+                                console.log('### focused(), speed up... ')
+                }
+
+                function setFrameEvents() {
+                        $('iframe').each( function(i, frame){
+                                if ( $.data(frame, 'wp-heartbeat-focus') )
+                                        return;
+
+                                $.data(frame, 'wp-heartbeat-focus', 1);
+
+                                $(frame.contentWindow).on('focus.wp-heartbeat-focus', function(e){
+                                        focused();
+                                }).on('blur.wp-heartbeat-focus', function(e){
+                                        setFrameEvents();
+                                        frameBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
+                                });
+                        });
+                }
+
+                $(window).on('blur.wp-heartbeat-focus', function(e){
+                        setFrameEvents();
+                        winBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
+                }).on('focus.wp-heartbeat-focus', function(){
+                        $('iframe').each( function(i, frame){
+                                $.removeData(frame, 'wp-heartbeat-focus');
+                                $(frame.contentWindow).off('.wp-heartbeat-focus');
+                        });
+
+                        focused();
+                });
+
+                function userIsActive() {
+                        userActiveEvents = false;
+                        $(document).off('.wp-heartbeat-active');
+                        $('iframe').each( function(i, frame){
+                                $(frame.contentWindow).off('.wp-heartbeat-active');
+                        });
+
+                        focused();
+
+                        // temp debug
+                        if ( self.debug )
+                                console.log( 'userIsActive()' );
+                }
+
+                // Set 'hasFocus = true' if user is active and the window is in the background.
+                // Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity) for 5 min. even when the window has focus.
+                function checkUserActive() {
+                        var lastActive = isUserActive ? time() - isUserActive : 0;
+
+                        // temp debug
+                        if ( self.debug )
+                                console.log( 'checkUserActive(), lastActive = %s seconds ago', parseInt(lastActive / 1000) || 'null' );
+
+                        // Throttle down when no mouse or keyboard activity for 5 min
+                        if ( lastActive > 300000 && hasFocus )
+                                 blurred();
+
+                        if ( !userActiveEvents ) {
+                                $(document).on('mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); });
+                                $('iframe').each( function(i, frame){
+                                        $(frame.contentWindow).on('mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); });
+                                });
+                                userActiveEvents = true;
</ins><span class="cx">                         }
</span><del>-                        return interval / 1000;
</del><ins>+                }
+
+                // Check for user activity every 30 seconds.
+                window.setInterval( function(){ checkUserActive(); }, 30000 );
+
+                if ( this.autostart ) {
+                        $(document).ready( function(){
+                                // Start one tick (15 sec) after DOM ready
+                                running = true;
+                                tick = time();
+                                next();
+                        });
+                }
+
+                this.winHasFocus = function() {
+                        return hasFocus;
+                }
+
+                /**
+                 * Get/Set the interval
+                 *
+                 * When setting the interval to 'fast', the number of ticks is specified wiht the second argument, default 30.
+                 * If the window doesn't have focus, the interval is overridden to 2 min. In this case setting the 'ticks'
+                 * will start counting after the window gets focus.
+                 *
+                 * @param string speed Interval speed: 'fast' (5sec), 'standard' (15sec) default, 'slow' (60sec)
+                 * @param int ticks Number of ticks for the changed interval, optional when setting 'standard' or 'slow'
+                 * @return int Current interval in seconds
+                 */
+                this.interval = function(speed, ticks) {
+                        var reset, seconds;
+
+                        if ( speed ) {
+                                switch ( speed ) {
+                                        case 'fast':
+                                                seconds = 5;
+                                                countdown = parseInt(ticks) || 30;
+                                                break;
+                                        case 'slow':
+                                                seconds = 60;
+                                                countdown = parseInt(ticks) || 0;
+                                                break;
+                                        case 'long-polling':
+                                                // Allow long polling, (experimental)
+                                                interval = 0;
+                                                return 0;
+                                                break;
+                                        default:
+                                                seconds = 15;
+                                                countdown = 0;
+                                }
+
+                                // Reset when the new interval value is lower than the current one
+                                reset = seconds * 1000 < interval;
+
+                                if ( countdown ) {
+                                        tempInterval = seconds * 1000;
+                                } else {
+                                        interval = seconds * 1000;
+                                        tempInterval = 0;
+                                }
+
+                                if ( reset )
+                                        next();
+                        }
+
+                        if ( !hasFocus )
+                                return 120;
+
+                        return tempInterval ? tempInterval / 1000 : interval / 1000;
</ins><span class="cx">                 };
</span><span class="cx">
</span><ins>+                // Start. Has no effect if heartbeat is already running
</ins><span class="cx">                 this.start = function() {
</span><del>-                        // start only once
</del><span class="cx">                         if ( running )
</span><span class="cx">                                 return false;
</span><span class="cx">
</span><span class="cx">                         running = true;
</span><span class="cx">                         connect();
</span><del>-
</del><span class="cx">                         return true;
</span><span class="cx">                 };
</span><span class="cx">
</span><ins>+                // Stop. If a XHR is in progress, abort it
</ins><span class="cx">                 this.stop = function() {
</span><del>-                        if ( !running )
-                                return false;
-
-                        if ( self.xhr )
</del><ins>+                        if ( self.xhr && self.xhr.readyState != 4 )
</ins><span class="cx">                                 self.xhr.abort();
</span><span class="cx">
</span><span class="cx">                         running = false;
</span><span class="cx">                         return true;
</span><span class="cx">                 }
</span><span class="cx">
</span><del>-                this.send = function(action, data) {
-                        if ( action )
-                                queue[action] = data;
</del><ins>+                /**
+                 * Send data with the next XHR
+                 *
+                 * As the data is sent later, this function doesn't return the XHR response.
+                 * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
+                 *                $(document).on('heartbeat-tick.myname', function(data, textStatus, jqXHR) {
+                 *                        // code
+                 *                });
+                 * If the same 'handle' is used more than once, the data is overwritten when the third argument is 'true'.
+                 * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
+                 *
+                 * $param string handle Unique handle for the data. The handle is used in PHP to receive the data
+                 * $param mixed data The data to be sent
+                 * $param bool overwrite Whether to overwrite existing data in the queue
+                 * $return bool Whether the data was queued or not
+                 */
+                this.send = function(handle, data, overwrite) {
+                        if ( handle ) {
+                                if ( queue.hasOwnProperty(handle) && !overwrite )
+                                        return false;
+
+                                queue[handle] = data;
+                                return true;
+                        }
+                        return false;
</ins><span class="cx">                 }
</span><span class="cx">
</span><del>-                if ( this.autostart ) {
-                        $(document).ready( function(){
-                                // Start one tick (15 sec) after DOM ready
-                                running = true;
-                                tick = time();
-                                next();
-                        });
</del><ins>+                /**
+                 * Check if data with a particular handle is queued
+                 *
+                 * $param string handle The handle for the data
+                 * $return mixed The data queued with that handle or null
+                 */
+                this.isQueued = function(handle) {
+                        return queue[handle];
</ins><span class="cx">                 }
</span><del>-                        
</del><span class="cx">         }
</span><span class="cx">
</span><span class="cx">         $.extend( Heartbeat.prototype, {
</span><del>-                tick: function(r) {
-                        $(document).trigger( 'heartbeat-tick', r );
</del><ins>+                tick: function(data, textStatus, jqXHR) {
+                        $(document).trigger( 'heartbeat-tick', [data, textStatus, jqXHR] );
</ins><span class="cx">                 },
</span><del>-                error: function(r) {
-                        $(document).trigger( 'heartbeat-error', r );
</del><ins>+                error: function(jqXHR, textStatus, error) {
+                        $(document).trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
</ins><span class="cx">                 }
</span><span class="cx">         });
</span><span class="cx">
</span></span></pre>
</div>
</div>
</body>
</html>