PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 11.2.2
Jetpack – WP Security, Backup, Speed, & Growth v11.2.2
16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 All 502 releases
jetpack / modules / sharedaddy / sharing.js

sharing.js in Jetpack – WP Security, Backup, Speed, & Growth 11.2.2, at modules/sharedaddy/sharing.js

600 lines 17.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /* global WPCOM_sharing_counts */
2
3 // NOTE: This file intentionally does not make use of polyfills or libraries,
4 // including jQuery. Please keep all code as IE11-compatible vanilla ES5, and
5 // ensure everything is inside an IIFE to avoid global namespace pollution.
6 // Code follows WordPress browser support guidelines. For an up to date list,
7 // see https://make.wordpress.org/core/handbook/best-practices/browser-support/
8
9 ( function () {
10 var currentScript = document.currentScript;
11
12 // -------------------------- UTILITY FUNCTIONS -------------------------- //
13
14 // Helper function to load an external script.
15 function loadScript( url ) {
16 var script = document.createElement( 'script' );
17 var prev = currentScript || document.getElementsByTagName( 'script' )[ 0 ];
18 script.setAttribute( 'async', true );
19 script.setAttribute( 'src', url );
20 prev.parentNode.insertBefore( script, prev );
21 }
22
23 // Helper matches function (not a polyfill), compatible with IE 11.
24 function matches( el, sel ) {
25 if ( Element.prototype.matches ) {
26 return el.matches( sel );
27 }
28
29 if ( Element.prototype.msMatchesSelector ) {
30 return el.msMatchesSelector( sel );
31 }
32 }
33
34 // Helper closest parent node function (not a polyfill) based on
35 // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
36 function closest( el, sel ) {
37 if ( el.closest ) {
38 return el.closest( sel );
39 }
40
41 var current = el;
42
43 do {
44 if ( matches( current, sel ) ) {
45 return current;
46 }
47 current = current.parentElement || current.parentNode;
48 } while ( current !== null && current.nodeType === 1 );
49
50 return null;
51 }
52
53 // Helper function to iterate over a NodeList
54 // (since IE 11 doesn't have NodeList.prototype.forEach)
55 function forEachNode( list, fn ) {
56 for ( var i = 0; i < list.length; i++ ) {
57 var node = list[ i ];
58 fn( node, i, list );
59 }
60 }
61
62 // Helper function to remove a node from the DOM.
63 function removeNode( node ) {
64 if ( node && node.parentNode ) {
65 node.parentNode.removeChild( node );
66 }
67 }
68
69 // Helper functions to show/hide a node, and check its status.
70 function hideNode( node ) {
71 if ( node ) {
72 node.style.display = 'none';
73 }
74 }
75
76 function showNode( node ) {
77 if ( node ) {
78 node.style.removeProperty( 'display' );
79 }
80 }
81
82 function isNodeHidden( node ) {
83 return ! node || node.style.display === 'none';
84 }
85
86 // ------------------------------- CLASSES ------------------------------- //
87
88 var PANE_SELECTOR = '.sharing-hidden .inner';
89 var PANE_DATA_ATTR = 'data-sharing-more-button-id';
90
91 // Implements a MoreButton class, which controls the lifecycle and behavior
92 // of a "more" button and its dialog.
93 function MoreButton( buttonEl ) {
94 this.button = buttonEl;
95 this.pane = closest( buttonEl, 'div' ).querySelector( PANE_SELECTOR );
96 this.openedBy = null;
97 this.recentlyOpenedByHover = false;
98
99 MoreButton.instances.push( this );
100 this.pane.setAttribute( PANE_DATA_ATTR, MoreButton.instances.length - 1 );
101
102 this.attachHandlers();
103 }
104
105 // Keep a reference to each instance, so we can get back to it from the DOM.
106 MoreButton.instances = [];
107
108 // Delay time configs.
109 MoreButton.hoverOpenDelay = 200;
110 MoreButton.recentOpenDelay = 400;
111 MoreButton.hoverCloseDelay = 300;
112
113 // Use this to avoid creating new instances for buttons which already have one.
114 MoreButton.instantiateOrReuse = function ( buttonEl ) {
115 var pane = closest( buttonEl, 'div' ).querySelector( PANE_SELECTOR );
116 var paneId = pane && pane.getAttribute( PANE_DATA_ATTR );
117
118 var existingInstance = MoreButton.instances[ paneId ];
119 if ( existingInstance ) {
120 return existingInstance;
121 }
122
123 return new MoreButton( buttonEl );
124 };
125
126 // Retrieve a button instance from the pane DOM element.
127 MoreButton.getButtonInstanceFromPane = function ( paneEl ) {
128 var paneId = paneEl && paneEl.getAttribute( PANE_DATA_ATTR );
129 return MoreButton.instances[ paneId ];
130 };
131
132 // Close all open More Button dialogs.
133 MoreButton.closeAll = function () {
134 for ( var i = 0; i < MoreButton.instances.length; i++ ) {
135 MoreButton.instances[ i ].close();
136 }
137 };
138
139 MoreButton.prototype.open = function () {
140 var offset;
141 var offsetParent;
142 var parentOffset = [ 0, 0 ];
143
144 function getOffsets( el ) {
145 var rect = el.getBoundingClientRect();
146 return [
147 rect.left + ( window.scrollX || window.pageXOffset || 0 ),
148 rect.top + ( window.scrollY || window.pageYOffset || 0 ),
149 ];
150 }
151
152 function getStyleValue( el, prop ) {
153 return parseInt( getComputedStyle( el ).getPropertyValue( prop ) || 0 );
154 }
155
156 offset = getOffsets( this.button );
157 offsetParent = this.button.offsetParent || document.documentElement;
158
159 while (
160 offsetParent &&
161 ( offsetParent === document.body || offsetParent === document.documentElement ) &&
162 getComputedStyle( offsetParent ).getPropertyValue( 'position' ) === 'static'
163 ) {
164 offsetParent = offsetParent.parentNode;
165 }
166
167 if ( offsetParent && offsetParent !== this.button && offsetParent.nodeType === 1 ) {
168 parentOffset = getOffsets( offsetParent );
169 parentOffset = [
170 parentOffset[ 0 ] + getStyleValue( offsetParent, 'border-left-width' ),
171 parentOffset[ 1 ] + getStyleValue( offsetParent, 'border-top-width' ),
172 ];
173 }
174
175 var positionLeft =
176 offset[ 0 ] - parentOffset[ 0 ] - getStyleValue( this.button, 'margin-left' );
177 var positionTop = offset[ 1 ] - parentOffset[ 1 ] - getStyleValue( this.button, 'margin-top' );
178
179 this.pane.style.left = positionLeft + 'px';
180 this.pane.style.top = positionTop + this.button.offsetHeight + 3 + 'px';
181
182 showNode( this.pane );
183 };
184
185 MoreButton.prototype.close = function () {
186 hideNode( this.pane );
187 this.openedBy = null;
188 };
189
190 MoreButton.prototype.toggle = function () {
191 if ( isNodeHidden( this.pane ) ) {
192 this.open();
193 } else {
194 this.close();
195 }
196 };
197
198 MoreButton.prototype.resetCloseTimer = function () {
199 clearTimeout( this.closeTimer );
200 this.closeTimer = setTimeout( this.close.bind( this ), MoreButton.hoverCloseDelay );
201 };
202
203 MoreButton.prototype.attachHandlers = function () {
204 this.buttonClick = function ( event ) {
205 event.preventDefault();
206 event.stopPropagation();
207
208 this.openedBy = 'click';
209 clearTimeout( this.openTimer );
210 clearTimeout( this.closeTimer );
211
212 if ( this.recentlyOpenedByHover ) {
213 this.recentlyOpenedByHover = false;
214 clearTimeout( this.hoverOpenTimer );
215 this.open();
216 } else {
217 this.toggle();
218 }
219 }.bind( this );
220
221 this.buttonEnter = function () {
222 if ( ! this.openedBy ) {
223 this.openTimer = setTimeout(
224 function () {
225 this.open();
226 this.openedBy = 'hover';
227 this.recentlyOpenedByHover = true;
228 this.hoverOpenTimer = setTimeout(
229 function () {
230 this.recentlyOpenedByHover = false;
231 }.bind( this ),
232 MoreButton.recentOpenDelay
233 );
234 }.bind( this ),
235 MoreButton.hoverOpenDelay
236 );
237 }
238 clearTimeout( this.closeTimer );
239 }.bind( this );
240
241 this.buttonLeave = function () {
242 if ( this.openedBy === 'hover' ) {
243 this.resetCloseTimer();
244 }
245 clearTimeout( this.openTimer );
246 }.bind( this );
247
248 this.paneEnter = function () {
249 clearTimeout( this.closeTimer );
250 }.bind( this );
251
252 this.paneLeave = function () {
253 if ( this.openedBy === 'hover' ) {
254 this.resetCloseTimer();
255 }
256 }.bind( this );
257
258 this.documentClick = function () {
259 this.close();
260 }.bind( this );
261
262 this.button.addEventListener( 'click', this.buttonClick );
263 document.addEventListener( 'click', this.documentClick );
264
265 if ( document.ontouchstart === undefined ) {
266 // Non-touchscreen device: use hover/mouseout with delay
267 this.button.addEventListener( 'mouseenter', this.buttonEnter );
268 this.button.addEventListener( 'mouseleave', this.buttonLeave );
269 this.pane.addEventListener( 'mouseenter', this.paneEnter );
270 this.pane.addEventListener( 'mouseleave', this.paneLeave );
271 }
272 };
273
274 // ---------------------------- SHARE COUNTS ---------------------------- //
275
276 if ( window.sharing_js_options && window.sharing_js_options.counts ) {
277 var WPCOMSharing = {
278 done_urls: [],
279 get_counts: function () {
280 var url, requests, id, service, service_request;
281
282 if ( 'undefined' === typeof WPCOM_sharing_counts ) {
283 return;
284 }
285
286 for ( url in WPCOM_sharing_counts ) {
287 id = WPCOM_sharing_counts[ url ];
288
289 if ( 'undefined' !== typeof WPCOMSharing.done_urls[ id ] ) {
290 continue;
291 }
292
293 requests = {
294 // Pinterest handles share counts for both http and https
295 pinterest: [
296 window.location.protocol +
297 '//api.pinterest.com/v1/urls/count.json?callback=WPCOMSharing.update_pinterest_count&url=' +
298 encodeURIComponent( url ),
299 ],
300 };
301
302 for ( service in requests ) {
303 if ( ! document.querySelector( 'a[data-shared=sharing-' + service + '-' + id + ']' ) ) {
304 continue;
305 }
306
307 while ( ( service_request = requests[ service ].pop() ) ) {
308 loadScript( service_request );
309 }
310
311 if ( window.sharing_js_options.is_stats_active ) {
312 WPCOMSharing.bump_sharing_count_stat( service );
313 }
314 }
315
316 WPCOMSharing.done_urls[ id ] = true;
317 }
318 },
319 update_pinterest_count: function ( data ) {
320 if ( 'undefined' !== typeof data.count && data.count * 1 > 0 ) {
321 WPCOMSharing.inject_share_count(
322 'sharing-pinterest-' + WPCOM_sharing_counts[ data.url ],
323 data.count
324 );
325 }
326 },
327 inject_share_count: function ( id, count ) {
328 forEachNode(
329 document.querySelectorAll( 'a[data-shared=' + id + '] > span' ),
330 function ( span ) {
331 var countNode = span.querySelector( '.share-count' );
332 removeNode( countNode );
333 var newNode = document.createElement( 'span' );
334 newNode.className = 'share-count';
335 newNode.textContent = WPCOMSharing.format_count( count );
336 span.appendChild( newNode );
337 }
338 );
339 },
340 format_count: function ( count ) {
341 if ( count < 1000 ) {
342 return count;
343 }
344 if ( count >= 1000 && count < 10000 ) {
345 return String( count ).substring( 0, 1 ) + 'K+';
346 }
347 return '10K+';
348 },
349 bump_sharing_count_stat: function ( service ) {
350 new Image().src =
351 document.location.protocol +
352 '//pixel.wp.com/g.gif?v=wpcom-no-pv&x_sharing-count-request=' +
353 service +
354 '&r=' +
355 Math.random();
356 },
357 };
358 window.WPCOMSharing = WPCOMSharing;
359 }
360
361 // ------------------------ BUTTON FUNCTIONALITY ------------------------ //
362 function isUrlForCurrentHost( url ) {
363 var currentDomain = window.location.protocol + '//' + window.location.hostname + '/';
364
365 return String( url ).indexOf( currentDomain ) === 0;
366 }
367
368 function getEncodedFormFieldForSubmit( name, value ) {
369 // Encode the key and value into a URI-compatible string.
370 var encoded = encodeURIComponent( name ) + '=' + encodeURIComponent( value );
371
372 // In x-www-form-urlencoded, spaces should be `+`, not `%20`.
373 return encoded.replace( /%20/g, '+' );
374 }
375
376 function trackButtonClick( button ) {
377 var clickCount = getClickCountForButton( button );
378
379 setClickCountForButton( button, clickCount + 1 );
380 }
381
382 function setClickCountForButton( button, clickCount ) {
383 button.setAttribute( 'jetpack-share-click-count', clickCount );
384 }
385
386 function getClickCountForButton( button ) {
387 var currentClickCount = button.getAttribute( 'jetpack-share-click-count' );
388 if ( currentClickCount === null ) {
389 return 0;
390 }
391
392 return parseInt( currentClickCount, 10 );
393 }
394
395 function showEmailShareError( emailShareButton, sdUlGroup ) {
396 var sdContent = sdUlGroup.parentElement;
397 if ( ! sdContent.classList.contains( 'sd-content' ) ) {
398 return;
399 }
400
401 forEachNode( sdContent.querySelectorAll( '.share-email-error' ), function ( shareEmailError ) {
402 shareEmailError.parentElement.removeChild( shareEmailError );
403 } );
404
405 var newShareEmailError = document.createElement( 'div' );
406 newShareEmailError.className = 'share-email-error';
407
408 var newShareEmailErrorTitle = document.createElement( 'h6' );
409 newShareEmailErrorTitle.className = 'share-email-error-title';
410 newShareEmailErrorTitle.innerText = emailShareButton.getAttribute(
411 'data-email-share-error-title'
412 );
413 newShareEmailError.appendChild( newShareEmailErrorTitle );
414
415 var newShareEmailErrorText = document.createElement( 'p' );
416 newShareEmailErrorText.className = 'share-email-error-text';
417 newShareEmailErrorText.innerText = emailShareButton.getAttribute(
418 'data-email-share-error-text'
419 );
420 newShareEmailError.appendChild( newShareEmailErrorText );
421
422 sdContent.appendChild( newShareEmailError );
423 }
424
425 function recordEmailShareClick( emailShareTrackerUrl, emailShareNonce ) {
426 var request = new XMLHttpRequest();
427 request.open( 'POST', emailShareTrackerUrl, true );
428 request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' );
429 request.setRequestHeader( 'x-requested-with', 'XMLHttpRequest' );
430
431 request.send( getEncodedFormFieldForSubmit( 'email-share-nonce', emailShareNonce ) );
432 }
433
434 // Sharing initialization.
435 // Will run immediately or on `DOMContentLoaded`, depending on current page status.
436 function init() {
437 WPCOMSharing_do();
438 }
439 if ( document.readyState !== 'loading' ) {
440 init();
441 } else {
442 document.addEventListener( 'DOMContentLoaded', init );
443 }
444
445 // Set up sharing again whenever a new post loads, to pick up any new buttons.
446 document.body.addEventListener( 'is.post-load', WPCOMSharing_do );
447
448 // Set up sharing, updating counts and adding all button functionality.
449 function WPCOMSharing_do() {
450 if ( window.WPCOMSharing ) {
451 window.WPCOMSharing.get_counts();
452 }
453
454 forEachNode( document.querySelectorAll( '.sharedaddy a' ), function ( anchor ) {
455 var href = anchor.getAttribute( 'href' );
456 if ( href && href.indexOf( 'share=' ) !== -1 && href.indexOf( '&nb=1' ) === -1 ) {
457 anchor.setAttribute( 'href', href + '&nb=1' );
458 }
459 } );
460
461 // Show hidden buttons
462
463 // Touchscreen device: use click.
464 // Non-touchscreen device: use click if not already appearing due to a hover event
465
466 forEachNode(
467 document.querySelectorAll( '.sharedaddy a.sharing-anchor' ),
468 function ( buttonEl ) {
469 MoreButton.instantiateOrReuse( buttonEl );
470 }
471 );
472
473 if ( document.ontouchstart !== undefined ) {
474 document.body.classList.add( 'jp-sharing-input-touch' );
475 }
476
477 // Add click functionality
478 forEachNode( document.querySelectorAll( '.sharedaddy ul' ), function ( group ) {
479 if ( group.getAttribute( 'data-sharing-events-added' ) === 'true' ) {
480 return;
481 }
482 group.setAttribute( 'data-sharing-events-added', 'true' );
483
484 var printUrl = function ( uniqueId, urlToPrint ) {
485 var iframe = document.createElement( 'iframe' );
486 iframe.setAttribute(
487 'style',
488 'position:fixed; top:100; left:100; height:1px; width:1px; border:none;'
489 );
490 iframe.setAttribute( 'id', 'printFrame-' + uniqueId );
491 iframe.setAttribute( 'name', iframe.getAttribute( 'id' ) );
492 iframe.setAttribute( 'src', urlToPrint );
493 iframe.setAttribute(
494 'onload',
495 'frames["printFrame-' +
496 uniqueId +
497 '"].focus();frames["printFrame-' +
498 uniqueId +
499 '"].print();'
500 );
501 document.body.appendChild( iframe );
502 };
503
504 // Print button
505 forEachNode( group.querySelectorAll( 'a.share-print' ), function ( printButton ) {
506 printButton.addEventListener( 'click', function ( event ) {
507 event.preventDefault();
508 event.stopPropagation();
509
510 var ref = printButton.getAttribute( 'href' ) || '';
511 var doPrint = function () {
512 if ( ref.indexOf( '#print' ) === -1 ) {
513 var uid = new Date().getTime();
514 printUrl( uid, ref );
515 } else {
516 window.print();
517 }
518 };
519
520 // Is the button in a dropdown?
521 var pane = closest( printButton, PANE_SELECTOR );
522 if ( pane ) {
523 var moreButton = MoreButton.getButtonInstanceFromPane( pane );
524 if ( moreButton ) {
525 moreButton.close();
526 doPrint();
527 }
528 } else {
529 doPrint();
530 }
531 } );
532 } );
533
534 // Press This button
535 forEachNode( group.querySelectorAll( 'a.share-press-this' ), function ( pressThisButton ) {
536 pressThisButton.addEventListener( 'click', function ( event ) {
537 event.preventDefault();
538 event.stopPropagation();
539
540 var s = '';
541
542 if ( window.getSelection ) {
543 s = window.getSelection();
544 } else if ( document.getSelection ) {
545 s = document.getSelection();
546 } else if ( document.selection ) {
547 s = document.selection.createRange().text;
548 }
549
550 if ( s ) {
551 var href = pressThisButton.getAttribute( 'href' );
552 pressThisButton.setAttribute( 'href', href + '&sel=' + encodeURI( s ) );
553 }
554
555 if (
556 ! window.open(
557 pressThisButton.getAttribute( 'href' ),
558 't',
559 'toolbar=0,resizable=1,scrollbars=1,status=1,width=720,height=570'
560 )
561 ) {
562 document.location.href = pressThisButton.getAttribute( 'href' );
563 }
564 } );
565 } );
566
567 // Email button
568 forEachNode( group.querySelectorAll( 'a.share-email' ), function ( emailButton ) {
569 setClickCountForButton( emailButton, 0 );
570
571 var emailShareNonce = emailButton.getAttribute( 'data-email-share-nonce' );
572 var emailShareTrackerUrl = emailButton.getAttribute( 'data-email-share-track-url' );
573
574 if (
575 emailShareNonce &&
576 emailShareTrackerUrl &&
577 isUrlForCurrentHost( emailShareTrackerUrl )
578 ) {
579 emailButton.addEventListener( 'click', function () {
580 trackButtonClick( emailButton );
581
582 if ( getClickCountForButton( emailButton ) > 2 ) {
583 showEmailShareError( emailButton, group );
584 }
585
586 recordEmailShareClick( emailShareTrackerUrl, emailShareNonce );
587 } );
588 }
589 } );
590 } );
591
592 forEachNode(
593 document.querySelectorAll( 'li.share-email, li.share-custom a.sharing-anchor' ),
594 function ( node ) {
595 node.classList.add( 'share-service-visible' );
596 }
597 );
598 }
599 } )();
600