Keine Beschreibung

jetpack-carousel.js 52KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. /* global wpcom, jetpackCarouselStrings, DocumentTouch */
  2. ( function () {
  3. 'use strict';
  4. var swiper;
  5. /////////////////////////////////////
  6. // Utility functions
  7. /////////////////////////////////////
  8. var util = ( function () {
  9. var noop = function () {};
  10. function texturize( text ) {
  11. // Ensure we get a string.
  12. text = text + '';
  13. text = text.replace( /'/g, '’' ).replace( /'/g, '’' );
  14. text = text
  15. .replace( /"/g, '”' )
  16. .replace( /"/g, '”' )
  17. .replace( /"/g, '”' )
  18. .replace( /[\u201D]/g, '”' );
  19. // Untexturize allowed HTML tags params double-quotes.
  20. text = text.replace( /([\w]+)=&#[\d]+;(.+?)&#[\d]+;/g, '$1="$2"' );
  21. return text.trim();
  22. }
  23. function applyReplacements( text, replacements ) {
  24. if ( ! text ) {
  25. return;
  26. }
  27. if ( ! replacements ) {
  28. return text;
  29. }
  30. return text.replace( /{(\d+)}/g, function ( match, number ) {
  31. return typeof replacements[ number ] !== 'undefined' ? replacements[ number ] : match;
  32. } );
  33. }
  34. function getBackgroundImage( imgEl ) {
  35. var canvas = document.createElement( 'canvas' ),
  36. context = canvas.getContext && canvas.getContext( '2d' );
  37. if ( ! imgEl ) {
  38. return;
  39. }
  40. context.filter = 'blur(20px) ';
  41. context.drawImage( imgEl, 0, 0 );
  42. var url = canvas.toDataURL( 'image/png' );
  43. canvas = null;
  44. return url;
  45. }
  46. return {
  47. noop: noop,
  48. texturize: texturize,
  49. applyReplacements: applyReplacements,
  50. getBackgroundImage: getBackgroundImage,
  51. };
  52. } )();
  53. /////////////////////////////////////
  54. // DOM-related utility functions
  55. /////////////////////////////////////
  56. var domUtil = ( function () {
  57. // Helper matches function (not a polyfill), compatible with IE 11.
  58. function matches( el, sel ) {
  59. if ( Element.prototype.matches ) {
  60. return el.matches( sel );
  61. }
  62. if ( Element.prototype.msMatchesSelector ) {
  63. return el.msMatchesSelector( sel );
  64. }
  65. }
  66. // Helper closest parent node function (not a polyfill) based on
  67. // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
  68. function closest( el, sel ) {
  69. if ( el.closest ) {
  70. return el.closest( sel );
  71. }
  72. var current = el;
  73. do {
  74. if ( matches( current, sel ) ) {
  75. return current;
  76. }
  77. current = current.parentElement || current.parentNode;
  78. } while ( current !== null && current.nodeType === 1 );
  79. return null;
  80. }
  81. function hide( el ) {
  82. if ( el ) {
  83. el.style.display = 'none';
  84. }
  85. }
  86. function show( el ) {
  87. if ( el ) {
  88. // Everything we show and hide in Carousel is currently a block,
  89. // so we can make this really straightforward.
  90. el.style.display = 'block';
  91. }
  92. }
  93. function fade( el, start, end, callback ) {
  94. if ( ! el ) {
  95. return callback();
  96. }
  97. // Prepare for transition.
  98. // Ensure the item is in the render tree, in its initial state.
  99. el.style.removeProperty( 'display' );
  100. el.style.opacity = start;
  101. el.style.transition = 'opacity 0.2s';
  102. el.style.pointerEvents = 'none';
  103. var finished = function ( e ) {
  104. if ( e.target === el && e.propertyName === 'opacity' ) {
  105. el.style.removeProperty( 'transition' );
  106. el.style.removeProperty( 'opacity' );
  107. el.style.removeProperty( 'pointer-events' );
  108. el.removeEventListener( 'transitionend', finished );
  109. el.removeEventListener( 'transitioncancel', finished );
  110. callback();
  111. }
  112. };
  113. requestAnimationFrame( function () {
  114. // Double rAF for browser compatibility.
  115. requestAnimationFrame( function () {
  116. el.addEventListener( 'transitionend', finished );
  117. el.addEventListener( 'transitioncancel', finished );
  118. // Trigger transition.
  119. el.style.opacity = end;
  120. } );
  121. } );
  122. }
  123. function fadeIn( el, callback ) {
  124. callback = callback || util.noop;
  125. fade( el, '0', '1', callback );
  126. }
  127. function fadeOut( el, callback ) {
  128. callback = callback || util.noop;
  129. fade( el, '1', '0', function () {
  130. if ( el ) {
  131. el.style.display = 'none';
  132. }
  133. callback();
  134. } );
  135. }
  136. function emitEvent( el, type, detail ) {
  137. var e;
  138. try {
  139. e = new CustomEvent( type, {
  140. bubbles: true,
  141. cancelable: true,
  142. detail: detail || null,
  143. } );
  144. } catch ( err ) {
  145. e = document.createEvent( 'CustomEvent' );
  146. e.initCustomEvent( type, true, true, detail || null );
  147. }
  148. el.dispatchEvent( e );
  149. }
  150. // From: https://easings.net/#easeInOutQuad
  151. function easeInOutQuad( num ) {
  152. return num < 0.5 ? 2 * num * num : 1 - Math.pow( -2 * num + 2, 2 ) / 2;
  153. }
  154. function getFooterClearance( container ) {
  155. var footer = container.querySelector( '.jp-carousel-info-footer' );
  156. var infoArea = container.querySelector( '.jp-carousel-info-extra' );
  157. var contentArea = container.querySelector( '.jp-carousel-info-content-wrapper' );
  158. if ( footer && infoArea && contentArea ) {
  159. var styles = window.getComputedStyle( infoArea );
  160. var padding = parseInt( styles.paddingTop, 10 ) + parseInt( styles.paddingBottom, 10 );
  161. padding = isNaN( padding ) ? 0 : padding;
  162. return contentArea.offsetHeight + footer.offsetHeight + padding;
  163. }
  164. return 0;
  165. }
  166. function isTouch() {
  167. return (
  168. 'ontouchstart' in window || ( window.DocumentTouch && document instanceof DocumentTouch )
  169. );
  170. }
  171. function scrollToElement( el, container, callback ) {
  172. if ( ! el || ! container ) {
  173. if ( callback ) {
  174. return callback();
  175. }
  176. return;
  177. }
  178. // For iOS Safari compatibility, use JS to set the minimum height.
  179. var infoArea = container.querySelector( '.jp-carousel-info-extra' );
  180. if ( infoArea ) {
  181. // 64px is the same height as `.jp-carousel-info-footer` in the CSS.
  182. infoArea.style.minHeight = window.innerHeight - 64 + 'px';
  183. }
  184. var isScrolling = true;
  185. var startTime = Date.now();
  186. var duration = 300;
  187. var originalPosition = container.scrollTop;
  188. var targetPosition = Math.max(
  189. 0,
  190. el.offsetTop - Math.max( 0, window.innerHeight - getFooterClearance( container ) )
  191. );
  192. var distance = targetPosition - container.scrollTop;
  193. distance = Math.min( distance, container.scrollHeight - window.innerHeight );
  194. function stopScroll() {
  195. isScrolling = false;
  196. }
  197. function runScroll() {
  198. var now = Date.now();
  199. var progress = easeInOutQuad( ( now - startTime ) / duration );
  200. progress = progress > 1 ? 1 : progress;
  201. var newVal = progress * distance;
  202. container.scrollTop = originalPosition + newVal;
  203. if ( now <= startTime + duration && isScrolling ) {
  204. return requestAnimationFrame( runScroll );
  205. }
  206. if ( callback ) {
  207. callback();
  208. }
  209. if ( infoArea ) {
  210. infoArea.style.minHeight = '';
  211. }
  212. isScrolling = false;
  213. container.removeEventListener( 'wheel', stopScroll );
  214. }
  215. // Allow scroll to be cancelled by user interaction.
  216. container.addEventListener( 'wheel', stopScroll );
  217. runScroll();
  218. }
  219. function getJSONAttribute( el, attr ) {
  220. if ( ! el || ! el.hasAttribute( attr ) ) {
  221. return undefined;
  222. }
  223. try {
  224. return JSON.parse( el.getAttribute( attr ) );
  225. } catch ( e ) {
  226. return undefined;
  227. }
  228. }
  229. function convertToPlainText( html ) {
  230. var dummy = document.createElement( 'div' );
  231. dummy.textContent = html;
  232. return dummy.innerHTML;
  233. }
  234. function stripHTML( text ) {
  235. return text.replace( /<[^>]*>?/gm, '' );
  236. }
  237. return {
  238. closest: closest,
  239. matches: matches,
  240. hide: hide,
  241. show: show,
  242. fadeIn: fadeIn,
  243. fadeOut: fadeOut,
  244. scrollToElement: scrollToElement,
  245. getJSONAttribute: getJSONAttribute,
  246. convertToPlainText: convertToPlainText,
  247. stripHTML: stripHTML,
  248. emitEvent: emitEvent,
  249. isTouch: isTouch,
  250. };
  251. } )();
  252. /////////////////////////////////////
  253. // Carousel implementation
  254. /////////////////////////////////////
  255. function init() {
  256. var commentInterval;
  257. var screenPadding;
  258. var originalOverflow;
  259. var originalHOverflow;
  260. var scrollPos;
  261. var lastKnownLocationHash = '';
  262. var isUserTyping = false;
  263. var gallerySelector =
  264. 'div.gallery, div.tiled-gallery, ul.wp-block-gallery, ul.blocks-gallery-grid, ' +
  265. 'figure.wp-block-gallery.has-nested-images, div.wp-block-jetpack-tiled-gallery, a.single-image-gallery';
  266. // Selector for items within a gallery or tiled gallery.
  267. var galleryItemSelector =
  268. '.gallery-item, .tiled-gallery-item, .blocks-gallery-item, ' + ' .tiled-gallery__item';
  269. // Selector for all items including single images.
  270. var itemSelector = galleryItemSelector + ', .wp-block-image';
  271. var carousel = {};
  272. var stat =
  273. typeof wpcom !== 'undefined' && wpcom.carousel && wpcom.carousel.stat
  274. ? wpcom.carousel.stat
  275. : util.noop;
  276. var pageview =
  277. typeof wpcom !== 'undefined' && wpcom.carousel && wpcom.carousel.pageview
  278. ? wpcom.carousel.pageview
  279. : util.noop;
  280. function handleKeyboardEvent( e ) {
  281. if ( ! isUserTyping ) {
  282. switch ( e.which ) {
  283. case 38: // up
  284. e.preventDefault();
  285. carousel.overlay.scrollTop -= 100;
  286. break;
  287. case 40: // down
  288. e.preventDefault();
  289. carousel.overlay.scrollTop += 100;
  290. break;
  291. case 39: // right
  292. e.preventDefault();
  293. swiper.slideNext();
  294. break;
  295. case 37: // left
  296. case 8: // backspace
  297. e.preventDefault();
  298. swiper.slidePrev();
  299. break;
  300. case 27: // escape
  301. e.preventDefault();
  302. closeCarousel();
  303. break;
  304. default:
  305. break;
  306. }
  307. }
  308. }
  309. function disableKeyboardNavigation() {
  310. isUserTyping = true;
  311. }
  312. function enableKeyboardNavigation() {
  313. isUserTyping = false;
  314. }
  315. function calculatePadding() {
  316. var baseScreenPadding = 110;
  317. screenPadding = baseScreenPadding;
  318. if ( window.innerWidth <= 760 ) {
  319. screenPadding = Math.round( ( window.innerWidth / 760 ) * baseScreenPadding );
  320. if ( screenPadding < 40 && domUtil.isTouch() ) {
  321. screenPadding = 0;
  322. }
  323. }
  324. }
  325. function initializeCarousel() {
  326. if ( ! carousel.overlay ) {
  327. carousel.overlay = document.querySelector( '.jp-carousel-overlay' );
  328. carousel.container = carousel.overlay.querySelector( '.jp-carousel-wrap' );
  329. carousel.gallery = carousel.container.querySelector( '.jp-carousel' );
  330. carousel.info = carousel.overlay.querySelector( '.jp-carousel-info' );
  331. carousel.caption = carousel.info.querySelector( '.jp-carousel-caption' );
  332. carousel.commentField = carousel.overlay.querySelector(
  333. '#jp-carousel-comment-form-comment-field'
  334. );
  335. carousel.emailField = carousel.overlay.querySelector(
  336. '#jp-carousel-comment-form-email-field'
  337. );
  338. carousel.authorField = carousel.overlay.querySelector(
  339. '#jp-carousel-comment-form-author-field'
  340. );
  341. carousel.urlField = carousel.overlay.querySelector( '#jp-carousel-comment-form-url-field' );
  342. calculatePadding();
  343. [
  344. carousel.commentField,
  345. carousel.emailField,
  346. carousel.authorField,
  347. carousel.urlField,
  348. ].forEach( function ( field ) {
  349. if ( field ) {
  350. field.addEventListener( 'focus', disableKeyboardNavigation );
  351. field.addEventListener( 'blur', enableKeyboardNavigation );
  352. }
  353. } );
  354. carousel.overlay.addEventListener( 'click', function ( e ) {
  355. var target = e.target;
  356. var isTargetCloseHint = !! domUtil.closest( target, '.jp-carousel-close-hint' );
  357. var isSmallScreen = !! window.matchMedia( '(max-device-width: 760px)' ).matches;
  358. if ( target === carousel.overlay ) {
  359. if ( isSmallScreen ) {
  360. return;
  361. } else {
  362. closeCarousel();
  363. }
  364. } else if ( isTargetCloseHint ) {
  365. closeCarousel();
  366. } else if ( target.classList.contains( 'jp-carousel-image-download' ) ) {
  367. stat( 'download_original_click' );
  368. } else if ( target.classList.contains( 'jp-carousel-comment-login' ) ) {
  369. handleCommentLoginClick( e );
  370. } else if ( domUtil.closest( target, '#jp-carousel-comment-form-container' ) ) {
  371. handleCommentFormClick( e );
  372. } else if (
  373. domUtil.closest( target, '.jp-carousel-photo-icons-container' ) ||
  374. target.classList.contains( 'jp-carousel-photo-title' )
  375. ) {
  376. handleFooterElementClick( e );
  377. } else if ( ! domUtil.closest( target, '.jp-carousel-info' ) ) {
  378. return;
  379. }
  380. } );
  381. window.addEventListener( 'keydown', handleKeyboardEvent );
  382. carousel.overlay.addEventListener( 'jp_carousel.afterOpen', function () {
  383. enableKeyboardNavigation();
  384. // Don't show navigation if there's only one image.
  385. if ( carousel.slides.length <= 1 ) {
  386. return;
  387. }
  388. // Show dot pagination if slide count is <= 5, otherwise show n/total.
  389. if ( carousel.slides.length <= 5 ) {
  390. domUtil.show( carousel.info.querySelector( '.jp-swiper-pagination' ) );
  391. } else {
  392. domUtil.show( carousel.info.querySelector( '.jp-carousel-pagination' ) );
  393. }
  394. } );
  395. carousel.overlay.addEventListener( 'jp_carousel.beforeClose', function () {
  396. disableKeyboardNavigation();
  397. // Fixes some themes where closing carousel brings view back to top.
  398. document.documentElement.style.removeProperty( 'height' );
  399. // If we disable the swiper (because there's only one image)
  400. // we have to re-enable it here again as Swiper doesn't, for some reason,
  401. // show the navigation buttons again after reinitialization.
  402. if ( swiper ) {
  403. swiper.enable();
  404. }
  405. // Hide pagination.
  406. domUtil.hide( carousel.info.querySelector( '.jp-swiper-pagination' ) );
  407. domUtil.hide( carousel.info.querySelector( '.jp-carousel-pagination' ) );
  408. } );
  409. carousel.overlay.addEventListener( 'jp_carousel.afterClose', function () {
  410. // don't force the browser back when the carousel closes.
  411. if ( window.history.pushState ) {
  412. history.pushState(
  413. '',
  414. document.title,
  415. window.location.pathname + window.location.search
  416. );
  417. } else {
  418. window.location.href = '';
  419. }
  420. lastKnownLocationHash = '';
  421. carousel.isOpen = false;
  422. } );
  423. // Prevent native browser zooming
  424. carousel.overlay.addEventListener( 'touchstart', function ( e ) {
  425. if ( e.touches.length > 1 ) {
  426. e.preventDefault();
  427. }
  428. } );
  429. }
  430. }
  431. function handleCommentLoginClick() {
  432. var slide = carousel.currentSlide;
  433. var attachmentId = slide ? slide.attrs.attachmentId : '0';
  434. window.location.href = jetpackCarouselStrings.login_url + '%23jp-carousel-' + attachmentId;
  435. }
  436. function updatePostResults( msg, isSuccess ) {
  437. var results = carousel.overlay.querySelector( '#jp-carousel-comment-post-results' );
  438. var elClass = 'jp-carousel-comment-post-' + ( isSuccess ? 'success' : 'error' );
  439. results.innerHTML = '<span class="' + elClass + '">' + msg + '</span>';
  440. domUtil.hide( carousel.overlay.querySelector( '#jp-carousel-comment-form-spinner' ) );
  441. carousel.overlay
  442. .querySelector( '#jp-carousel-comment-form' )
  443. .classList.remove( 'jp-carousel-is-disabled' );
  444. domUtil.show( results );
  445. }
  446. function handleCommentFormClick( e ) {
  447. var target = e.target;
  448. var data = domUtil.getJSONAttribute( carousel.container, 'data-carousel-extra' ) || {};
  449. var attachmentId = carousel.currentSlide.attrs.attachmentId;
  450. var wrapper = document.querySelector( '#jp-carousel-comment-form-submit-and-info-wrapper' );
  451. var spinner = document.querySelector( '#jp-carousel-comment-form-spinner' );
  452. var submit = document.querySelector( '#jp-carousel-comment-form-button-submit' );
  453. var form = document.querySelector( '#jp-carousel-comment-form' );
  454. if (
  455. carousel.commentField &&
  456. carousel.commentField.getAttribute( 'id' ) === target.getAttribute( 'id' )
  457. ) {
  458. // For first page load
  459. disableKeyboardNavigation();
  460. domUtil.show( wrapper );
  461. } else if ( domUtil.matches( target, 'input[type="submit"]' ) ) {
  462. e.preventDefault();
  463. e.stopPropagation();
  464. domUtil.show( spinner );
  465. form.classList.add( 'jp-carousel-is-disabled' );
  466. var ajaxData = {
  467. action: 'post_attachment_comment',
  468. nonce: jetpackCarouselStrings.nonce,
  469. blog_id: data.blog_id,
  470. id: attachmentId,
  471. comment: carousel.commentField.value,
  472. };
  473. if ( ! ajaxData.comment.length ) {
  474. updatePostResults( jetpackCarouselStrings.no_comment_text, false );
  475. return;
  476. }
  477. if ( Number( jetpackCarouselStrings.is_logged_in ) !== 1 ) {
  478. ajaxData.email = carousel.emailField.value;
  479. ajaxData.author = carousel.authorField.value;
  480. ajaxData.url = carousel.urlField.value;
  481. if ( Number( jetpackCarouselStrings.require_name_email ) === 1 ) {
  482. if ( ! ajaxData.email.length || ! ajaxData.email.match( '@' ) ) {
  483. updatePostResults( jetpackCarouselStrings.no_comment_email, false );
  484. return;
  485. } else if ( ! ajaxData.author.length ) {
  486. updatePostResults( jetpackCarouselStrings.no_comment_author, false );
  487. return;
  488. }
  489. }
  490. }
  491. var xhr = new XMLHttpRequest();
  492. xhr.open( 'POST', jetpackCarouselStrings.ajaxurl, true );
  493. xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
  494. xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' );
  495. xhr.onreadystatechange = function () {
  496. if (
  497. this.readyState === XMLHttpRequest.DONE &&
  498. this.status >= 200 &&
  499. this.status < 300
  500. ) {
  501. var response;
  502. try {
  503. response = JSON.parse( this.response );
  504. } catch ( error ) {
  505. updatePostResults( jetpackCarouselStrings.comment_post_error, false );
  506. return;
  507. }
  508. if ( response.comment_status === 'approved' ) {
  509. updatePostResults( jetpackCarouselStrings.comment_approved, true );
  510. } else if ( response.comment_status === 'unapproved' ) {
  511. updatePostResults( jetpackCarouselStrings.comment_unapproved, true );
  512. } else {
  513. // 'deleted', 'spam', false
  514. updatePostResults( jetpackCarouselStrings.comment_post_error, false );
  515. }
  516. clearCommentTextAreaValue();
  517. fetchComments( attachmentId );
  518. submit.value = jetpackCarouselStrings.post_comment;
  519. domUtil.hide( spinner );
  520. form.classList.remove( 'jp-carousel-is-disabled' );
  521. } else {
  522. // TODO: Add error handling and display here
  523. updatePostResults( jetpackCarouselStrings.comment_post_error, false );
  524. }
  525. };
  526. var params = [];
  527. for ( var item in ajaxData ) {
  528. if ( item ) {
  529. // Encode each form element into a URI-compatible string.
  530. var encoded = encodeURIComponent( item ) + '=' + encodeURIComponent( ajaxData[ item ] );
  531. // In x-www-form-urlencoded, spaces should be `+`, not `%20`.
  532. params.push( encoded.replace( /%20/g, '+' ) );
  533. }
  534. }
  535. var encodedData = params.join( '&' );
  536. xhr.send( encodedData );
  537. }
  538. }
  539. /**
  540. * Handles clicks to icons and other action elements in the icon container.
  541. * @param {MouseEvent|TouchEvent|KeyBoardEvent} Event object.
  542. */
  543. function handleFooterElementClick( e ) {
  544. e.preventDefault();
  545. var target = e.target;
  546. var extraInfoContainer = carousel.info.querySelector( '.jp-carousel-info-extra' );
  547. var photoMetaContainer = carousel.info.querySelector( '.jp-carousel-image-meta' );
  548. var commentsContainer = carousel.info.querySelector( '.jp-carousel-comments-wrapper' );
  549. var infoIcon = carousel.info.querySelector( '.jp-carousel-icon-info' );
  550. var commentsIcon = carousel.info.querySelector( '.jp-carousel-icon-comments' );
  551. function handleInfoToggle() {
  552. if ( commentsIcon ) {
  553. commentsIcon.classList.remove( 'jp-carousel-selected' );
  554. }
  555. infoIcon.classList.toggle( 'jp-carousel-selected' );
  556. if ( commentsContainer ) {
  557. commentsContainer.classList.remove( 'jp-carousel-show' );
  558. }
  559. if ( photoMetaContainer ) {
  560. photoMetaContainer.classList.toggle( 'jp-carousel-show' );
  561. if ( photoMetaContainer.classList.contains( 'jp-carousel-show' ) ) {
  562. extraInfoContainer.classList.add( 'jp-carousel-show' );
  563. } else {
  564. extraInfoContainer.classList.remove( 'jp-carousel-show' );
  565. }
  566. }
  567. }
  568. function handleCommentToggle() {
  569. if ( infoIcon ) {
  570. infoIcon.classList.remove( 'jp-carousel-selected' );
  571. }
  572. commentsIcon.classList.toggle( 'jp-carousel-selected' );
  573. if ( photoMetaContainer ) {
  574. photoMetaContainer.classList.remove( 'jp-carousel-show' );
  575. }
  576. if ( commentsContainer ) {
  577. commentsContainer.classList.toggle( 'jp-carousel-show' );
  578. if ( commentsContainer.classList.contains( 'jp-carousel-show' ) ) {
  579. extraInfoContainer.classList.add( 'jp-carousel-show' );
  580. } else {
  581. extraInfoContainer.classList.remove( 'jp-carousel-show' );
  582. }
  583. }
  584. }
  585. if (
  586. domUtil.closest( target, '.jp-carousel-icon-info' ) ||
  587. target.classList.contains( 'jp-carousel-photo-title' )
  588. ) {
  589. if ( photoMetaContainer && photoMetaContainer.classList.contains( 'jp-carousel-show' ) ) {
  590. domUtil.scrollToElement( carousel.overlay, carousel.overlay, handleInfoToggle );
  591. } else {
  592. handleInfoToggle();
  593. domUtil.scrollToElement( carousel.info, carousel.overlay );
  594. }
  595. }
  596. if ( domUtil.closest( target, '.jp-carousel-icon-comments' ) ) {
  597. if ( commentsContainer && commentsContainer.classList.contains( 'jp-carousel-show' ) ) {
  598. domUtil.scrollToElement( carousel.overlay, carousel.overlay, handleCommentToggle );
  599. } else {
  600. handleCommentToggle();
  601. domUtil.scrollToElement( carousel.info, carousel.overlay );
  602. }
  603. }
  604. }
  605. function processSingleImageGallery() {
  606. var images = document.querySelectorAll( 'a img[data-attachment-id]' );
  607. Array.prototype.forEach.call( images, function ( image ) {
  608. var link = image.parentElement;
  609. var container = link.parentElement;
  610. // Skip if image was already added to gallery by shortcode.
  611. if ( container.classList.contains( 'gallery-icon' ) ) {
  612. return;
  613. }
  614. // Skip if image is part of a gallery.
  615. if ( domUtil.closest( container, galleryItemSelector ) ) {
  616. return;
  617. }
  618. // Skip if the parent is not actually a link.
  619. if ( ! link.hasAttribute( 'href' ) ) {
  620. return;
  621. }
  622. var valid = false;
  623. // If link points to 'Media File' (ignoring GET parameters) and flag is set, allow it.
  624. if (
  625. link.getAttribute( 'href' ).split( '?' )[ 0 ] ===
  626. image.getAttribute( 'data-orig-file' ).split( '?' )[ 0 ] &&
  627. Number( jetpackCarouselStrings.single_image_gallery_media_file ) === 1
  628. ) {
  629. valid = true;
  630. }
  631. // If link points to 'Attachment Page', allow it.
  632. if ( link.getAttribute( 'href' ) === image.getAttribute( 'data-permalink' ) ) {
  633. valid = true;
  634. }
  635. // Links to 'Custom URL' or 'Media File' when flag is not set are not valid.
  636. if ( ! valid ) {
  637. return;
  638. }
  639. // Make this node a gallery recognizable by event listener above.
  640. link.classList.add( 'single-image-gallery' );
  641. // blog_id is needed to allow posting comments to correct blog.
  642. link.setAttribute(
  643. 'data-carousel-extra',
  644. JSON.stringify( {
  645. blog_id: Number( jetpackCarouselStrings.blog_id ),
  646. } )
  647. );
  648. } );
  649. }
  650. function testForData( el ) {
  651. return !! ( el && el.getAttribute( 'data-carousel-extra' ) );
  652. }
  653. function openOrSelectSlide( gal, index ) {
  654. if ( ! carousel.isOpen ) {
  655. // The `open` method selects the correct slide during the initialization.
  656. loadSwiper( gal, { startIndex: index } );
  657. } else {
  658. selectSlideAtIndex( index );
  659. // We have to force swiper to slide to the index onHasChange.
  660. swiper.slideTo( index + 1 );
  661. }
  662. }
  663. function selectSlideAtIndex( index ) {
  664. if ( ! index || index < 0 || index > carousel.slides.length ) {
  665. index = 0;
  666. }
  667. carousel.currentSlide = carousel.slides[ index ];
  668. var current = carousel.currentSlide;
  669. var attachmentId = current.attrs.attachmentId;
  670. var infoIcon = carousel.info.querySelector( '.jp-carousel-icon-info' );
  671. var commentsIcon = carousel.info.querySelector( '.jp-carousel-icon-comments' );
  672. // If the comment/info section is toggled open, it's kept open, but scroll to top of the next slide.
  673. if (
  674. ( infoIcon && infoIcon.classList.contains( 'jp-carousel-selected' ) ) ||
  675. ( commentsIcon && commentsIcon.classList.contains( 'jp-carousel-selected' ) )
  676. ) {
  677. if ( carousel.overlay.scrollTop !== 0 ) {
  678. domUtil.scrollToElement( carousel.overlay, carousel.overlay );
  679. }
  680. }
  681. loadFullImage( carousel.slides[ index ] );
  682. if (
  683. Number( jetpackCarouselStrings.display_background_image ) === 1 &&
  684. ! carousel.slides[ index ].backgroundImage
  685. ) {
  686. loadBackgroundImage( carousel.slides[ index ] );
  687. }
  688. domUtil.hide( carousel.caption );
  689. updateTitleCaptionAndDesc( {
  690. caption: current.attrs.caption,
  691. title: current.attrs.title,
  692. desc: current.attrs.desc,
  693. } );
  694. var imageMeta = carousel.slides[ index ].attrs.imageMeta;
  695. updateExif( imageMeta );
  696. updateFullSizeLink( current );
  697. if ( Number( jetpackCarouselStrings.display_comments ) === 1 ) {
  698. testCommentsOpened( carousel.slides[ index ].attrs.commentsOpened );
  699. fetchComments( attachmentId );
  700. domUtil.hide( carousel.info.querySelector( '#jp-carousel-comment-post-results' ) );
  701. }
  702. // Update pagination in footer.
  703. var pagination = carousel.info.querySelector( '.jp-carousel-pagination' );
  704. if ( pagination && carousel.slides.length > 5 ) {
  705. var currentPage = index + 1;
  706. pagination.innerHTML = '<span>' + currentPage + ' / ' + carousel.slides.length + '</span>';
  707. }
  708. // Record pageview in WP Stats, for each new image loaded full-screen.
  709. if ( jetpackCarouselStrings.stats ) {
  710. new Image().src =
  711. document.location.protocol +
  712. '//pixel.wp.com/g.gif?' +
  713. jetpackCarouselStrings.stats +
  714. '&post=' +
  715. encodeURIComponent( attachmentId ) +
  716. '&rand=' +
  717. Math.random();
  718. }
  719. pageview( attachmentId );
  720. window.location.hash = lastKnownLocationHash = '#jp-carousel-' + attachmentId;
  721. }
  722. function restoreScroll() {
  723. window.scrollTo( window.scrollX || window.pageXOffset || 0, scrollPos || 0 );
  724. }
  725. function closeCarousel() {
  726. // Make sure to let the page scroll again.
  727. document.body.style.overflow = originalOverflow;
  728. document.documentElement.style.overflow = originalHOverflow;
  729. clearCommentTextAreaValue();
  730. disableKeyboardNavigation();
  731. domUtil.emitEvent( carousel.overlay, 'jp_carousel.beforeClose' );
  732. restoreScroll();
  733. swiper.destroy();
  734. carousel.isOpen = false;
  735. // Clear slide data for DOM garbage collection.
  736. carousel.slides = [];
  737. carousel.currentSlide = undefined;
  738. carousel.gallery.innerHTML = '';
  739. domUtil.fadeOut( carousel.overlay, function () {
  740. domUtil.emitEvent( carousel.overlay, 'jp_carousel.afterClose' );
  741. } );
  742. }
  743. function calculateMaxSlideDimensions() {
  744. return {
  745. width: window.innerWidth,
  746. height: window.innerHeight - 64, //subtract height of bottom info bar,
  747. };
  748. }
  749. function selectBestImageUrl( args ) {
  750. if ( typeof args !== 'object' ) {
  751. args = {};
  752. }
  753. if ( typeof args.origFile === 'undefined' ) {
  754. return '';
  755. }
  756. if ( typeof args.origWidth === 'undefined' || typeof args.maxWidth === 'undefined' ) {
  757. return args.origFile;
  758. }
  759. if ( typeof args.mediumFile === 'undefined' || typeof args.largeFile === 'undefined' ) {
  760. return args.origFile;
  761. }
  762. // Check if the image is being served by Photon (using a regular expression on the hostname).
  763. var imageLinkParser = document.createElement( 'a' );
  764. imageLinkParser.href = args.largeFile;
  765. var isPhotonUrl = /^i[0-2]\.wp\.com$/i.test( imageLinkParser.hostname );
  766. var mediumSizeParts = getImageSizeParts( args.mediumFile, args.origWidth, isPhotonUrl );
  767. var largeSizeParts = getImageSizeParts( args.largeFile, args.origWidth, isPhotonUrl );
  768. var largeWidth = parseInt( largeSizeParts[ 0 ], 10 );
  769. var largeHeight = parseInt( largeSizeParts[ 1 ], 10 );
  770. var mediumWidth = parseInt( mediumSizeParts[ 0 ], 10 );
  771. var mediumHeight = parseInt( mediumSizeParts[ 1 ], 10 );
  772. args.origMaxWidth = args.maxWidth;
  773. args.origMaxHeight = args.maxHeight;
  774. // Give devices with a higher devicePixelRatio higher-res images (Retina display = 2, Android phones = 1.5, etc)
  775. if ( typeof window.devicePixelRatio !== 'undefined' && window.devicePixelRatio > 1 ) {
  776. args.maxWidth = args.maxWidth * window.devicePixelRatio;
  777. args.maxHeight = args.maxHeight * window.devicePixelRatio;
  778. }
  779. if ( largeWidth >= args.maxWidth || largeHeight >= args.maxHeight ) {
  780. return args.largeFile;
  781. }
  782. if ( mediumWidth >= args.maxWidth || mediumHeight >= args.maxHeight ) {
  783. return args.mediumFile;
  784. }
  785. if ( isPhotonUrl ) {
  786. // args.origFile doesn't point to a Photon url, so in this case we use args.largeFile
  787. // to return the photon url of the original image.
  788. var largeFileIndex = args.largeFile.lastIndexOf( '?' );
  789. var origPhotonUrl = args.largeFile;
  790. if ( largeFileIndex !== -1 ) {
  791. origPhotonUrl = args.largeFile.substring( 0, largeFileIndex );
  792. // If we have a really large image load a smaller version
  793. // that is closer to the viewable size
  794. if ( args.origWidth > args.maxWidth || args.origHeight > args.maxHeight ) {
  795. // @2x the max sizes so we get a high enough resolution for zooming.
  796. args.origMaxWidth = args.maxWidth * 2;
  797. args.origMaxHeight = args.maxHeight * 2;
  798. origPhotonUrl += '?fit=' + args.origMaxWidth + '%2C' + args.origMaxHeight;
  799. }
  800. }
  801. return origPhotonUrl;
  802. }
  803. return args.origFile;
  804. }
  805. function getImageSizeParts( file, origWidth, isPhotonUrl ) {
  806. var size = isPhotonUrl
  807. ? file.replace( /.*=([\d]+%2C[\d]+).*$/, '$1' )
  808. : file.replace( /.*-([\d]+x[\d]+)\..+$/, '$1' );
  809. var sizeParts =
  810. size !== file
  811. ? isPhotonUrl
  812. ? size.split( '%2C' )
  813. : size.split( 'x' )
  814. : [ origWidth, 0 ];
  815. // If one of the dimensions is set to 9999, then the actual value of that dimension can't be retrieved from the url.
  816. // In that case, we set the value to 0.
  817. if ( sizeParts[ 0 ] === '9999' ) {
  818. sizeParts[ 0 ] = '0';
  819. }
  820. if ( sizeParts[ 1 ] === '9999' ) {
  821. sizeParts[ 1 ] = '0';
  822. }
  823. return sizeParts;
  824. }
  825. /**
  826. * Returns a number in a fraction format that represents the shutter speed.
  827. * @param Number speed
  828. * @return String
  829. */
  830. function formatShutterSpeed( speed ) {
  831. var denominator;
  832. // round to one decimal if value > 1s by multiplying it by 10, rounding, then dividing by 10 again
  833. if ( speed >= 1 ) {
  834. return Math.round( speed * 10 ) / 10 + 's';
  835. }
  836. // If the speed is less than one, we find the denominator by inverting
  837. // the number. Since cameras usually use rational numbers as shutter
  838. // speeds, we should get a nice round number. Or close to one in cases
  839. // like 1/30. So we round it.
  840. denominator = Math.round( 1 / speed );
  841. return '1/' + denominator + 's';
  842. }
  843. function parseTitleOrDesc( value ) {
  844. if ( ! value.match( ' ' ) && value.match( '_' ) ) {
  845. return '';
  846. }
  847. return value;
  848. }
  849. function updateTitleCaptionAndDesc( data ) {
  850. var caption = '';
  851. var title = '';
  852. var desc = '';
  853. var captionMainElement;
  854. var captionInfoExtraElement;
  855. var titleElement;
  856. var descriptionElement;
  857. captionMainElement = carousel.overlay.querySelector( '.jp-carousel-photo-caption' );
  858. captionInfoExtraElement = carousel.overlay.querySelector( '.jp-carousel-caption' );
  859. titleElement = carousel.overlay.querySelector( '.jp-carousel-photo-title' );
  860. descriptionElement = carousel.overlay.querySelector( '.jp-carousel-photo-description' );
  861. domUtil.hide( captionMainElement );
  862. domUtil.hide( captionInfoExtraElement );
  863. domUtil.hide( titleElement );
  864. domUtil.hide( descriptionElement );
  865. caption = parseTitleOrDesc( data.caption ) || '';
  866. title = parseTitleOrDesc( data.title ) || '';
  867. desc = parseTitleOrDesc( data.desc ) || '';
  868. if ( caption || title || desc ) {
  869. if ( caption ) {
  870. captionMainElement.innerHTML = caption;
  871. captionInfoExtraElement.innerHTML = caption;
  872. domUtil.show( captionMainElement );
  873. domUtil.show( captionInfoExtraElement );
  874. }
  875. if ( domUtil.stripHTML( caption ) === domUtil.stripHTML( title ) ) {
  876. title = '';
  877. }
  878. if ( domUtil.stripHTML( caption ) === domUtil.stripHTML( desc ) ) {
  879. desc = '';
  880. }
  881. if ( domUtil.stripHTML( title ) === domUtil.stripHTML( desc ) ) {
  882. desc = '';
  883. }
  884. if ( desc ) {
  885. descriptionElement.innerHTML = desc;
  886. domUtil.show( descriptionElement );
  887. if ( ! title && ! caption ) {
  888. captionMainElement.innerHTML = domUtil.stripHTML( desc );
  889. domUtil.show( captionMainElement );
  890. }
  891. }
  892. if ( title ) {
  893. var plainTitle = domUtil.stripHTML( title );
  894. titleElement.innerHTML = plainTitle;
  895. if ( ! caption ) {
  896. captionMainElement.innerHTML = plainTitle;
  897. captionInfoExtraElement.innerHTML = plainTitle;
  898. domUtil.show( captionMainElement );
  899. }
  900. domUtil.show( titleElement );
  901. }
  902. }
  903. }
  904. // updateExif updates the contents of the exif UL (.jp-carousel-image-exif)
  905. function updateExif( meta ) {
  906. if ( ! meta || Number( jetpackCarouselStrings.display_exif ) !== 1 ) {
  907. return false;
  908. }
  909. var ul = carousel.info.querySelector( '.jp-carousel-image-meta ul.jp-carousel-image-exif' );
  910. var html = '';
  911. for ( var key in meta ) {
  912. var val = meta[ key ];
  913. var metaKeys = jetpackCarouselStrings.meta_data || [];
  914. if ( parseFloat( val ) === 0 || ! val.length || metaKeys.indexOf( key ) === -1 ) {
  915. continue;
  916. }
  917. switch ( key ) {
  918. case 'focal_length':
  919. val = val + 'mm';
  920. break;
  921. case 'shutter_speed':
  922. val = formatShutterSpeed( val );
  923. break;
  924. case 'aperture':
  925. val = 'f/' + val;
  926. break;
  927. }
  928. html += '<li><h5>' + jetpackCarouselStrings[ key ] + '</h5>' + val + '</li>';
  929. }
  930. ul.innerHTML = html;
  931. ul.style.removeProperty( 'display' );
  932. }
  933. // Update the contents of the jp-carousel-image-download link
  934. function updateFullSizeLink( currentSlide ) {
  935. if ( ! currentSlide ) {
  936. return false;
  937. }
  938. var original;
  939. var origSize = [ currentSlide.attrs.origWidth, currentSlide.attrs.origHeight ];
  940. var imageLinkParser = document.createElement( 'a' );
  941. imageLinkParser.href = currentSlide.attrs.src.replace( /\?.+$/, '' );
  942. // Is this a Photon URL?
  943. if ( imageLinkParser.hostname.match( /^i[\d]{1}\.wp\.com$/i ) !== null ) {
  944. original = imageLinkParser.href;
  945. } else {
  946. original = currentSlide.attrs.origFile.replace( /\?.+$/, '' );
  947. }
  948. var downloadText = carousel.info.querySelector( '.jp-carousel-download-text' );
  949. var permalink = carousel.info.querySelector( '.jp-carousel-image-download' );
  950. downloadText.innerHTML = util.applyReplacements(
  951. jetpackCarouselStrings.download_original,
  952. origSize
  953. );
  954. permalink.setAttribute( 'href', original );
  955. permalink.style.removeProperty( 'display' );
  956. }
  957. function testCommentsOpened( opened ) {
  958. var commentForm = carousel.container.querySelector( '.jp-carousel-comment-form-container' );
  959. var isOpened = parseInt( opened, 10 ) === 1;
  960. if ( isOpened ) {
  961. domUtil.fadeIn( commentForm );
  962. } else {
  963. domUtil.fadeOut( commentForm );
  964. }
  965. }
  966. function fetchComments( attachmentId, offset ) {
  967. var shouldClear = offset === undefined;
  968. var commentsIndicator = carousel.info.querySelector(
  969. '.jp-carousel-icon-comments .jp-carousel-has-comments-indicator'
  970. );
  971. commentsIndicator.classList.remove( 'jp-carousel-show' );
  972. clearInterval( commentInterval );
  973. if ( ! attachmentId ) {
  974. return;
  975. }
  976. if ( ! offset || offset < 1 ) {
  977. offset = 0;
  978. }
  979. var comments = carousel.info.querySelector( '.jp-carousel-comments' );
  980. var commentsLoading = carousel.info.querySelector( '#jp-carousel-comments-loading' );
  981. domUtil.show( commentsLoading );
  982. if ( shouldClear ) {
  983. domUtil.hide( comments );
  984. comments.innerHTML = '';
  985. }
  986. var xhr = new XMLHttpRequest();
  987. var url =
  988. jetpackCarouselStrings.ajaxurl +
  989. '?action=get_attachment_comments' +
  990. '&nonce=' +
  991. jetpackCarouselStrings.nonce +
  992. '&id=' +
  993. attachmentId +
  994. '&offset=' +
  995. offset;
  996. xhr.open( 'GET', url );
  997. xhr.setRequestHeader( 'X-Requested-With', 'XMLHttpRequest' );
  998. var onError = function () {
  999. domUtil.fadeIn( comments );
  1000. domUtil.fadeOut( commentsLoading );
  1001. };
  1002. xhr.onload = function () {
  1003. // Ignore the results if they arrive late and we're now on a different slide.
  1004. if (
  1005. ! carousel.currentSlide ||
  1006. carousel.currentSlide.attrs.attachmentId !== attachmentId
  1007. ) {
  1008. return;
  1009. }
  1010. var isSuccess = xhr.status >= 200 && xhr.status < 300;
  1011. var data;
  1012. try {
  1013. data = JSON.parse( xhr.responseText );
  1014. } catch ( e ) {
  1015. // Do nothing.
  1016. }
  1017. if ( ! isSuccess || ! data || ! Array.isArray( data ) ) {
  1018. return onError();
  1019. }
  1020. if ( shouldClear ) {
  1021. comments.innerHTML = '';
  1022. }
  1023. for ( var i = 0; i < data.length; i++ ) {
  1024. var entry = data[ i ];
  1025. var comment = document.createElement( 'div' );
  1026. comment.classList.add( 'jp-carousel-comment' );
  1027. comment.setAttribute( 'id', 'jp-carousel-comment-' + entry.id );
  1028. comment.innerHTML =
  1029. '<div class="comment-gravatar">' +
  1030. entry.gravatar_markup +
  1031. '</div>' +
  1032. '<div class="comment-content">' +
  1033. '<div class="comment-author">' +
  1034. entry.author_markup +
  1035. '</div>' +
  1036. '<div class="comment-date">' +
  1037. entry.date_gmt +
  1038. '</div>' +
  1039. entry.content +
  1040. '</div>';
  1041. comments.appendChild( comment );
  1042. // Set the interval to check for a new page of comments.
  1043. clearInterval( commentInterval );
  1044. commentInterval = setInterval( function () {
  1045. if ( carousel.container.scrollTop + 150 > window.innerHeight ) {
  1046. fetchComments( attachmentId, offset + 10 );
  1047. clearInterval( commentInterval );
  1048. }
  1049. }, 300 );
  1050. }
  1051. if ( data.length > 0 ) {
  1052. domUtil.show( comments );
  1053. commentsIndicator.innerText = data.length;
  1054. commentsIndicator.classList.add( 'jp-carousel-show' );
  1055. }
  1056. domUtil.hide( commentsLoading );
  1057. };
  1058. xhr.onerror = onError;
  1059. xhr.send();
  1060. }
  1061. function loadFullImage( slide ) {
  1062. var el = slide.el;
  1063. var attrs = slide.attrs;
  1064. var image = el.querySelector( 'img' );
  1065. if ( ! image.hasAttribute( 'data-loaded' ) ) {
  1066. var hasPreview = !! attrs.previewImage;
  1067. var thumbSize = attrs.thumbSize;
  1068. if ( ! hasPreview || ( thumbSize && el.offsetWidth > thumbSize.width ) ) {
  1069. image.src = attrs.src;
  1070. } else {
  1071. image.src = attrs.previewImage;
  1072. }
  1073. image.setAttribute( 'itemprop', 'image' );
  1074. image.setAttribute( 'data-loaded', 1 );
  1075. }
  1076. }
  1077. function loadBackgroundImage( slide ) {
  1078. var currentSlide = slide.el;
  1079. if ( swiper && swiper.slides ) {
  1080. currentSlide = swiper.slides[ swiper.activeIndex ];
  1081. }
  1082. var image = slide.attrs.originalElement;
  1083. var isLoaded = image.complete && image.naturalHeight !== 0;
  1084. if ( isLoaded ) {
  1085. applyBackgroundImage( slide, currentSlide, image );
  1086. return;
  1087. }
  1088. image.onload = function () {
  1089. applyBackgroundImage( slide, currentSlide, image );
  1090. };
  1091. }
  1092. function applyBackgroundImage( slide, currentSlide, image ) {
  1093. var url = util.getBackgroundImage( image );
  1094. slide.backgroundImage = url;
  1095. currentSlide.style.backgroundImage = 'url(' + url + ')';
  1096. currentSlide.style.backgroundSize = 'cover';
  1097. }
  1098. function clearCommentTextAreaValue() {
  1099. if ( carousel.commentField ) {
  1100. carousel.commentField.value = '';
  1101. }
  1102. }
  1103. function getOriginalDimensions( el ) {
  1104. var size = el.getAttribute( 'data-orig-size' ) || '';
  1105. if ( size ) {
  1106. var parts = size.split( ',' );
  1107. return { width: parseInt( parts[ 0 ], 10 ), height: parseInt( parts[ 1 ], 10 ) };
  1108. } else {
  1109. return {
  1110. width:
  1111. el.getAttribute( 'data-original-width' ) || el.getAttribute( 'width' ) || undefined,
  1112. height:
  1113. el.getAttribute( 'data-original-height' ) || el.getAttribute( 'height' ) || undefined,
  1114. };
  1115. }
  1116. }
  1117. function initCarouselSlides( items, startIndex ) {
  1118. carousel.slides = [];
  1119. var max = calculateMaxSlideDimensions();
  1120. // If the startIndex is not 0 then preload the clicked image first.
  1121. if ( startIndex !== 0 ) {
  1122. var img = new Image();
  1123. img.src = items[ startIndex ].getAttribute( 'data-gallery-src' );
  1124. }
  1125. var useInPageThumbnails = !! domUtil.closest( items[ 0 ], '.tiled-gallery.type-rectangular' );
  1126. // create the 'slide'
  1127. Array.prototype.forEach.call( items, function ( item, i ) {
  1128. var permalinkEl = domUtil.closest( item, 'a' );
  1129. var origFile = item.getAttribute( 'data-orig-file' ) || item.getAttribute( 'src-orig' );
  1130. var attrID =
  1131. item.getAttribute( 'data-attachment-id' ) || item.getAttribute( 'data-id' ) || '0';
  1132. var caption = document.querySelector(
  1133. 'img[data-attachment-id="' + attrID + '"] + figcaption'
  1134. );
  1135. if ( caption ) {
  1136. caption = caption.innerHTML;
  1137. } else {
  1138. caption = item.getAttribute( 'data-image-caption' );
  1139. }
  1140. var attrs = {
  1141. originalElement: item,
  1142. attachmentId: attrID,
  1143. commentsOpened: item.getAttribute( 'data-comments-opened' ) || '0',
  1144. imageMeta: domUtil.getJSONAttribute( item, 'data-image-meta' ) || {},
  1145. title: item.getAttribute( 'data-image-title' ) || '',
  1146. desc: item.getAttribute( 'data-image-description' ) || '',
  1147. mediumFile: item.getAttribute( 'data-medium-file' ) || '',
  1148. largeFile: item.getAttribute( 'data-large-file' ) || '',
  1149. origFile: origFile || '',
  1150. thumbSize: { width: item.naturalWidth, height: item.naturalHeight },
  1151. caption: caption || '',
  1152. permalink: permalinkEl && permalinkEl.getAttribute( 'href' ),
  1153. src: origFile || item.getAttribute( 'src' ) || '',
  1154. };
  1155. var tiledGalleryItem = domUtil.closest( item, '.tiled-gallery-item' );
  1156. var tiledCaptionEl =
  1157. tiledGalleryItem && tiledGalleryItem.querySelector( '.tiled-gallery-caption' );
  1158. var tiledCaption = tiledCaptionEl && tiledCaptionEl.innerHTML;
  1159. if ( tiledCaption ) {
  1160. attrs.caption = tiledCaption;
  1161. }
  1162. var origDimensions = getOriginalDimensions( item );
  1163. attrs.origWidth = origDimensions.width || attrs.thumbSize.width;
  1164. attrs.origHeight = origDimensions.height || attrs.thumbSize.height;
  1165. if ( typeof wpcom !== 'undefined' && wpcom.carousel && wpcom.carousel.generateImgSrc ) {
  1166. attrs.src = wpcom.carousel.generateImgSrc( item, max );
  1167. } else {
  1168. attrs.src = selectBestImageUrl( {
  1169. origFile: attrs.src,
  1170. origWidth: attrs.origWidth,
  1171. origHeight: attrs.origHeight,
  1172. maxWidth: max.width,
  1173. maxHeight: max.height,
  1174. mediumFile: attrs.mediumFile,
  1175. largeFile: attrs.largeFile,
  1176. } );
  1177. }
  1178. // Set the final src.
  1179. item.setAttribute( 'data-gallery-src', attrs.src );
  1180. if ( attrs.attachmentId !== '0' ) {
  1181. attrs.title = util.texturize( attrs.title );
  1182. attrs.desc = util.texturize( attrs.desc );
  1183. attrs.caption = util.texturize( attrs.caption );
  1184. // Initially, the image is a 1x1 transparent gif.
  1185. // The preview is shown as a background image on the slide itself.
  1186. var image = new Image();
  1187. image.src = attrs.src;
  1188. var slideEl = document.createElement( 'div' );
  1189. slideEl.classList.add( 'swiper-slide' );
  1190. slideEl.setAttribute( 'itemprop', 'associatedMedia' );
  1191. slideEl.setAttribute( 'itemscope', '' );
  1192. slideEl.setAttribute( 'itemtype', 'https://schema.org/ImageObject' );
  1193. var zoomEl = document.createElement( 'div' );
  1194. zoomEl.classList.add( 'swiper-zoom-container' );
  1195. carousel.gallery.appendChild( slideEl );
  1196. slideEl.appendChild( zoomEl );
  1197. zoomEl.appendChild( image );
  1198. slideEl.setAttribute( 'data-attachment-id', attrs.attachmentId );
  1199. slideEl.setAttribute( 'data-permalink', attrs.permalink );
  1200. slideEl.setAttribute( 'data-orig-file', attrs.origFile );
  1201. if ( useInPageThumbnails ) {
  1202. // Use the image already loaded in the gallery as a preview.
  1203. attrs.previewImage = attrs.src;
  1204. }
  1205. var slide = { el: slideEl, attrs: attrs, index: i };
  1206. carousel.slides.push( slide );
  1207. }
  1208. } );
  1209. }
  1210. function loadSwiper( gallery, options ) {
  1211. if ( ! window.Swiper670 ) {
  1212. var loader = document.querySelector( '#jp-carousel-loading-overlay' );
  1213. domUtil.show( loader );
  1214. var jsScript = document.createElement( 'script' );
  1215. jsScript.id = 'jetpack-carousel-swiper-js';
  1216. jsScript.src = window.jetpackSwiperLibraryPath.url;
  1217. jsScript.async = true;
  1218. jsScript.onload = function () {
  1219. domUtil.hide( loader );
  1220. openCarousel( gallery, options );
  1221. };
  1222. jsScript.onerror = function () {
  1223. domUtil.hide( loader );
  1224. };
  1225. document.head.appendChild( jsScript );
  1226. return;
  1227. }
  1228. openCarousel( gallery, options );
  1229. }
  1230. function openCarousel( gallery, options ) {
  1231. var settings = {
  1232. imgSelector:
  1233. '.gallery-item [data-attachment-id], .tiled-gallery-item [data-attachment-id], img[data-attachment-id], img[data-id]',
  1234. startIndex: 0,
  1235. };
  1236. var data = domUtil.getJSONAttribute( gallery, 'data-carousel-extra' );
  1237. var tapTimeout;
  1238. if ( ! data ) {
  1239. return; // don't run if the default gallery functions weren't used
  1240. }
  1241. initializeCarousel();
  1242. if ( carousel.isOpen ) {
  1243. return; // don't open if already opened
  1244. }
  1245. carousel.isOpen = true;
  1246. // make sure to stop the page from scrolling behind the carousel overlay, so we don't trigger
  1247. // infiniscroll for it when enabled (Reader, theme infiniscroll, etc).
  1248. originalOverflow = getComputedStyle( document.body ).overflow;
  1249. document.body.style.overflow = 'hidden';
  1250. // prevent html from overflowing on some of the new themes.
  1251. originalHOverflow = getComputedStyle( document.documentElement ).overflow;
  1252. document.documentElement.style.overflow = 'hidden';
  1253. scrollPos = window.scrollY || window.pageYOffset || 0;
  1254. carousel.container.setAttribute( 'data-carousel-extra', JSON.stringify( data ) );
  1255. stat( [ 'open', 'view_image' ] );
  1256. // If options exist, lets merge them
  1257. // with our default settings
  1258. for ( var option in options || {} ) {
  1259. settings[ option ] = options[ option ];
  1260. }
  1261. if ( settings.startIndex === -1 ) {
  1262. settings.startIndex = 0; // -1 returned if can't find index, so start from beginning
  1263. }
  1264. domUtil.emitEvent( carousel.overlay, 'jp_carousel.beforeOpen' );
  1265. carousel.gallery.innerHTML = '';
  1266. // Need to set the overlay manually to block or swiper does't initialise properly.
  1267. carousel.overlay.style.opacity = 1;
  1268. carousel.overlay.style.display = 'block';
  1269. initCarouselSlides( gallery.querySelectorAll( settings.imgSelector ), settings.startIndex );
  1270. swiper = new window.Swiper670( '.jp-carousel-swiper-container', {
  1271. centeredSlides: true,
  1272. zoom: true,
  1273. loop: carousel.slides.length > 1,
  1274. // Turn off interactions and hide navigation arrows if there is only one slide.
  1275. enabled: carousel.slides.length > 1,
  1276. pagination: {
  1277. el: '.jp-swiper-pagination',
  1278. clickable: true,
  1279. },
  1280. navigation: {
  1281. nextEl: '.jp-swiper-button-next',
  1282. prevEl: '.jp-swiper-button-prev',
  1283. },
  1284. initialSlide: settings.startIndex,
  1285. on: {
  1286. init: function () {
  1287. selectSlideAtIndex( settings.startIndex );
  1288. },
  1289. },
  1290. preventClicks: false,
  1291. preventClicksPropagation: false,
  1292. preventInteractionOnTransition: ! domUtil.isTouch(),
  1293. threshold: 5,
  1294. } );
  1295. swiper.on( 'slideChange', function ( swiper ) {
  1296. var index;
  1297. // Swiper indexes slides from 1, plus when looping to left last slide ends up
  1298. // as 0 and looping to right first slide as total slides + 1. These are adjusted
  1299. // here to match index of carousel.slides.
  1300. if ( swiper.activeIndex === 0 ) {
  1301. index = carousel.slides.length - 1;
  1302. } else if ( swiper.activeIndex === carousel.slides.length + 1 ) {
  1303. index = 0;
  1304. } else {
  1305. index = swiper.activeIndex - 1;
  1306. }
  1307. selectSlideAtIndex( index );
  1308. carousel.overlay.classList.remove( 'jp-carousel-hide-controls' );
  1309. } );
  1310. swiper.on( 'zoomChange', function ( swiper, scale ) {
  1311. if ( scale > 1 ) {
  1312. carousel.overlay.classList.add( 'jp-carousel-hide-controls' );
  1313. }
  1314. if ( scale === 1 ) {
  1315. carousel.overlay.classList.remove( 'jp-carousel-hide-controls' );
  1316. }
  1317. } );
  1318. swiper.on( 'doubleTap', function ( swiper ) {
  1319. clearTimeout( tapTimeout );
  1320. if ( swiper.zoom.scale === 1 ) {
  1321. var zoomTimeout = setTimeout( function () {
  1322. carousel.overlay.classList.remove( 'jp-carousel-hide-controls' );
  1323. clearTimeout( zoomTimeout );
  1324. }, 150 );
  1325. }
  1326. } );
  1327. swiper.on( 'tap', function () {
  1328. if ( swiper.zoom.scale > 1 ) {
  1329. tapTimeout = setTimeout( function () {
  1330. carousel.overlay.classList.toggle( 'jp-carousel-hide-controls' );
  1331. }, 150 );
  1332. }
  1333. } );
  1334. domUtil.fadeIn( carousel.overlay, function () {
  1335. domUtil.emitEvent( carousel.overlay, 'jp_carousel.afterOpen' );
  1336. } );
  1337. }
  1338. // Register the event listener for starting the gallery
  1339. document.body.addEventListener( 'click', function ( e ) {
  1340. var isCompatible =
  1341. window.CSS && window.CSS.supports && window.CSS.supports( 'display', 'grid' );
  1342. // IE11 support is being dropped in August 2021. The new swiper.js libray is not IE11 compat
  1343. // so just default to opening individual image attachment/media pages for IE.
  1344. if ( ! isCompatible ) {
  1345. return;
  1346. }
  1347. var target = e.target;
  1348. var gallery = domUtil.closest( target, gallerySelector );
  1349. if ( gallery ) {
  1350. if ( ! testForData( gallery ) ) {
  1351. return;
  1352. }
  1353. var parent = target.parentElement;
  1354. var grandparent = parent.parentElement;
  1355. // If Gallery is made up of individual Image blocks check for custom link before
  1356. // loading carousel.
  1357. if ( grandparent && grandparent.classList.contains( 'wp-block-image' ) ) {
  1358. var parentHref = parent.getAttribute( 'href' );
  1359. // If the link does not point to the attachment or media file then assume Image has
  1360. // a custom link so don't load the carousel.
  1361. if (
  1362. parentHref.split( '?' )[ 0 ] !==
  1363. target.getAttribute( 'data-orig-file' ).split( '?' )[ 0 ] &&
  1364. parentHref !== target.getAttribute( 'data-permalink' )
  1365. ) {
  1366. return;
  1367. }
  1368. }
  1369. // Do not open the modal if we are looking at a gallery caption from before WP5, which may contain a link.
  1370. if ( parent.classList.contains( 'gallery-caption' ) ) {
  1371. return;
  1372. }
  1373. // Do not open the modal if we are looking at a caption of a gallery block, which may contain a link.
  1374. if ( domUtil.matches( parent, 'figcaption' ) ) {
  1375. return;
  1376. }
  1377. // Set height to auto.
  1378. // Fix some themes where closing carousel brings view back to top.
  1379. document.documentElement.style.height = 'auto';
  1380. e.preventDefault();
  1381. // Stopping propagation in case there are parent elements
  1382. // with .gallery or .tiled-gallery class
  1383. e.stopPropagation();
  1384. var item = domUtil.closest( target, itemSelector );
  1385. var index = Array.prototype.indexOf.call( gallery.querySelectorAll( itemSelector ), item );
  1386. loadSwiper( gallery, { startIndex: index } );
  1387. }
  1388. } );
  1389. // Handle lightbox (single image gallery) for images linking to 'Attachment Page'.
  1390. if ( Number( jetpackCarouselStrings.single_image_gallery ) === 1 ) {
  1391. processSingleImageGallery();
  1392. document.body.addEventListener( 'is.post-load', function () {
  1393. processSingleImageGallery();
  1394. } );
  1395. }
  1396. // Makes carousel work on page load and when back button leads to same URL with carousel hash
  1397. // (i.e. no actual document.ready trigger).
  1398. window.addEventListener( 'hashchange', function () {
  1399. var hashRegExp = /jp-carousel-(\d+)/;
  1400. if ( ! window.location.hash || ! hashRegExp.test( window.location.hash ) ) {
  1401. if ( carousel.isOpen ) {
  1402. closeCarousel();
  1403. }
  1404. return;
  1405. }
  1406. if ( window.location.hash === lastKnownLocationHash && carousel.isOpen ) {
  1407. return;
  1408. }
  1409. if ( window.location.hash && carousel.gallery && ! carousel.isOpen && history.back ) {
  1410. history.back();
  1411. return;
  1412. }
  1413. lastKnownLocationHash = window.location.hash;
  1414. var matchList = window.location.hash.match( hashRegExp );
  1415. var attachmentId = parseInt( matchList[ 1 ], 10 );
  1416. var galleries = document.querySelectorAll( gallerySelector );
  1417. // Find the first thumbnail that matches the attachment ID in the location
  1418. // hash, then open the gallery that contains it.
  1419. for ( var i = 0; i < galleries.length; i++ ) {
  1420. var gallery = galleries[ i ];
  1421. var selected;
  1422. var images = gallery.querySelectorAll( 'img' );
  1423. for ( var j = 0; j < images.length; j++ ) {
  1424. if (
  1425. parseInt( images[ j ].getAttribute( 'data-attachment-id' ), 10 ) === attachmentId ||
  1426. parseInt( images[ j ].getAttribute( 'data-id' ), 10 ) === attachmentId
  1427. ) {
  1428. selected = j;
  1429. break;
  1430. }
  1431. }
  1432. if ( selected !== undefined ) {
  1433. openOrSelectSlide( gallery, selected );
  1434. break;
  1435. }
  1436. }
  1437. } );
  1438. if ( window.location.hash ) {
  1439. domUtil.emitEvent( window, 'hashchange' );
  1440. }
  1441. }
  1442. if ( document.readyState !== 'loading' ) {
  1443. init();
  1444. } else {
  1445. document.addEventListener( 'DOMContentLoaded', init );
  1446. }
  1447. } )();