You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

844 lines
25 KiB

  1. /*
  2. * Script run inside a Customizer preview frame.
  3. */
  4. (function( exports, $ ){
  5. var api = wp.customize,
  6. debounce,
  7. currentHistoryState = {};
  8. /*
  9. * Capture the state that is passed into history.replaceState() and history.pushState()
  10. * and also which is returned in the popstate event so that when the changeset_uuid
  11. * gets updated when transitioning to a new changeset there the current state will
  12. * be supplied in the call to history.replaceState().
  13. */
  14. ( function( history ) {
  15. var injectUrlWithState;
  16. if ( ! history.replaceState ) {
  17. return;
  18. }
  19. /**
  20. * Amend the supplied URL with the customized state.
  21. *
  22. * @since 4.7.0
  23. * @access private
  24. *
  25. * @param {string} url URL.
  26. * @returns {string} URL with customized state.
  27. */
  28. injectUrlWithState = function( url ) {
  29. var urlParser, oldQueryParams, newQueryParams;
  30. urlParser = document.createElement( 'a' );
  31. urlParser.href = url;
  32. oldQueryParams = api.utils.parseQueryString( location.search.substr( 1 ) );
  33. newQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
  34. newQueryParams.customize_changeset_uuid = oldQueryParams.customize_changeset_uuid;
  35. if ( oldQueryParams.customize_theme ) {
  36. newQueryParams.customize_theme = oldQueryParams.customize_theme;
  37. }
  38. if ( oldQueryParams.customize_messenger_channel ) {
  39. newQueryParams.customize_messenger_channel = oldQueryParams.customize_messenger_channel;
  40. }
  41. urlParser.search = $.param( newQueryParams );
  42. return urlParser.href;
  43. };
  44. history.replaceState = ( function( nativeReplaceState ) {
  45. return function historyReplaceState( data, title, url ) {
  46. currentHistoryState = data;
  47. return nativeReplaceState.call( history, data, title, 'string' === typeof url && url.length > 0 ? injectUrlWithState( url ) : url );
  48. };
  49. } )( history.replaceState );
  50. history.pushState = ( function( nativePushState ) {
  51. return function historyPushState( data, title, url ) {
  52. currentHistoryState = data;
  53. return nativePushState.call( history, data, title, 'string' === typeof url && url.length > 0 ? injectUrlWithState( url ) : url );
  54. };
  55. } )( history.pushState );
  56. window.addEventListener( 'popstate', function( event ) {
  57. currentHistoryState = event.state;
  58. } );
  59. }( history ) );
  60. /**
  61. * Returns a debounced version of the function.
  62. *
  63. * @todo Require Underscore.js for this file and retire this.
  64. */
  65. debounce = function( fn, delay, context ) {
  66. var timeout;
  67. return function() {
  68. var args = arguments;
  69. context = context || this;
  70. clearTimeout( timeout );
  71. timeout = setTimeout( function() {
  72. timeout = null;
  73. fn.apply( context, args );
  74. }, delay );
  75. };
  76. };
  77. /**
  78. * @constructor
  79. * @augments wp.customize.Messenger
  80. * @augments wp.customize.Class
  81. * @mixes wp.customize.Events
  82. */
  83. api.Preview = api.Messenger.extend({
  84. /**
  85. * @param {object} params - Parameters to configure the messenger.
  86. * @param {object} options - Extend any instance parameter or method with this object.
  87. */
  88. initialize: function( params, options ) {
  89. var preview = this, urlParser = document.createElement( 'a' );
  90. api.Messenger.prototype.initialize.call( preview, params, options );
  91. urlParser.href = preview.origin();
  92. preview.add( 'scheme', urlParser.protocol.replace( /:$/, '' ) );
  93. preview.body = $( document.body );
  94. preview.window = $( window );
  95. if ( api.settings.channel ) {
  96. // If in an iframe, then intercept the link clicks and form submissions.
  97. preview.body.on( 'click.preview', 'a', function( event ) {
  98. preview.handleLinkClick( event );
  99. } );
  100. preview.body.on( 'submit.preview', 'form', function( event ) {
  101. preview.handleFormSubmit( event );
  102. } );
  103. preview.window.on( 'scroll.preview', debounce( function() {
  104. preview.send( 'scroll', preview.window.scrollTop() );
  105. }, 200 ) );
  106. preview.bind( 'scroll', function( distance ) {
  107. preview.window.scrollTop( distance );
  108. });
  109. }
  110. },
  111. /**
  112. * Handle link clicks in preview.
  113. *
  114. * @since 4.7.0
  115. * @access public
  116. *
  117. * @param {jQuery.Event} event Event.
  118. */
  119. handleLinkClick: function( event ) {
  120. var preview = this, link, isInternalJumpLink;
  121. link = $( event.target ).closest( 'a' );
  122. // No-op if the anchor is not a link.
  123. if ( _.isUndefined( link.attr( 'href' ) ) ) {
  124. return;
  125. }
  126. // Allow internal jump links and JS links to behave normally without preventing default.
  127. isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
  128. if ( isInternalJumpLink || ! /^https?:$/.test( link.prop( 'protocol' ) ) ) {
  129. return;
  130. }
  131. // If the link is not previewable, prevent the browser from navigating to it.
  132. if ( ! api.isLinkPreviewable( link[0] ) ) {
  133. wp.a11y.speak( api.settings.l10n.linkUnpreviewable );
  134. event.preventDefault();
  135. return;
  136. }
  137. // Prevent initiating navigating from click and instead rely on sending url message to pane.
  138. event.preventDefault();
  139. /*
  140. * Note the shift key is checked so shift+click on widgets or
  141. * nav menu items can just result on focusing on the corresponding
  142. * control instead of also navigating to the URL linked to.
  143. */
  144. if ( event.shiftKey ) {
  145. return;
  146. }
  147. // Note: It's not relevant to send scroll because sending url message will have the same effect.
  148. preview.send( 'url', link.prop( 'href' ) );
  149. },
  150. /**
  151. * Handle form submit.
  152. *
  153. * @since 4.7.0
  154. * @access public
  155. *
  156. * @param {jQuery.Event} event Event.
  157. */
  158. handleFormSubmit: function( event ) {
  159. var preview = this, urlParser, form;
  160. urlParser = document.createElement( 'a' );
  161. form = $( event.target );
  162. urlParser.href = form.prop( 'action' );
  163. // If the link is not previewable, prevent the browser from navigating to it.
  164. if ( 'GET' !== form.prop( 'method' ).toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
  165. wp.a11y.speak( api.settings.l10n.formUnpreviewable );
  166. event.preventDefault();
  167. return;
  168. }
  169. /*
  170. * If the default wasn't prevented already (in which case the form
  171. * submission is already being handled by JS), and if it has a GET
  172. * request method, then take the serialized form data and add it as
  173. * a query string to the action URL and send this in a url message
  174. * to the customizer pane so that it will be loaded. If the form's
  175. * action points to a non-previewable URL, the customizer pane's
  176. * previewUrl setter will reject it so that the form submission is
  177. * a no-op, which is the same behavior as when clicking a link to an
  178. * external site in the preview.
  179. */
  180. if ( ! event.isDefaultPrevented() ) {
  181. if ( urlParser.search.length > 1 ) {
  182. urlParser.search += '&';
  183. }
  184. urlParser.search += form.serialize();
  185. preview.send( 'url', urlParser.href );
  186. }
  187. // Prevent default since navigation should be done via sending url message or via JS submit handler.
  188. event.preventDefault();
  189. }
  190. });
  191. /**
  192. * Inject the changeset UUID into links in the document.
  193. *
  194. * @since 4.7.0
  195. * @access protected
  196. *
  197. * @access private
  198. * @returns {void}
  199. */
  200. api.addLinkPreviewing = function addLinkPreviewing() {
  201. var linkSelectors = 'a[href], area';
  202. // Inject links into initial document.
  203. $( document.body ).find( linkSelectors ).each( function() {
  204. api.prepareLinkPreview( this );
  205. } );
  206. // Inject links for new elements added to the page.
  207. if ( 'undefined' !== typeof MutationObserver ) {
  208. api.mutationObserver = new MutationObserver( function( mutations ) {
  209. _.each( mutations, function( mutation ) {
  210. $( mutation.target ).find( linkSelectors ).each( function() {
  211. api.prepareLinkPreview( this );
  212. } );
  213. } );
  214. } );
  215. api.mutationObserver.observe( document.documentElement, {
  216. childList: true,
  217. subtree: true
  218. } );
  219. } else {
  220. // If mutation observers aren't available, fallback to just-in-time injection.
  221. $( document.documentElement ).on( 'click focus mouseover', linkSelectors, function() {
  222. api.prepareLinkPreview( this );
  223. } );
  224. }
  225. };
  226. /**
  227. * Should the supplied link is previewable.
  228. *
  229. * @since 4.7.0
  230. * @access public
  231. *
  232. * @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
  233. * @param {string} element.search Query string.
  234. * @param {string} element.pathname Path.
  235. * @param {string} element.host Host.
  236. * @param {object} [options]
  237. * @param {object} [options.allowAdminAjax=false] Allow admin-ajax.php requests.
  238. * @returns {boolean} Is appropriate for changeset link.
  239. */
  240. api.isLinkPreviewable = function isLinkPreviewable( element, options ) {
  241. var matchesAllowedUrl, parsedAllowedUrl, args;
  242. args = _.extend( {}, { allowAdminAjax: false }, options || {} );
  243. if ( 'javascript:' === element.protocol ) { // jshint ignore:line
  244. return true;
  245. }
  246. // Only web URLs can be previewed.
  247. if ( 'https:' !== element.protocol && 'http:' !== element.protocol ) {
  248. return false;
  249. }
  250. parsedAllowedUrl = document.createElement( 'a' );
  251. matchesAllowedUrl = ! _.isUndefined( _.find( api.settings.url.allowed, function( allowedUrl ) {
  252. parsedAllowedUrl.href = allowedUrl;
  253. return parsedAllowedUrl.protocol === element.protocol && parsedAllowedUrl.host === element.host && 0 === element.pathname.indexOf( parsedAllowedUrl.pathname.replace( /\/$/, '' ) );
  254. } ) );
  255. if ( ! matchesAllowedUrl ) {
  256. return false;
  257. }
  258. // Skip wp login and signup pages.
  259. if ( /\/wp-(login|signup)\.php$/.test( element.pathname ) ) {
  260. return false;
  261. }
  262. // Allow links to admin ajax as faux frontend URLs.
  263. if ( /\/wp-admin\/admin-ajax\.php$/.test( element.pathname ) ) {
  264. return args.allowAdminAjax;
  265. }
  266. // Disallow links to admin, includes, and content.
  267. if ( /\/wp-(admin|includes|content)(\/|$)/.test( element.pathname ) ) {
  268. return false;
  269. }
  270. return true;
  271. };
  272. /**
  273. * Inject the customize_changeset_uuid query param into links on the frontend.
  274. *
  275. * @since 4.7.0
  276. * @access protected
  277. *
  278. * @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
  279. * @param {string} element.search Query string.
  280. * @param {string} element.host Host.
  281. * @param {string} element.protocol Protocol.
  282. * @returns {void}
  283. */
  284. api.prepareLinkPreview = function prepareLinkPreview( element ) {
  285. var queryParams;
  286. // Skip links in admin bar.
  287. if ( $( element ).closest( '#wpadminbar' ).length ) {
  288. return;
  289. }
  290. // Ignore links with href="#", href="#id", or non-HTTP protocols (e.g. javascript: and mailto:).
  291. if ( '#' === $( element ).attr( 'href' ).substr( 0, 1 ) || ! /^https?:$/.test( element.protocol ) ) {
  292. return;
  293. }
  294. // Make sure links in preview use HTTPS if parent frame uses HTTPS.
  295. if ( api.settings.channel && 'https' === api.preview.scheme.get() && 'http:' === element.protocol && -1 !== api.settings.url.allowedHosts.indexOf( element.host ) ) {
  296. element.protocol = 'https:';
  297. }
  298. if ( ! api.isLinkPreviewable( element ) ) {
  299. // Style link as unpreviewable only if previewing in iframe; if previewing on frontend, links will be allowed to work normally.
  300. if ( api.settings.channel ) {
  301. $( element ).addClass( 'customize-unpreviewable' );
  302. }
  303. return;
  304. }
  305. $( element ).removeClass( 'customize-unpreviewable' );
  306. queryParams = api.utils.parseQueryString( element.search.substring( 1 ) );
  307. queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
  308. if ( ! api.settings.theme.active ) {
  309. queryParams.customize_theme = api.settings.theme.stylesheet;
  310. }
  311. if ( api.settings.channel ) {
  312. queryParams.customize_messenger_channel = api.settings.channel;
  313. }
  314. element.search = $.param( queryParams );
  315. // Prevent links from breaking out of preview iframe.
  316. if ( api.settings.channel ) {
  317. element.target = '_self';
  318. }
  319. };
  320. /**
  321. * Inject the changeset UUID into Ajax requests.
  322. *
  323. * @since 4.7.0
  324. * @access protected
  325. *
  326. * @return {void}
  327. */
  328. api.addRequestPreviewing = function addRequestPreviewing() {
  329. /**
  330. * Rewrite Ajax requests to inject customizer state.
  331. *
  332. * @param {object} options Options.
  333. * @param {string} options.type Type.
  334. * @param {string} options.url URL.
  335. * @param {object} originalOptions Original options.
  336. * @param {XMLHttpRequest} xhr XHR.
  337. * @returns {void}
  338. */
  339. var prefilterAjax = function( options, originalOptions, xhr ) {
  340. var urlParser, queryParams, requestMethod, dirtyValues = {};
  341. urlParser = document.createElement( 'a' );
  342. urlParser.href = options.url;
  343. // Abort if the request is not for this site.
  344. if ( ! api.isLinkPreviewable( urlParser, { allowAdminAjax: true } ) ) {
  345. return;
  346. }
  347. queryParams = api.utils.parseQueryString( urlParser.search.substring( 1 ) );
  348. // Note that _dirty flag will be cleared with changeset updates.
  349. api.each( function( setting ) {
  350. if ( setting._dirty ) {
  351. dirtyValues[ setting.id ] = setting.get();
  352. }
  353. } );
  354. if ( ! _.isEmpty( dirtyValues ) ) {
  355. requestMethod = options.type.toUpperCase();
  356. // Override underlying request method to ensure unsaved changes to changeset can be included (force Backbone.emulateHTTP).
  357. if ( 'POST' !== requestMethod ) {
  358. xhr.setRequestHeader( 'X-HTTP-Method-Override', requestMethod );
  359. queryParams._method = requestMethod;
  360. options.type = 'POST';
  361. }
  362. // Amend the post data with the customized values.
  363. if ( options.data ) {
  364. options.data += '&';
  365. } else {
  366. options.data = '';
  367. }
  368. options.data += $.param( {
  369. customized: JSON.stringify( dirtyValues )
  370. } );
  371. }
  372. // Include customized state query params in URL.
  373. queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
  374. if ( ! api.settings.theme.active ) {
  375. queryParams.customize_theme = api.settings.theme.stylesheet;
  376. }
  377. urlParser.search = $.param( queryParams );
  378. options.url = urlParser.href;
  379. };
  380. $.ajaxPrefilter( prefilterAjax );
  381. };
  382. /**
  383. * Inject changeset UUID into forms, allowing preview to persist through submissions.
  384. *
  385. * @since 4.7.0
  386. * @access protected
  387. *
  388. * @returns {void}
  389. */
  390. api.addFormPreviewing = function addFormPreviewing() {
  391. // Inject inputs for forms in initial document.
  392. $( document.body ).find( 'form' ).each( function() {
  393. api.prepareFormPreview( this );
  394. } );
  395. // Inject inputs for new forms added to the page.
  396. if ( 'undefined' !== typeof MutationObserver ) {
  397. api.mutationObserver = new MutationObserver( function( mutations ) {
  398. _.each( mutations, function( mutation ) {
  399. $( mutation.target ).find( 'form' ).each( function() {
  400. api.prepareFormPreview( this );
  401. } );
  402. } );
  403. } );
  404. api.mutationObserver.observe( document.documentElement, {
  405. childList: true,
  406. subtree: true
  407. } );
  408. }
  409. };
  410. /**
  411. * Inject changeset into form inputs.
  412. *
  413. * @since 4.7.0
  414. * @access protected
  415. *
  416. * @param {HTMLFormElement} form Form.
  417. * @returns {void}
  418. */
  419. api.prepareFormPreview = function prepareFormPreview( form ) {
  420. var urlParser, stateParams = {};
  421. if ( ! form.action ) {
  422. form.action = location.href;
  423. }
  424. urlParser = document.createElement( 'a' );
  425. urlParser.href = form.action;
  426. // Make sure forms in preview use HTTPS if parent frame uses HTTPS.
  427. if ( api.settings.channel && 'https' === api.preview.scheme.get() && 'http:' === urlParser.protocol && -1 !== api.settings.url.allowedHosts.indexOf( urlParser.host ) ) {
  428. urlParser.protocol = 'https:';
  429. form.action = urlParser.href;
  430. }
  431. if ( 'GET' !== form.method.toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
  432. // Style form as unpreviewable only if previewing in iframe; if previewing on frontend, all forms will be allowed to work normally.
  433. if ( api.settings.channel ) {
  434. $( form ).addClass( 'customize-unpreviewable' );
  435. }
  436. return;
  437. }
  438. $( form ).removeClass( 'customize-unpreviewable' );
  439. stateParams.customize_changeset_uuid = api.settings.changeset.uuid;
  440. if ( ! api.settings.theme.active ) {
  441. stateParams.customize_theme = api.settings.theme.stylesheet;
  442. }
  443. if ( api.settings.channel ) {
  444. stateParams.customize_messenger_channel = api.settings.channel;
  445. }
  446. _.each( stateParams, function( value, name ) {
  447. var input = $( form ).find( 'input[name="' + name + '"]' );
  448. if ( input.length ) {
  449. input.val( value );
  450. } else {
  451. $( form ).prepend( $( '<input>', {
  452. type: 'hidden',
  453. name: name,
  454. value: value
  455. } ) );
  456. }
  457. } );
  458. // Prevent links from breaking out of preview iframe.
  459. if ( api.settings.channel ) {
  460. form.target = '_self';
  461. }
  462. };
  463. /**
  464. * Watch current URL and send keep-alive (heartbeat) messages to the parent.
  465. *
  466. * Keep the customizer pane notified that the preview is still alive
  467. * and that the user hasn't navigated to a non-customized URL.
  468. *
  469. * @since 4.7.0
  470. * @access protected
  471. */
  472. api.keepAliveCurrentUrl = ( function() {
  473. var previousPathName = location.pathname,
  474. previousQueryString = location.search.substr( 1 ),
  475. previousQueryParams = null,
  476. stateQueryParams = [ 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel' ];
  477. return function keepAliveCurrentUrl() {
  478. var urlParser, currentQueryParams;
  479. // Short-circuit with keep-alive if previous URL is identical (as is normal case).
  480. if ( previousQueryString === location.search.substr( 1 ) && previousPathName === location.pathname ) {
  481. api.preview.send( 'keep-alive' );
  482. return;
  483. }
  484. urlParser = document.createElement( 'a' );
  485. if ( null === previousQueryParams ) {
  486. urlParser.search = previousQueryString;
  487. previousQueryParams = api.utils.parseQueryString( previousQueryString );
  488. _.each( stateQueryParams, function( name ) {
  489. delete previousQueryParams[ name ];
  490. } );
  491. }
  492. // Determine if current URL minus customized state params and URL hash.
  493. urlParser.href = location.href;
  494. currentQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
  495. _.each( stateQueryParams, function( name ) {
  496. delete currentQueryParams[ name ];
  497. } );
  498. if ( previousPathName !== location.pathname || ! _.isEqual( previousQueryParams, currentQueryParams ) ) {
  499. urlParser.search = $.param( currentQueryParams );
  500. urlParser.hash = '';
  501. api.settings.url.self = urlParser.href;
  502. api.preview.send( 'ready', {
  503. currentUrl: api.settings.url.self,
  504. activePanels: api.settings.activePanels,
  505. activeSections: api.settings.activeSections,
  506. activeControls: api.settings.activeControls,
  507. settingValidities: api.settings.settingValidities
  508. } );
  509. } else {
  510. api.preview.send( 'keep-alive' );
  511. }
  512. previousQueryParams = currentQueryParams;
  513. previousQueryString = location.search.substr( 1 );
  514. previousPathName = location.pathname;
  515. };
  516. } )();
  517. api.settingPreviewHandlers = {
  518. /**
  519. * Preview changes to custom logo.
  520. *
  521. * @param {number} attachmentId Attachment ID for custom logo.
  522. * @returns {void}
  523. */
  524. custom_logo: function( attachmentId ) {
  525. $( 'body' ).toggleClass( 'wp-custom-logo', !! attachmentId );
  526. },
  527. /**
  528. * Preview changes to custom css.
  529. *
  530. * @param {string} value Custom CSS..
  531. * @returns {void}
  532. */
  533. custom_css: function( value ) {
  534. $( '#wp-custom-css' ).text( value );
  535. },
  536. /**
  537. * Preview changes to any of the background settings.
  538. *
  539. * @returns {void}
  540. */
  541. background: function() {
  542. var css = '', settings = {};
  543. _.each( ['color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment'], function( prop ) {
  544. settings[ prop ] = api( 'background_' + prop );
  545. } );
  546. /*
  547. * The body will support custom backgrounds if either the color or image are set.
  548. *
  549. * See get_body_class() in /wp-includes/post-template.php
  550. */
  551. $( document.body ).toggleClass( 'custom-background', !! ( settings.color() || settings.image() ) );
  552. if ( settings.color() ) {
  553. css += 'background-color: ' + settings.color() + ';';
  554. }
  555. if ( settings.image() ) {
  556. css += 'background-image: url("' + settings.image() + '");';
  557. css += 'background-size: ' + settings.size() + ';';
  558. css += 'background-position: ' + settings.position_x() + ' ' + settings.position_y() + ';';
  559. css += 'background-repeat: ' + settings.repeat() + ';';
  560. css += 'background-attachment: ' + settings.attachment() + ';';
  561. }
  562. $( '#custom-background-css' ).text( 'body.custom-background { ' + css + ' }' );
  563. }
  564. };
  565. $( function() {
  566. var bg, setValue;
  567. api.settings = window._wpCustomizeSettings;
  568. if ( ! api.settings ) {
  569. return;
  570. }
  571. api.preview = new api.Preview({
  572. url: window.location.href,
  573. channel: api.settings.channel
  574. });
  575. api.addLinkPreviewing();
  576. api.addRequestPreviewing();
  577. api.addFormPreviewing();
  578. /**
  579. * Create/update a setting value.
  580. *
  581. * @param {string} id - Setting ID.
  582. * @param {*} value - Setting value.
  583. * @param {boolean} [createDirty] - Whether to create a setting as dirty. Defaults to false.
  584. */
  585. setValue = function( id, value, createDirty ) {
  586. var setting = api( id );
  587. if ( setting ) {
  588. setting.set( value );
  589. } else {
  590. createDirty = createDirty || false;
  591. setting = api.create( id, value, {
  592. id: id
  593. } );
  594. // Mark dynamically-created settings as dirty so they will get posted.
  595. if ( createDirty ) {
  596. setting._dirty = true;
  597. }
  598. }
  599. };
  600. api.preview.bind( 'settings', function( values ) {
  601. $.each( values, setValue );
  602. });
  603. api.preview.trigger( 'settings', api.settings.values );
  604. $.each( api.settings._dirty, function( i, id ) {
  605. var setting = api( id );
  606. if ( setting ) {
  607. setting._dirty = true;
  608. }
  609. } );
  610. api.preview.bind( 'setting', function( args ) {
  611. var createDirty = true;
  612. setValue.apply( null, args.concat( createDirty ) );
  613. });
  614. api.preview.bind( 'sync', function( events ) {
  615. /*
  616. * Delete any settings that already exist locally which haven't been
  617. * modified in the controls while the preview was loading. This prevents
  618. * situations where the JS value being synced from the pane may differ
  619. * from the PHP-sanitized JS value in the preview which causes the
  620. * non-sanitized JS value to clobber the PHP-sanitized value. This
  621. * is particularly important for selective refresh partials that
  622. * have a fallback refresh behavior since infinite refreshing would
  623. * result.
  624. */
  625. if ( events.settings && events['settings-modified-while-loading'] ) {
  626. _.each( _.keys( events.settings ), function( syncedSettingId ) {
  627. if ( api.has( syncedSettingId ) && ! events['settings-modified-while-loading'][ syncedSettingId ] ) {
  628. delete events.settings[ syncedSettingId ];
  629. }
  630. } );
  631. }
  632. $.each( events, function( event, args ) {
  633. api.preview.trigger( event, args );
  634. });
  635. api.preview.send( 'synced' );
  636. });
  637. api.preview.bind( 'active', function() {
  638. api.preview.send( 'nonce', api.settings.nonce );
  639. api.preview.send( 'documentTitle', document.title );
  640. // Send scroll in case of loading via non-refresh.
  641. api.preview.send( 'scroll', $( window ).scrollTop() );
  642. });
  643. api.preview.bind( 'saved', function( response ) {
  644. if ( response.next_changeset_uuid ) {
  645. api.settings.changeset.uuid = response.next_changeset_uuid;
  646. // Update UUIDs in links and forms.
  647. $( document.body ).find( 'a[href], area' ).each( function() {
  648. api.prepareLinkPreview( this );
  649. } );
  650. $( document.body ).find( 'form' ).each( function() {
  651. api.prepareFormPreview( this );
  652. } );
  653. /*
  654. * Replace the UUID in the URL. Note that the wrapped history.replaceState()
  655. * will handle injecting the current api.settings.changeset.uuid into the URL,
  656. * so this is merely to trigger that logic.
  657. */
  658. if ( history.replaceState ) {
  659. history.replaceState( currentHistoryState, '', location.href );
  660. }
  661. }
  662. api.trigger( 'saved', response );
  663. } );
  664. /*
  665. * Clear dirty flag for settings when saved to changeset so that they
  666. * won't be needlessly included in selective refresh or ajax requests.
  667. */
  668. api.preview.bind( 'changeset-saved', function( data ) {
  669. _.each( data.saved_changeset_values, function( value, settingId ) {
  670. var setting = api( settingId );
  671. if ( setting && _.isEqual( setting.get(), value ) ) {
  672. setting._dirty = false;
  673. }
  674. } );
  675. } );
  676. api.preview.bind( 'nonce-refresh', function( nonce ) {
  677. $.extend( api.settings.nonce, nonce );
  678. } );
  679. /*
  680. * Send a message to the parent customize frame with a list of which
  681. * containers and controls are active.
  682. */
  683. api.preview.send( 'ready', {
  684. currentUrl: api.settings.url.self,
  685. activePanels: api.settings.activePanels,
  686. activeSections: api.settings.activeSections,
  687. activeControls: api.settings.activeControls,
  688. settingValidities: api.settings.settingValidities
  689. } );
  690. // Send ready when URL changes via JS.
  691. setInterval( api.keepAliveCurrentUrl, api.settings.timeouts.keepAliveSend );
  692. // Display a loading indicator when preview is reloading, and remove on failure.
  693. api.preview.bind( 'loading-initiated', function () {
  694. $( 'body' ).addClass( 'wp-customizer-unloading' );
  695. });
  696. api.preview.bind( 'loading-failed', function () {
  697. $( 'body' ).removeClass( 'wp-customizer-unloading' );
  698. });
  699. /* Custom Backgrounds */
  700. bg = $.map( ['color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment'], function( prop ) {
  701. return 'background_' + prop;
  702. } );
  703. api.when.apply( api, bg ).done( function() {
  704. $.each( arguments, function() {
  705. this.bind( api.settingPreviewHandlers.background );
  706. });
  707. });
  708. /**
  709. * Custom Logo
  710. *
  711. * Toggle the wp-custom-logo body class when a logo is added or removed.
  712. *
  713. * @since 4.5.0
  714. */
  715. api( 'custom_logo', function ( setting ) {
  716. api.settingPreviewHandlers.custom_logo.call( setting, setting.get() );
  717. setting.bind( api.settingPreviewHandlers.custom_logo );
  718. } );
  719. api( 'custom_css[' + api.settings.theme.stylesheet + ']', function( setting ) {
  720. setting.bind( api.settingPreviewHandlers.custom_css );
  721. } );
  722. api.trigger( 'preview-ready' );
  723. });
  724. })( wp, jQuery );