customize-preview.js 27 KB

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