<!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>[26169] trunk/src: Heartbeat: clean up code style, better naming, better code structure.</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 { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { 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/26169">26169</a></dd>
<dt>Author</dt> <dd>azaozz</dd>
<dt>Date</dt> <dd>2013-11-14 18:40:03 +0000 (Thu, 14 Nov 2013)</dd>
</dl>
<h3>Log Message</h3>
<pre>Heartbeat: clean up code style, better naming, better code structure. Props carldanley, props evansolomon.
Changes:
- Add connectNow() public method to trigger a connection immediately.
- Remove the "skipping" when no data to send.
- Change the default interval to 60 sec.
- Fix resetting the next connection time when changing the interval.
See <a href="http://core.trac.wordpress.org/ticket/25073">#25073</a>.</pre>
<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpadminincludespostphp">trunk/src/wp-admin/includes/post.php</a></li>
<li><a href="#trunksrcwpadminjsinlineeditpostjs">trunk/src/wp-admin/js/inline-edit-post.js</a></li>
<li><a href="#trunksrcwpadminjspostjs">trunk/src/wp-admin/js/post.js</a></li>
<li><a href="#trunksrcwpincludesjsheartbeatjs">trunk/src/wp-includes/js/heartbeat.js</a></li>
</ul>
</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpadminincludespostphp"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-admin/includes/post.php (26168 => 26169)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-admin/includes/post.php 2013-11-14 18:16:59 UTC (rev 26168)
+++ trunk/src/wp-admin/includes/post.php 2013-11-14 18:40:03 UTC (rev 26169)
</span><span class="lines">@@ -1185,7 +1185,7 @@
</span><span class="cx"> $time = $lock[0];
</span><span class="cx"> $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
</span><span class="cx">
</span><del>- $time_window = apply_filters( 'wp_check_post_lock_window', 120 );
</del><ins>+ $time_window = apply_filters( 'wp_check_post_lock_window', 150 );
</ins><span class="cx">
</span><span class="cx"> if ( $time && $time > time() - $time_window && $user != get_current_user_id() )
</span><span class="cx"> return $user;
</span></span></pre></div>
<a id="trunksrcwpadminjsinlineeditpostjs"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-admin/js/inline-edit-post.js (26168 => 26169)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-admin/js/inline-edit-post.js 2013-11-14 18:16:59 UTC (rev 26168)
+++ trunk/src/wp-admin/js/inline-edit-post.js 2013-11-14 18:40:03 UTC (rev 26169)
</span><span class="lines">@@ -325,6 +325,11 @@
</span><span class="cx">
</span><span class="cx"> if ( check.length )
</span><span class="cx"> data['wp-check-locked-posts'] = check;
</span><ins>+}).ready( function() {
+ // Set the heartbeat interval to 15 sec.
+ if ( typeof wp !== 'undefined' && wp.heartbeat ) {
+ wp.heartbeat.setInterval( 15 );
+ }
</ins><span class="cx"> });
</span><span class="cx">
</span><span class="cx"> }(jQuery));
</span></span></pre></div>
<a id="trunksrcwpadminjspostjs"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-admin/js/post.js (26168 => 26169)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-admin/js/post.js 2013-11-14 18:16:59 UTC (rev 26168)
+++ trunk/src/wp-admin/js/post.js 2013-11-14 18:40:03 UTC (rev 26169)
</span><span class="lines">@@ -370,6 +370,11 @@
</span><span class="cx"> e.preventDefault();
</span><span class="cx"> }
</span><span class="cx"> }).filter(':visible').find('.wp-tab-first').focus();
</span><ins>+
+ // Set the heartbeat interval to 15 sec. if post lock dialogs are enabled
+ if ( typeof wp !== 'undefined' && wp.heartbeat && $('#post-lock-dialog').length ) {
+ wp.heartbeat.setInterval( 15 );
+ }
</ins><span class="cx">
</span><span class="cx"> // multi-taxonomies
</span><span class="cx"> if ( $('#tagsdiv-post_tag').length ) {
</span></span></pre></div>
<a id="trunksrcwpincludesjsheartbeatjs"></a>
<div class="modfile"><h4>Modified: trunk/src/wp-includes/js/heartbeat.js (26168 => 26169)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/src/wp-includes/js/heartbeat.js 2013-11-14 18:16:59 UTC (rev 26168)
+++ trunk/src/wp-includes/js/heartbeat.js 2013-11-14 18:40:03 UTC (rev 26169)
</span><span class="lines">@@ -6,11 +6,11 @@
</span><span class="cx"> * to use it, please follow the development closely.
</span><span class="cx"> *
</span><span class="cx"> * Heartbeat is a simple server polling API that sends XHR requests to
</span><del>- * the server every 15 seconds and triggers events (or callbacks) upon
</del><ins>+ * the server every 15 - 60 seconds and triggers events (or callbacks) upon
</ins><span class="cx"> * receiving data. Currently these 'ticks' handle transports for post locking,
</span><span class="cx"> * login-expiration warnings, and related tasks while a user is logged in.
</span><span class="cx"> *
</span><del>- * Available filters in ajax-actions.php:
</del><ins>+ * Available PHP filters (in ajax-actions.php):
</ins><span class="cx"> * - heartbeat_received
</span><span class="cx"> * - heartbeat_send
</span><span class="cx"> * - heartbeat_tick
</span><span class="lines">@@ -19,96 +19,195 @@
</span><span class="cx"> * - heartbeat_nopriv_tick
</span><span class="cx"> * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
</span><span class="cx"> *
</span><ins>+ * Custom jQuery events:
+ * - heartbeat-send
+ * - heartbeat-tick
+ * - heartbeat-error
+ * - heartbeat-connection-lost
+ * - heartbeat-connection-restored
+ * - heartbeat-nonces-expired
+ *
</ins><span class="cx"> * @since 3.6.0
</span><span class="cx"> */
</span><span class="cx">
</span><del>- // Ensure the global `wp` object exists.
-window.wp = window.wp || {};
-
-(function($){
</del><ins>+( function( $, window, undefined ) {
</ins><span class="cx"> var Heartbeat = function() {
</span><del>- var self = this,
- running,
- beat,
- screenId = typeof pagenow != 'undefined' ? pagenow : '',
- url = typeof ajaxurl != 'undefined' ? ajaxurl : '',
- settings,
- tick = 0,
- queue = {},
- interval,
- connecting,
- countdown = 0,
- errorcount = 0,
- tempInterval,
- hasFocus = true,
- isUserActive,
- userActiveEvents,
- winBlurTimeout,
- frameBlurTimeout = -1,
- hasConnectionError = null;
</del><ins>+ var $document = $(document),
+ settings = {
+ // Used to stop the "beat"
+ isRunning: true,
</ins><span class="cx">
</span><ins>+ // Current screen id, defaults to the JS global 'pagenow' when present (in the admin) or 'front'
+ screenId: '',
+
+ // XHR request URL, defaults to the JS global 'ajaxurl' when present
+ url: '',
+
+ // Timestamp, start of the last connection request
+ lastTick: 0,
+
+ // Container for the enqueued items
+ queue: {},
+
+ // Connect interval (in seconds)
+ mainInterval: 60,
+
+ // Used when the interval is set to 5 sec. temporarily
+ tempInterval: 0,
+
+ // Used when the interval is reset
+ originalInterval: 0,
+
+ // Used together with tempInterval
+ countdown: 0,
+
+ // Whether a connection is currently in progress
+ connecting: false,
+
+ // Whether a connection error occured
+ connectionError: false,
+
+ // Used to track non-critical errors
+ errorcount: 0,
+
+ // Whether at least one connection has completed successfully
+ hasConnected: false,
+
+ // Whether the current browser window is in focus and the user is active
+ hasFocus: true,
+
+ // Timestamp, last time the user was active. Checked every 30 sec.
+ userActivity: 0,
+
+ // Flags whether events tracking user activity were set
+ userActivityEvents: false,
+
+ // References to various timeouts
+ beatTimer: 0,
+ winBlurTimer: 0,
+ frameBlurTimer: 0
+ };
+
</ins><span class="cx"> /**
</span><del>- * Returns a boolean that's indicative of whether or not there is a connection error
</del><ins>+ * Set local vars and events, then start
</ins><span class="cx"> *
</span><del>- * @returns boolean
</del><ins>+ * @access private
+ *
+ * @return void
</ins><span class="cx"> */
</span><del>- this.hasConnectionError = function() {
- return !! hasConnectionError;
- };
</del><ins>+ function initialize() {
+ if ( typeof window.pagenow === 'string' ) {
+ settings.screenId = window.pagenow;
+ }
</ins><span class="cx">
</span><del>- if ( typeof( window.heartbeatSettings ) == 'object' ) {
- settings = $.extend( {}, window.heartbeatSettings );
</del><ins>+ if ( typeof window.ajaxurl === 'string' ) {
+ settings.url = window.ajaxurl;
+ }
</ins><span class="cx">
</span><del>- // Add private vars
- url = settings.ajaxurl || url;
- delete settings.ajaxurl;
- delete settings.nonce;
</del><ins>+ // Pull in options passed from PHP
+ if ( typeof window.heartbeatSettings === 'object' ) {
+ var options = window.heartbeatSettings;
</ins><span class="cx">
</span><del>- interval = settings.interval || 15; // default interval
- delete settings.interval;
- // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec.
- if ( interval < 15 )
- interval = 15;
- else if ( interval > 60 )
- interval = 60;
</del><ins>+ // The XHR URL can be passed as option when window.ajaxurl is not set
+ if ( ! settings.url && options.ajaxurl ) {
+ settings.url = options.ajaxurl;
+ }
</ins><span class="cx">
</span><del>- interval = interval * 1000;
</del><ins>+ // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec.
+ if ( options.interval ) {
+ settings.mainInterval = options.interval;
</ins><span class="cx">
</span><del>- // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
- screenId = screenId || settings.screenId || 'front';
- delete settings.screenId;
</del><ins>+ if ( settings.mainInterval < 15 ) {
+ settings.mainInterval = 15;
+ } else if ( settings.mainInterval > 60 ) {
+ settings.mainInterval = 60;
+ }
+ }
</ins><span class="cx">
</span><del>- // Add or overwrite public vars
- $.extend( this, settings );
</del><ins>+ // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
+ if ( ! settings.screenId ) {
+ settings.screenId = options.screenId || 'front';
+ }
+ }
+
+ // Convert to milliseconds
+ settings.mainInterval = settings.mainInterval * 1000;
+ settings.originalInterval = settings.mainInterval;
+
+ // Set focus/blur events on the window
+ $(window).on( 'blur.wp-heartbeat-focus', function() {
+ setFrameFocusEvents();
+ // We don't know why the 'blur' was fired. Either the user clicked in an iframe or outside the browser.
+ // Running blurred() after some timeout lets us cancel it if the user clicked in an iframe.
+ settings.winBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
+ }).on( 'focus.wp-heartbeat-focus', function() {
+ removeFrameFocusEvents();
+ focused();
+ }).on( 'unload.wp-heartbeat', function() {
+ // Don't connect any more
+ settings.isRunning = false;
+ });
+
+ // Check for user activity every 30 seconds.
+ window.setInterval( function(){ checkUserActivity(); }, 30000 );
+
+ // Start one tick after DOM ready
+ $document.ready( function() {
+ settings.lastTick = time();
+ scheduleNextTick();
+ });
</ins><span class="cx"> }
</span><span class="cx">
</span><del>- function time(s) {
- if ( s )
- return parseInt( (new Date()).getTime() / 1000 );
-
</del><ins>+ /**
+ * Return the current time according to the browser
+ *
+ * @access private
+ *
+ * @return int
+ */
+ function time() {
</ins><span class="cx"> return (new Date()).getTime();
</span><span class="cx"> }
</span><span class="cx">
</span><ins>+ /**
+ * Check if the iframe is from the same origin
+ *
+ * @access private
+ *
+ * @return bool
+ */
</ins><span class="cx"> function isLocalFrame( frame ) {
</span><span class="cx"> var origin, src = frame.src;
</span><span class="cx">
</span><ins>+ // Need to compare strings as WebKit doesn't throw JS errors when iframes have different origin.
+ // It throws uncatchable exceptions.
</ins><span class="cx"> if ( src && /^https?:\/\//.test( src ) ) {
</span><span class="cx"> origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
</span><span class="cx">
</span><del>- if ( src.indexOf( origin ) !== 0 )
</del><ins>+ if ( src.indexOf( origin ) !== 0 ) {
</ins><span class="cx"> return false;
</span><ins>+ }
</ins><span class="cx"> }
</span><span class="cx">
</span><span class="cx"> try {
</span><del>- if ( frame.contentWindow.document )
</del><ins>+ if ( frame.contentWindow.document ) {
</ins><span class="cx"> return true;
</span><ins>+ }
</ins><span class="cx"> } catch(e) {}
</span><span class="cx">
</span><span class="cx"> return false;
</span><span class="cx"> }
</span><span class="cx">
</span><del>- // Set error state and fire an event on XHR errors or timeout
- function errorstate( error, status ) {
</del><ins>+ /**
+ * Set error state and fire an event on XHR errors or timeout
+ *
+ * @access private
+ *
+ * @param string error The error type passed from the XHR
+ * @param int status The HTTP status code passed from jqXHR (200, 404, 500, etc.)
+ * @return void
+ */
+ function setErrorState( error, status ) {
</ins><span class="cx"> var trigger;
</span><span class="cx">
</span><span class="cx"> if ( error ) {
</span><span class="lines">@@ -120,203 +219,273 @@
</span><span class="cx"> // no response for 30 sec.
</span><span class="cx"> trigger = true;
</span><span class="cx"> break;
</span><ins>+ case 'error':
+ if ( 503 === status && settings.hasConnected ) {
+ trigger = true;
+ break;
+ }
+ // Pass through other error statuses
</ins><span class="cx"> case 'parsererror':
</span><del>- case 'error':
</del><span class="cx"> case 'empty':
</span><span class="cx"> case 'unknown':
</span><del>- errorcount++;
</del><ins>+ settings.errorcount++;
</ins><span class="cx">
</span><del>- if ( errorcount > 2 )
</del><ins>+ if ( settings.errorcount > 2 && settings.hasConnected ) {
</ins><span class="cx"> trigger = true;
</span><ins>+ }
</ins><span class="cx">
</span><span class="cx"> break;
</span><span class="cx"> }
</span><span class="cx">
</span><del>- if ( 503 == status && false === hasConnectionError ) {
- trigger = true;
- }
-
- if ( trigger && ! self.hasConnectionError() ) {
- hasConnectionError = true;
</del><ins>+ if ( trigger && ! hasConnectionError() ) {
+ settings.connectionError = true;
</ins><span class="cx"> $(document).trigger( 'heartbeat-connection-lost', [error, status] );
</span><span class="cx"> }
</span><del>- } else if ( self.hasConnectionError() ) {
- errorcount = 0;
- hasConnectionError = false;
- $(document).trigger( 'heartbeat-connection-restored' );
- } else if ( null === hasConnectionError ) {
- hasConnectionError = false;
</del><span class="cx"> }
</span><span class="cx"> }
</span><span class="cx">
</span><del>- function connect() {
- var send = {}, data, i, empty = true,
- nonce = typeof window.heartbeatSettings == 'object' ? window.heartbeatSettings.nonce : '';
- tick = time();
</del><ins>+ /**
+ * Clear the error state and fire an event
+ *
+ * @access private
+ *
+ * @return void
+ */
+ function clearErrorState() {
+ // Has connected successfully
+ settings.hasConnected = true;
</ins><span class="cx">
</span><del>- data = $.extend( {}, queue );
- // Clear the data queue, anything added after this point will be send on the next tick
- queue = {};
</del><ins>+ if ( hasConnectionError() ) {
+ settings.errorcount = 0;
+ settings.connectionError = false;
+ $document.trigger( 'heartbeat-connection-restored' );
+ }
+ }
</ins><span class="cx">
</span><del>- $(document).trigger( 'heartbeat-send', [data] );
</del><ins>+ /**
+ * Gather the data and connect to the server
+ *
+ * @access private
+ *
+ * @return void
+ */
+ function connect() {
+ var ajaxData, heartbeatData;
</ins><span class="cx">
</span><del>- for ( i in data ) {
- if ( data.hasOwnProperty( i ) ) {
- empty = false;
- break;
- }
- }
-
- // If nothing to send (nothing is expecting a response),
- // schedule the next tick and bail
- if ( empty && ! self.hasConnectionError() ) {
- connecting = false;
- next();
</del><ins>+ // If the connection to the server is slower than the interval,
+ // heartbeat connects as soon as the previous connection's response is received.
+ if ( settings.connecting ) {
</ins><span class="cx"> return;
</span><span class="cx"> }
</span><span class="cx">
</span><del>- send.data = data;
- send.interval = interval / 1000;
- send._nonce = nonce;
- send.action = 'heartbeat';
- send.screen_id = screenId;
- send.has_focus = hasFocus;
</del><ins>+ settings.lastTick = time();
</ins><span class="cx">
</span><del>- connecting = true;
- self.xhr = $.ajax({
- url: url,
</del><ins>+ heartbeatData = $.extend( {}, settings.queue );
+ // Clear the data queue, anything added after this point will be send on the next tick
+ settings.queue = {};
+
+ $document.trigger( 'heartbeat-send', [ heartbeatData ] );
+
+ ajaxData = {
+ data: heartbeatData,
+ interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
+ _nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
+ action: 'heartbeat',
+ screen_id: settings.screenId,
+ has_focus: settings.hasFocus
+ };
+
+ settings.connecting = true;
+ settings.xhr = $.ajax({
+ url: settings.url,
</ins><span class="cx"> type: 'post',
</span><span class="cx"> timeout: 30000, // throw an error if not completed after 30 sec.
</span><del>- data: send,
</del><ins>+ data: ajaxData,
</ins><span class="cx"> dataType: 'json'
</span><ins>+ }).always( function() {
+ settings.connecting = false;
+ scheduleNextTick();
</ins><span class="cx"> }).done( function( response, textStatus, jqXHR ) {
</span><del>- var new_interval;
</del><ins>+ var newInterval;
</ins><span class="cx">
</span><del>- if ( ! response )
- return errorstate( 'empty' );
</del><ins>+ if ( ! response ) {
+ setErrorState( 'empty' );
+ return;
+ }
</ins><span class="cx">
</span><del>- // Clear error state
- if ( self.hasConnectionError() )
- errorstate();
</del><ins>+ clearErrorState();
</ins><span class="cx">
</span><span class="cx"> if ( response.nonces_expired ) {
</span><del>- $(document).trigger( 'heartbeat-nonces-expired' );
</del><ins>+ $document.trigger( 'heartbeat-nonces-expired' );
</ins><span class="cx"> return;
</span><span class="cx"> }
</span><span class="cx">
</span><span class="cx"> // Change the interval from PHP
</span><span class="cx"> if ( response.heartbeat_interval ) {
</span><del>- new_interval = response.heartbeat_interval;
</del><ins>+ newInterval = response.heartbeat_interval;
</ins><span class="cx"> delete response.heartbeat_interval;
</span><span class="cx"> }
</span><span class="cx">
</span><del>- self.tick( response, textStatus, jqXHR );
</del><ins>+ $document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
</ins><span class="cx">
</span><del>- // do this last, can trigger the next XHR if connection time > 5 sec. and new_interval == 'fast'
- if ( new_interval )
- self.interval.call( self, new_interval );
- }).always( function() {
- connecting = false;
- next();
</del><ins>+ // Do this last, can trigger the next XHR if connection time > 5 sec. and newInterval == 'fast'
+ if ( newInterval ) {
+ setInterval( newInterval );
+ }
</ins><span class="cx"> }).fail( function( jqXHR, textStatus, error ) {
</span><del>- errorstate( textStatus || 'unknown', jqXHR.status );
- self.error( jqXHR, textStatus, error );
</del><ins>+ setErrorState( textStatus || 'unknown', jqXHR.status );
+ $document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
</ins><span class="cx"> });
</span><span class="cx"> }
</span><span class="cx">
</span><del>- function next() {
- var delta = time() - tick, t = interval;
</del><ins>+ /**
+ * Schedule the next connection
+ *
+ * Fires immediately if the connection time is longer than the interval.
+ *
+ * @access private
+ *
+ * @return void
+ */
+ function scheduleNextTick() {
+ var delta = time() - settings.lastTick,
+ interval = settings.mainInterval;
</ins><span class="cx">
</span><del>- if ( ! running )
</del><ins>+ if ( ! settings.isRunning ) {
</ins><span class="cx"> return;
</span><ins>+ }
</ins><span class="cx">
</span><del>- if ( ! hasFocus ) {
- t = 100000; // 100 sec. Post locks expire after 120 sec.
- } else if ( countdown > 0 && tempInterval ) {
- t = tempInterval;
- countdown--;
</del><ins>+ if ( ! settings.hasFocus ) {
+ interval = 120000; // 120 sec. Post locks expire after 150 sec.
+ } else if ( settings.countdown > 0 && settings.tempInterval ) {
+ interval = settings.tempInterval;
+ settings.countdown--;
+
+ if ( settings.countdown < 1 ) {
+ settings.tempInterval = 0;
+ }
</ins><span class="cx"> }
</span><span class="cx">
</span><del>- window.clearTimeout(beat);
</del><ins>+ window.clearTimeout( settings.beatTimer );
</ins><span class="cx">
</span><del>- if ( delta < t ) {
- beat = window.setTimeout(
- function(){
- if ( running )
</del><ins>+ if ( delta < interval ) {
+ settings.beatTimer = window.setTimeout(
+ function() {
</ins><span class="cx"> connect();
</span><span class="cx"> },
</span><del>- t - delta
</del><ins>+ interval - delta
</ins><span class="cx"> );
</span><span class="cx"> } else {
</span><span class="cx"> connect();
</span><span class="cx"> }
</span><span class="cx"> }
</span><span class="cx">
</span><ins>+ /**
+ * Set the internal state when the browser window looses focus
+ *
+ * @access private
+ *
+ * @return void
+ */
</ins><span class="cx"> function blurred() {
</span><del>- window.clearTimeout(winBlurTimeout);
- window.clearTimeout(frameBlurTimeout);
- winBlurTimeout = frameBlurTimeout = 0;
-
- hasFocus = false;
</del><ins>+ clearFocusTimers();
+ settings.hasFocus = false;
</ins><span class="cx"> }
</span><span class="cx">
</span><ins>+ /**
+ * Set the internal state when the browser window is focused
+ *
+ * @access private
+ *
+ * @return void
+ */
</ins><span class="cx"> function focused() {
</span><del>- window.clearTimeout(winBlurTimeout);
- window.clearTimeout(frameBlurTimeout);
- winBlurTimeout = frameBlurTimeout = 0;
</del><ins>+ clearFocusTimers();
+ settings.userActivity = time();
</ins><span class="cx">
</span><del>- isUserActive = time();
-
- if ( hasFocus )
- return;
-
- hasFocus = true;
- window.clearTimeout(beat);
-
- if ( ! connecting )
- next();
</del><ins>+ if ( ! settings.hasFocus ) {
+ settings.hasFocus = true;
+ scheduleNextTick();
+ }
</ins><span class="cx"> }
</span><span class="cx">
</span><del>- function setFrameEvents() {
- $('iframe').each( function( i, frame ){
- if ( ! isLocalFrame( frame ) )
</del><ins>+ /**
+ * Add focus/blur events to all local iframes
+ *
+ * Used to detect when focus is moved from the main window to an iframe
+ *
+ * @access private
+ *
+ * @return void
+ */
+ function setFrameFocusEvents() {
+ $('iframe').each( function( i, frame ) {
+ if ( ! isLocalFrame( frame ) ) {
</ins><span class="cx"> return;
</span><ins>+ }
</ins><span class="cx">
</span><del>- if ( $.data( frame, 'wp-heartbeat-focus' ) )
</del><ins>+ if ( $.data( frame, 'wp-heartbeat-focus' ) ) {
</ins><span class="cx"> return;
</span><ins>+ }
</ins><span class="cx">
</span><span class="cx"> $.data( frame, 'wp-heartbeat-focus', 1 );
</span><span class="cx">
</span><del>- $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function(e) {
</del><ins>+ $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function() {
</ins><span class="cx"> focused();
</span><del>- }).on('blur.wp-heartbeat-focus', function(e) {
- setFrameEvents();
- frameBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
</del><ins>+ }).on('blur.wp-heartbeat-focus', function() {
+ setFrameFocusEvents();
+ // We don't know why 'blur' was fired. Either the user clicked in the main window or outside the browser.
+ // Running blurred() after some timeout lets us cancel it if the user clicked in the main window.
+ settings.frameBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
</ins><span class="cx"> });
</span><span class="cx"> });
</span><span class="cx"> }
</span><span class="cx">
</span><del>- $(window).on( 'blur.wp-heartbeat-focus', function(e) {
- setFrameEvents();
- winBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
- }).on( 'focus.wp-heartbeat-focus', function() {
</del><ins>+ /**
+ * Remove the focus/blur events to all local iframes
+ *
+ * @access private
+ *
+ * @return void
+ */
+ function removeFrameFocusEvents() {
</ins><span class="cx"> $('iframe').each( function( i, frame ) {
</span><del>- if ( !isLocalFrame( frame ) )
</del><ins>+ if ( ! isLocalFrame( frame ) ) {
</ins><span class="cx"> return;
</span><ins>+ }
</ins><span class="cx">
</span><span class="cx"> $.removeData( frame, 'wp-heartbeat-focus' );
</span><span class="cx"> $( frame.contentWindow ).off( '.wp-heartbeat-focus' );
</span><span class="cx"> });
</span><ins>+ }
</ins><span class="cx">
</span><del>- focused();
- });
</del><ins>+ /**
+ * Clear the reset timers for focus/blur events on the window and iframes
+ *
+ * @access private
+ *
+ * @return void
+ */
+ function clearFocusTimers() {
+ window.clearTimeout( settings.winBlurTimer );
+ window.clearTimeout( settings.frameBlurTimer );
+ }
</ins><span class="cx">
</span><ins>+ /**
+ * Runs when the user becomes active after a period of inactivity
+ *
+ * @access private
+ *
+ * @return void
+ */
</ins><span class="cx"> function userIsActive() {
</span><del>- userActiveEvents = false;
- $(document).off( '.wp-heartbeat-active' );
</del><ins>+ settings.userActivityEvents = false;
+ $document.off( '.wp-heartbeat-active' );
+
</ins><span class="cx"> $('iframe').each( function( i, frame ) {
</span><del>- if ( ! isLocalFrame( frame ) )
</del><ins>+ if ( ! isLocalFrame( frame ) ) {
</ins><span class="cx"> return;
</span><ins>+ }
</ins><span class="cx">
</span><span class="cx"> $( frame.contentWindow ).off( '.wp-heartbeat-active' );
</span><span class="cx"> });
</span><span class="lines">@@ -324,101 +493,139 @@
</span><span class="cx"> focused();
</span><span class="cx"> }
</span><span class="cx">
</span><del>- // 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;
</del><ins>+ /**
+ * Check for user activity
+ *
+ * Runs every 30 sec.
+ * Sets '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.
+ *
+ * @access private
+ *
+ * @return void
+ */
+ function checkUserActivity() {
+ var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
</ins><span class="cx">
</span><del>- // Throttle down when no mouse or keyboard activity for 5 min
- if ( lastActive > 300000 && hasFocus )
- blurred();
</del><ins>+ if ( lastActive > 300000 && settings.hasFocus ) {
+ // Throttle down when no mouse or keyboard activity for 5 min
+ blurred();
+ }
</ins><span class="cx">
</span><del>- if ( ! userActiveEvents ) {
- $(document).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
</del><ins>+ if ( ! settings.userActivityEvents ) {
+ $document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
</ins><span class="cx">
</span><span class="cx"> $('iframe').each( function( i, frame ) {
</span><del>- if ( ! isLocalFrame( frame ) )
</del><ins>+ if ( ! isLocalFrame( frame ) ) {
</ins><span class="cx"> return;
</span><ins>+ }
</ins><span class="cx">
</span><span class="cx"> $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
</span><span class="cx"> });
</span><span class="cx">
</span><del>- userActiveEvents = true;
</del><ins>+ settings.userActivityEvents = true;
</ins><span class="cx"> }
</span><span class="cx"> }
</span><span class="cx">
</span><del>- // Check for user activity every 30 seconds.
- window.setInterval( function(){ checkUserActive(); }, 30000 );
- $(document).ready( function() {
- // Start one tick (15 sec) after DOM ready
- running = true;
- tick = time();
- next();
- });
</del><ins>+ // Public methods
</ins><span class="cx">
</span><del>- this.hasFocus = function() {
- return hasFocus;
- };
</del><ins>+ /**
+ * Whether the window (or any local iframe in it) has focus, or the user is active
+ *
+ * @return bool
+ */
+ function hasFocus() {
+ return settings.hasFocus;
+ }
</ins><span class="cx">
</span><span class="cx"> /**
</span><ins>+ * Whether there is a connection error
+ *
+ * @return bool
+ */
+ function hasConnectionError() {
+ return settings.connectionError;
+ }
+
+ /**
+ * Connect asap regardless of 'hasFocus'
+ *
+ * Will not open two concurrent connections. If a connection is in progress,
+ * will connect again immediately after the current connection completes.
+ *
+ * @return void
+ */
+ function connectNow() {
+ settings.lastTick = 0;
+ scheduleNextTick();
+ }
+
+ /**
</ins><span class="cx"> * Get/Set the interval
</span><span class="cx"> *
</span><del>- * When setting to 'fast', the interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
</del><ins>+ * When setting to 'fast' or 5, by default interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
+ * In this case the number of 'ticks' can be passed as second argument.
</ins><span class="cx"> * If the window doesn't have focus, the interval slows down to 2 min.
</span><span class="cx"> *
</span><del>- * @param string speed Interval speed: 'fast' (5sec), 'standard' (15sec) default, 'slow' (60sec)
- * @param string ticks Used with speed = 'fast', how many ticks before the speed reverts back
</del><ins>+ * @param mixed speed Interval: 'fast' or 5, 15, 30, 60
+ * @param string ticks Used with speed = 'fast' or 5, how many ticks before the interval reverts back
</ins><span class="cx"> * @return int Current interval in seconds
</span><span class="cx"> */
</span><del>- this.interval = function( speed, ticks ) {
- var reset, seconds;
- ticks = parseInt( ticks, 10 ) || 30;
- ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
</del><ins>+ function setInterval( speed, ticks ) {
+ var interval, oldInerval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;
</ins><span class="cx">
</span><span class="cx"> if ( speed ) {
</span><span class="cx"> switch ( speed ) {
</span><span class="cx"> case 'fast':
</span><del>- seconds = 5;
- countdown = ticks;
</del><ins>+ case 5:
+ interval = 5000;
</ins><span class="cx"> break;
</span><del>- case 'slow':
- seconds = 60;
- countdown = 0;
</del><ins>+ case 15:
+ interval = 15000;
</ins><span class="cx"> break;
</span><ins>+ case 30:
+ interval = 30000;
+ break;
+ case 60:
+ interval = 60000;
+ break;
</ins><span class="cx"> case 'long-polling':
</span><span class="cx"> // Allow long polling, (experimental)
</span><del>- interval = 0;
</del><ins>+ settings.mainInterval = 0;
</ins><span class="cx"> return 0;
</span><span class="cx"> break;
</span><span class="cx"> default:
</span><del>- seconds = 15;
- countdown = 0;
</del><ins>+ interval = settings.originalInterval;
</ins><span class="cx"> }
</span><span class="cx">
</span><del>- // Reset when the new interval value is lower than the current one
- reset = seconds * 1000 < interval;
</del><ins>+ if ( 5000 === interval ) {
+ ticks = parseInt( ticks, 10 ) || 30;
+ ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
</ins><span class="cx">
</span><del>- if ( countdown > 0 ) {
- tempInterval = seconds * 1000;
</del><ins>+ settings.countdown = ticks;
+ settings.tempInterval = interval;
</ins><span class="cx"> } else {
</span><del>- interval = seconds * 1000;
- tempInterval = 0;
</del><ins>+ settings.countdown = 0;
+ settings.tempInterval = 0;
+ settings.mainInterval = interval;
</ins><span class="cx"> }
</span><span class="cx">
</span><del>- if ( reset )
- next();
</del><ins>+ // Change the next connection time if new interval has been set.
+ // Will connect immediately if the time since the last connection
+ // is greater than the new interval.
+ if ( interval !== oldInerval ) {
+ scheduleNextTick();
+ }
</ins><span class="cx"> }
</span><span class="cx">
</span><del>- if ( ! hasFocus )
- return 120;
</del><ins>+ return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
+ }
</ins><span class="cx">
</span><del>- return tempInterval ? tempInterval / 1000 : interval / 1000;
- };
-
</del><span class="cx"> /**
</span><span class="cx"> * Enqueue data to send with the next XHR
</span><span class="cx"> *
</span><del>- * As the data is sent later, this function doesn't return the XHR response.
</del><ins>+ * As the data is send asynchronously, this function doesn't return the XHR response.
</ins><span class="cx"> * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
</span><span class="cx"> * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
</span><span class="cx"> * // code
</span><span class="lines">@@ -428,19 +635,20 @@
</span><span class="cx"> *
</span><span class="cx"> * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
</span><span class="cx"> * $param mixed data The data to send.
</span><del>- * $param bool dont_overwrite Whether to overwrite existing data in the queue.
</del><ins>+ * $param bool noOverwrite Whether to overwrite existing data in the queue.
</ins><span class="cx"> * $return bool Whether the data was queued or not.
</span><span class="cx"> */
</span><del>- this.enqueue = function( handle, data, dont_overwrite ) {
</del><ins>+ function enqueue( handle, data, noOverwrite ) {
</ins><span class="cx"> if ( handle ) {
</span><del>- if ( dont_overwrite && this.isQueued( handle ) )
</del><ins>+ if ( noOverwrite && this.isQueued( handle ) ) {
</ins><span class="cx"> return false;
</span><ins>+ }
</ins><span class="cx">
</span><del>- queue[handle] = data;
</del><ins>+ settings.queue[handle] = data;
</ins><span class="cx"> return true;
</span><span class="cx"> }
</span><span class="cx"> return false;
</span><del>- };
</del><ins>+ }
</ins><span class="cx">
</span><span class="cx"> /**
</span><span class="cx"> * Check if data with a particular handle is queued
</span><span class="lines">@@ -448,10 +656,11 @@
</span><span class="cx"> * $param string handle The handle for the data
</span><span class="cx"> * $return bool Whether some data is queued with this handle
</span><span class="cx"> */
</span><del>- this.isQueued = function( handle ) {
- if ( handle )
- return queue.hasOwnProperty( handle );
- };
</del><ins>+ function isQueued( handle ) {
+ if ( handle ) {
+ return settings.queue.hasOwnProperty( handle );
+ }
+ }
</ins><span class="cx">
</span><span class="cx"> /**
</span><span class="cx"> * Remove data with a particular handle from the queue
</span><span class="lines">@@ -459,10 +668,11 @@
</span><span class="cx"> * $param string handle The handle for the data
</span><span class="cx"> * $return void
</span><span class="cx"> */
</span><del>- this.dequeue = function( handle ) {
- if ( handle )
- delete queue[handle];
- };
</del><ins>+ function dequeue( handle ) {
+ if ( handle ) {
+ delete settings.queue[handle];
+ }
+ }
</ins><span class="cx">
</span><span class="cx"> /**
</span><span class="cx"> * Get data that was enqueued with a particular handle
</span><span class="lines">@@ -470,21 +680,29 @@
</span><span class="cx"> * $param string handle The handle for the data
</span><span class="cx"> * $return mixed The data or undefined
</span><span class="cx"> */
</span><del>- this.getQueuedItem = function( handle ) {
- if ( handle )
- return this.isQueued( handle ) ? queue[handle] : undefined;
</del><ins>+ function getQueuedItem( handle ) {
+ if ( handle ) {
+ return this.isQueued( handle ) ? settings.queue[handle] : undefined;
+ }
+ }
+
+ initialize();
+
+ // Expose public methods
+ return {
+ hasFocus: hasFocus,
+ connectNow: connectNow,
+ setInterval: setInterval,
+ hasConnectionError: hasConnectionError,
+ enqueue: enqueue,
+ dequeue: dequeue,
+ isQueued: isQueued,
+ getQueuedItem: getQueuedItem
</ins><span class="cx"> };
</span><span class="cx"> };
</span><span class="cx">
</span><del>- $.extend( Heartbeat.prototype, {
- tick: function( data, textStatus, jqXHR ) {
- $(document).trigger( 'heartbeat-tick', [data, textStatus, jqXHR] );
- },
- error: function( jqXHR, textStatus, error ) {
- $(document).trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
- }
- });
</del><ins>+ // Ensure the global `wp` object exists.
+ window.wp = window.wp || {};
+ window.wp.heartbeat = new Heartbeat();
</ins><span class="cx">
</span><del>- wp.heartbeat = new Heartbeat();
-
-}(jQuery));
</del><ins>+}( jQuery, window ));
</ins></span></pre>
</div>
</div>
</body>
</html>