customize-preview.js 27 KB

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