Customize: Implement customized state persistence with changesets.

Includes infrastructure developed in the Customize Snapshots feature plugin.

See https://make.wordpress.org/core/2016/10/12/customize-changesets-technical-design-decisions/

Props westonruter, valendesigns, utkarshpatel, stubgo, lgedeon, ocean90, ryankienstra, mihai2u, dlh, aaroncampbell, jonathanbardo, jorbin.
See #28721.
See #31089.
Fixes #30937.
Fixes #31517.
Fixes #30028.
Fixes #23225.
Fixes #34142.
Fixes #36485.

Built from https://develop.svn.wordpress.org/trunk@38810


git-svn-id: http://core.svn.wordpress.org/trunk@38753 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Weston Ruter 2016-10-18 20:05:31 +00:00
parent f6d85de626
commit f1ba1918c9
30 changed files with 2885 additions and 517 deletions

View File

@ -20,6 +20,31 @@ if ( ! current_user_can( 'customize' ) ) {
);
}
/**
* @global WP_Scripts $wp_scripts
* @global WP_Customize_Manager $wp_customize
*/
global $wp_scripts, $wp_customize;
if ( $wp_customize->changeset_post_id() ) {
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $wp_customize->changeset_post_id() ) ) {
wp_die(
'<h1>' . __( 'Cheatin&#8217; uh?' ) . '</h1>' .
'<p>' . __( 'Sorry, you are not allowed to edit this changeset.' ) . '</p>',
403
);
}
if ( in_array( get_post_status( $wp_customize->changeset_post_id() ), array( 'publish', 'trash' ), true ) ) {
wp_die(
'<h1>' . __( 'Cheatin&#8217; uh?' ) . '</h1>' .
'<p>' . __( 'This changeset has already been published and cannot be further modified.' ) . '</p>' .
'<p><a href="' . esc_url( remove_query_arg( 'changeset_uuid' ) ) . '">' . __( 'Customize New Changes' ) . '</a></p>',
403
);
}
}
wp_reset_vars( array( 'url', 'return', 'autofocus' ) );
if ( ! empty( $url ) ) {
$wp_customize->set_preview_url( wp_unslash( $url ) );
@ -31,12 +56,6 @@ if ( ! empty( $autofocus ) && is_array( $autofocus ) ) {
$wp_customize->set_autofocus( wp_unslash( $autofocus ) );
}
/**
* @global WP_Scripts $wp_scripts
* @global WP_Customize_Manager $wp_customize
*/
global $wp_scripts, $wp_customize;
$registered = $wp_scripts->registered;
$wp_scripts = new WP_Scripts;
$wp_scripts->registered = $registered;
@ -115,7 +134,11 @@ do_action( 'customize_controls_print_scripts' );
<div id="customize-header-actions" class="wp-full-overlay-header">
<?php
$save_text = $wp_customize->is_theme_active() ? __( 'Save &amp; Publish' ) : __( 'Save &amp; Activate' );
submit_button( $save_text, 'primary save', 'save', false );
$save_attrs = array();
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) {
$save_attrs['style'] = 'display: none';
}
submit_button( $save_text, 'primary save', 'save', false, $save_attrs );
?>
<span class="spinner"></span>
<button type="button" class="customize-controls-preview-toggle">

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1154,7 +1154,7 @@
params.action = 'update-widget';
params.wp_customize = 'on';
params.nonce = api.settings.nonce['update-widget'];
params.theme = api.settings.theme.stylesheet;
params.customize_theme = api.settings.theme.stylesheet;
params.customized = wp.customize.previewer.query().customized;
data = $.param( params );

File diff suppressed because one or more lines are too long

View File

@ -366,15 +366,30 @@ function wp_admin_bar_site_menu( $wp_admin_bar ) {
* @since 4.3.0
*
* @param WP_Admin_Bar $wp_admin_bar WP_Admin_Bar instance.
* @global WP_Customize_Manager $wp_customize
*/
function wp_admin_bar_customize_menu( $wp_admin_bar ) {
global $wp_customize;
// Don't show for users who can't access the customizer or when in the admin.
if ( ! current_user_can( 'customize' ) || is_admin() ) {
return;
}
// Don't show if the user cannot edit a given customize_changeset post currently being previewed.
if ( is_customize_preview() && $wp_customize->changeset_post_id() && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $wp_customize->changeset_post_id() ) ) {
return;
}
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ( is_customize_preview() && $wp_customize->changeset_uuid() ) {
$current_url = remove_query_arg( 'customize_changeset_uuid', $current_url );
}
$customize_url = add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() );
if ( is_customize_preview() ) {
$customize_url = add_query_arg( array( 'changeset_uuid' => $wp_customize->changeset_uuid() ), $customize_url );
}
$wp_admin_bar->add_menu( array(
'id' => 'customize',

File diff suppressed because it is too large Load Diff

View File

@ -48,7 +48,12 @@ final class WP_Customize_Nav_Menus {
$this->previewed_menus = array();
$this->manager = $manager;
// Skip useless hooks when the user can't manage nav menus anyway.
// See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L469-L499
add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
// Skip remaining hooks when the user can't manage nav menus anyway.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
@ -58,9 +63,6 @@ final class WP_Customize_Nav_Menus {
add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
add_action( 'wp_ajax_customize-nav-menus-insert-auto-draft', array( $this, 'ajax_insert_auto_draft_post' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_templates' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'available_items_template' ) );
add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
@ -486,6 +488,23 @@ final class WP_Customize_Nav_Menus {
*/
public function customize_register() {
/*
* Preview settings for nav menus early so that the sections and controls will be added properly.
* See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L506-L543
*/
$nav_menus_setting_ids = array();
foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) {
$nav_menus_setting_ids[] = $setting_id;
}
}
foreach ( $nav_menus_setting_ids as $setting_id ) {
$setting = $this->manager->get_setting( $setting_id );
if ( $setting ) {
$setting->preview();
}
}
// Require JS-rendered control types.
$this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
$this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );

View File

@ -93,16 +93,18 @@ final class WP_Customize_Widgets {
public function __construct( $manager ) {
$this->manager = $manager;
// Skip useless hooks when the user can't manage widgets anyway.
// See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
// Skip remaining hooks when the user can't manage widgets anyway.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
@ -276,6 +278,7 @@ final class WP_Customize_Widgets {
$this->old_sidebars_widgets = wp_get_sidebars_widgets();
add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
$this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
// retrieve_widgets() looks at the global $sidebars_widgets
$sidebars_widgets = $this->old_sidebars_widgets;

View File

@ -307,8 +307,6 @@ final class WP_Customize_Selective_Refresh {
return;
}
$this->manager->remove_preview_signature();
/*
* Note that is_customize_preview() returning true will entail that the
* user passed the 'customize' capability check and the nonce check, since

View File

@ -63,8 +63,8 @@ class WP_Customize_Theme_Control extends WP_Customize_Control {
*/
public function content_template() {
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$active_url = esc_url( remove_query_arg( 'theme', $current_url ) );
$preview_url = esc_url( add_query_arg( 'theme', '__THEME__', $current_url ) ); // Token because esc_url() strips curly braces.
$active_url = esc_url( remove_query_arg( 'customize_theme', $current_url ) );
$preview_url = esc_url( add_query_arg( 'customize_theme', '__THEME__', $current_url ) ); // Token because esc_url() strips curly braces.
$preview_url = str_replace( '__THEME__', '{{ data.theme.id }}', $preview_url );
?>
<# if ( data.theme.isActiveTheme ) { #>

View File

@ -75,6 +75,7 @@ foreach ( array( 'user_url', 'link_url', 'link_image', 'link_rss', 'comment_url'
// Slugs
add_filter( 'pre_term_slug', 'sanitize_title' );
add_filter( 'wp_insert_post_data', '_wp_customize_changeset_filter_insert_post_data', 10, 2 );
// Keys
foreach ( array( 'pre_post_type', 'pre_post_status', 'pre_post_comment_status', 'pre_post_ping_status' ) as $filter ) {
@ -382,6 +383,7 @@ add_action( 'parse_request', 'rest_api_loaded' );
add_action( 'wp_loaded', '_custom_header_background_just_in_time' );
add_action( 'wp_head', '_custom_logo_header_styles' );
add_action( 'plugins_loaded', '_wp_customize_include' );
add_action( 'transition_post_status', '_wp_customize_publish_changeset', 10, 3 );
add_action( 'admin_enqueue_scripts', '_wp_customize_loader_settings' );
add_action( 'delete_attachment', '_delete_attachment_theme_mod' );

View File

@ -5523,3 +5523,20 @@ function wp_raise_memory_limit( $context = 'admin' ) {
return false;
}
/**
* Generate a random UUID (version 4).
*
* @since 4.7.0
*
* @return string UUID.
*/
function wp_generate_uuid4() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}

View File

@ -34,7 +34,7 @@ function wp_scripts() {
* @param string $function Function name.
*/
function _wp_scripts_maybe_doing_it_wrong( $function ) {
if ( did_action( 'init' ) ) {
if ( did_action( 'init' ) || did_action( 'admin_enqueue_scripts' ) || did_action( 'wp_enqueue_scripts' ) || did_action( 'login_enqueue_scripts' ) ) {
return;
}

View File

@ -637,22 +637,24 @@ window.wp = window.wp || {};
/**
* Initialize Messenger.
*
* @param {object} params Parameters to configure the messenger.
* {string} .url The URL to communicate with.
* {window} .targetWindow The window instance to communicate with. Default window.parent.
* {string} .channel If provided, will send the channel with each message and only accept messages a matching channel.
* @param {object} options Extend any instance parameter or method with this object.
* @param {object} params - Parameters to configure the messenger.
* {string} params.url - The URL to communicate with.
* {window} params.targetWindow - The window instance to communicate with. Default window.parent.
* {string} params.channel - If provided, will send the channel with each message and only accept messages a matching channel.
* @param {object} options - Extend any instance parameter or method with this object.
*/
initialize: function( params, options ) {
// Target the parent frame by default, but only if a parent frame exists.
var defaultTarget = window.parent == window ? null : window.parent;
var defaultTarget = window.parent === window ? null : window.parent;
$.extend( this, options || {} );
this.add( 'channel', params.channel );
this.add( 'url', params.url || '' );
this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
var urlParser = document.createElement( 'a' );
urlParser.href = to;
return urlParser.protocol + '//' + urlParser.hostname;
});
// first add with no value
@ -807,6 +809,40 @@ window.wp = window.wp || {};
return result;
};
/**
* Utility function namespace
*/
api.utils = {};
/**
* Parse query string.
*
* @since 4.7.0
* @access public
*
* @param {string} queryString Query string.
* @returns {object} Parsed query string.
*/
api.utils.parseQueryString = function parseQueryString( queryString ) {
var queryParams = {};
_.each( queryString.split( '&' ), function( pair ) {
var parts, key, value;
parts = pair.split( '=', 2 );
if ( ! parts[0] ) {
return;
}
key = decodeURIComponent( parts[0].replace( /\+/g, ' ' ) );
key = key.replace( / /g, '_' ); // What PHP does.
if ( _.isUndefined( parts[1] ) ) {
value = null;
} else {
value = decodeURIComponent( parts[1].replace( /\+/g, ' ' ) );
}
queryParams[ key ] = value;
} );
return queryParams;
};
// Expose the API publicly on window.wp.customize
exports.customize = api;
})( wp, jQuery );

File diff suppressed because one or more lines are too long

View File

@ -132,6 +132,19 @@ window.wp = window.wp || {};
targetWindow: this.iframe[0].contentWindow
});
// Expose the changeset UUID on the parent window's URL so that the customized state can survive a refresh.
if ( history.replaceState ) {
this.messenger.bind( 'changeset-uuid', function( changesetUuid ) {
var urlParser = document.createElement( 'a' );
urlParser.href = location.href;
urlParser.search = $.param( _.extend(
api.utils.parseQueryString( urlParser.search.substr( 1 ) ),
{ changeset_uuid: changesetUuid }
) );
history.replaceState( { customize: urlParser.href }, '', urlParser.href );
} );
}
// Wait for the connection from the iframe before sending any postMessage events.
this.messenger.bind( 'ready', function() {
Loader.messenger.send( 'back' );

View File

@ -1 +1 @@
window.wp=window.wp||{},function(a,b){var c,d=wp.customize;b.extend(b.support,{history:!(!window.history||!history.pushState),hashchange:"onhashchange"in window&&(void 0===document.documentMode||document.documentMode>7)}),c=b.extend({},d.Events,{initialize:function(){this.body=b(document.body),c.settings&&b.support.postMessage&&(b.support.cors||!c.settings.isCrossDomain)&&(this.window=b(window),this.element=b('<div id="customize-container" />').appendTo(this.body),this.bind("open",this.overlay.show),this.bind("close",this.overlay.hide),b("#wpbody").on("click",".load-customize",function(a){a.preventDefault(),c.link=b(this),c.open(c.link.attr("href"))}),b.support.history&&this.window.on("popstate",c.popstate),b.support.hashchange&&(this.window.on("hashchange",c.hashchange),this.window.triggerHandler("hashchange")))},popstate:function(a){var b=a.originalEvent.state;b&&b.customize?c.open(b.customize):c.active&&c.close()},hashchange:function(){var a=window.location.toString().split("#")[1];a&&0===a.indexOf("wp_customize=on")&&c.open(c.settings.url+"?"+a),a||b.support.history||c.close()},beforeunload:function(){return c.saved()?void 0:c.settings.l10n.saveAlert},open:function(a){if(!this.active){if(c.settings.browser.mobile)return window.location=a;this.originalDocumentTitle=document.title,this.active=!0,this.body.addClass("customize-loading"),this.saved=new d.Value(!0),this.iframe=b("<iframe />",{src:a,title:c.settings.l10n.mainIframeTitle}).appendTo(this.element),this.iframe.one("load",this.loaded),this.messenger=new d.Messenger({url:a,channel:"loader",targetWindow:this.iframe[0].contentWindow}),this.messenger.bind("ready",function(){c.messenger.send("back")}),this.messenger.bind("close",function(){b.support.history?history.back():b.support.hashchange?window.location.hash="":c.close()}),b(window).on("beforeunload",this.beforeunload),this.messenger.bind("saved",function(){c.saved(!0)}),this.messenger.bind("change",function(){c.saved(!1)}),this.messenger.bind("title",function(a){window.document.title=a}),this.pushState(a),this.trigger("open")}},pushState:function(a){var c=a.split("?")[1];b.support.history&&window.location.href!==a?history.pushState({customize:a},"",a):!b.support.history&&b.support.hashchange&&c&&(window.location.hash="wp_customize=on&"+c),this.trigger("open")},opened:function(){c.body.addClass("customize-active full-overlay-active").attr("aria-busy","true")},close:function(){if(this.active){if(!this.saved()&&!confirm(c.settings.l10n.saveAlert))return void history.forward();this.active=!1,this.trigger("close"),this.originalDocumentTitle&&(document.title=this.originalDocumentTitle)}},closed:function(){c.iframe.remove(),c.messenger.destroy(),c.iframe=null,c.messenger=null,c.saved=null,c.body.removeClass("customize-active full-overlay-active").removeClass("customize-loading"),b(window).off("beforeunload",c.beforeunload),c.link&&c.link.focus()},loaded:function(){c.body.removeClass("customize-loading").attr("aria-busy","false")},overlay:{show:function(){this.element.fadeIn(200,c.opened)},hide:function(){this.element.fadeOut(200,c.closed)}}}),b(function(){c.settings=_wpCustomizeLoaderSettings,c.initialize()}),d.Loader=c}(wp,jQuery);
window.wp=window.wp||{},function(a,b){var c,d=wp.customize;b.extend(b.support,{history:!(!window.history||!history.pushState),hashchange:"onhashchange"in window&&(void 0===document.documentMode||document.documentMode>7)}),c=b.extend({},d.Events,{initialize:function(){this.body=b(document.body),c.settings&&b.support.postMessage&&(b.support.cors||!c.settings.isCrossDomain)&&(this.window=b(window),this.element=b('<div id="customize-container" />').appendTo(this.body),this.bind("open",this.overlay.show),this.bind("close",this.overlay.hide),b("#wpbody").on("click",".load-customize",function(a){a.preventDefault(),c.link=b(this),c.open(c.link.attr("href"))}),b.support.history&&this.window.on("popstate",c.popstate),b.support.hashchange&&(this.window.on("hashchange",c.hashchange),this.window.triggerHandler("hashchange")))},popstate:function(a){var b=a.originalEvent.state;b&&b.customize?c.open(b.customize):c.active&&c.close()},hashchange:function(){var a=window.location.toString().split("#")[1];a&&0===a.indexOf("wp_customize=on")&&c.open(c.settings.url+"?"+a),a||b.support.history||c.close()},beforeunload:function(){return c.saved()?void 0:c.settings.l10n.saveAlert},open:function(a){if(!this.active){if(c.settings.browser.mobile)return window.location=a;this.originalDocumentTitle=document.title,this.active=!0,this.body.addClass("customize-loading"),this.saved=new d.Value(!0),this.iframe=b("<iframe />",{src:a,title:c.settings.l10n.mainIframeTitle}).appendTo(this.element),this.iframe.one("load",this.loaded),this.messenger=new d.Messenger({url:a,channel:"loader",targetWindow:this.iframe[0].contentWindow}),history.replaceState&&this.messenger.bind("changeset-uuid",function(a){var c=document.createElement("a");c.href=location.href,c.search=b.param(_.extend(d.utils.parseQueryString(c.search.substr(1)),{changeset_uuid:a})),history.replaceState({customize:c.href},"",c.href)}),this.messenger.bind("ready",function(){c.messenger.send("back")}),this.messenger.bind("close",function(){b.support.history?history.back():b.support.hashchange?window.location.hash="":c.close()}),b(window).on("beforeunload",this.beforeunload),this.messenger.bind("saved",function(){c.saved(!0)}),this.messenger.bind("change",function(){c.saved(!1)}),this.messenger.bind("title",function(a){window.document.title=a}),this.pushState(a),this.trigger("open")}},pushState:function(a){var c=a.split("?")[1];b.support.history&&window.location.href!==a?history.pushState({customize:a},"",a):!b.support.history&&b.support.hashchange&&c&&(window.location.hash="wp_customize=on&"+c),this.trigger("open")},opened:function(){c.body.addClass("customize-active full-overlay-active").attr("aria-busy","true")},close:function(){if(this.active){if(!this.saved()&&!confirm(c.settings.l10n.saveAlert))return void history.forward();this.active=!1,this.trigger("close"),this.originalDocumentTitle&&(document.title=this.originalDocumentTitle)}},closed:function(){c.iframe.remove(),c.messenger.destroy(),c.iframe=null,c.messenger=null,c.saved=null,c.body.removeClass("customize-active full-overlay-active").removeClass("customize-loading"),b(window).off("beforeunload",c.beforeunload),c.link&&c.link.focus()},loaded:function(){c.body.removeClass("customize-loading").attr("aria-busy","false")},overlay:{show:function(){this.element.fadeIn(200,c.opened)},hide:function(){this.element.fadeOut(200,c.closed)}}}),b(function(){c.settings=_wpCustomizeLoaderSettings,c.initialize()}),d.Loader=c}(wp,jQuery);

View File

@ -106,7 +106,7 @@ wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function(
* @returns {boolean}
*/
isRelatedSetting: function( setting, newValue, oldValue ) {
var partial = this, navMenuLocationSetting, navMenuId, isNavMenuItemSetting;
var partial = this, navMenuLocationSetting, navMenuId, isNavMenuItemSetting, _newValue, _oldValue, urlParser;
if ( _.isString( setting ) ) {
setting = api( setting );
}
@ -123,9 +123,23 @@ wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function(
*/
isNavMenuItemSetting = /^nav_menu_item\[/.test( setting.id );
if ( isNavMenuItemSetting && _.isObject( newValue ) && _.isObject( oldValue ) ) {
delete newValue.type_label;
delete oldValue.type_label;
if ( _.isEqual( oldValue, newValue ) ) {
_newValue = _.clone( newValue );
_oldValue = _.clone( oldValue );
delete _newValue.type_label;
delete _oldValue.type_label;
// Normalize URL scheme when parent frame is HTTPS to prevent selective refresh upon initial page load.
if ( 'https' === api.preview.scheme.get() ) {
urlParser = document.createElement( 'a' );
urlParser.href = _newValue.url;
urlParser.protocol = 'https:';
_newValue.url = urlParser.href;
urlParser.href = _oldValue.url;
urlParser.protocol = 'https:';
_oldValue.url = urlParser.href;
}
if ( _.isEqual( _oldValue, _newValue ) ) {
return false;
}
}
@ -365,6 +379,11 @@ wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function(
self.highlightControls = function() {
var selector = '.menu-item';
// Skip adding highlights if not in the customizer preview iframe.
if ( ! api.settings.channel ) {
return;
}
// Focus on the menu item control when shift+clicking the menu item.
$( document ).on( 'click', selector, function( e ) {
var navMenuItemParts;

View File

@ -1 +1 @@
wp.customize.navMenusPreview=wp.customize.MenusCustomizerPreview=function(a,b,c,d){"use strict";var e={data:{navMenuInstanceArgs:{}}};return"undefined"!=typeof _wpCustomizePreviewNavMenusExports&&b.extend(e.data,_wpCustomizePreviewNavMenusExports),e.init=function(){var a=this;d.selectiveRefresh&&(d.each(function(b){a.bindSettingListener(b)}),d.bind("add",function(b){a.bindSettingListener(b,{fire:!0})}),d.bind("remove",function(b){a.unbindSettingListener(b)}),d.selectiveRefresh.bind("render-partials-response",function(c){c.nav_menu_instance_args&&b.extend(a.data.navMenuInstanceArgs,c.nav_menu_instance_args)})),d.preview.bind("active",function(){a.highlightControls()})},d.selectiveRefresh&&(e.NavMenuInstancePartial=d.selectiveRefresh.Partial.extend({initialize:function(a,c){var e,f,g=this;if(e=a.match(/^nav_menu_instance\[([0-9a-f]{32})]$/),!e)throw new Error("Illegal id for nav_menu_instance partial. The key corresponds with the args HMAC.");if(f=e[1],c=c||{},c.params=b.extend({selector:'[data-customize-partial-id="'+a+'"]',navMenuArgs:c.constructingContainerContext||{},containerInclusive:!0},c.params||{}),d.selectiveRefresh.Partial.prototype.initialize.call(g,a,c),!b.isObject(g.params.navMenuArgs))throw new Error("Missing navMenuArgs");if(g.params.navMenuArgs.args_hmac!==f)throw new Error("args_hmac mismatch with id")},isRelatedSetting:function(a,c,e){var f,g,h,i=this;if(b.isString(a)&&(a=d(a)),h=/^nav_menu_item\[/.test(a.id),h&&b.isObject(c)&&b.isObject(e)&&(delete c.type_label,delete e.type_label,b.isEqual(e,c)))return!1;if(i.params.navMenuArgs.theme_location){if("nav_menu_locations["+i.params.navMenuArgs.theme_location+"]"===a.id)return!0;f=d("nav_menu_locations["+i.params.navMenuArgs.theme_location+"]")}return g=i.params.navMenuArgs.menu,!g&&f&&(g=f()),g?"nav_menu["+g+"]"===a.id||h&&(c&&c.nav_menu_term_id===g||e&&e.nav_menu_term_id===g):!1},refresh:function(){var c,e=this,f=a.Deferred();return b.isNumber(e.params.navMenuArgs.menu)?c=e.params.navMenuArgs.menu:e.params.navMenuArgs.theme_location&&d.has("nav_menu_locations["+e.params.navMenuArgs.theme_location+"]")&&(c=d("nav_menu_locations["+e.params.navMenuArgs.theme_location+"]").get()),c?d.selectiveRefresh.Partial.prototype.refresh.call(e):(e.fallback(),f.reject(),f.promise())},renderContent:function(b){var c=this,e=b.container;""===b.addedContent&&b.partial.fallback(),d.selectiveRefresh.Partial.prototype.renderContent.call(c,b)&&a(document).trigger("customize-preview-menu-refreshed",[{instanceNumber:null,wpNavArgs:b.context,wpNavMenuArgs:b.context,oldContainer:e,newContainer:b.container}])}}),d.selectiveRefresh.partialConstructor.nav_menu_instance=e.NavMenuInstancePartial,e.handleUnplacedNavMenuInstances=function(a){var c;return c=b.filter(b.values(e.data.navMenuInstanceArgs),function(a){return!d.selectiveRefresh.partial.has("nav_menu_instance["+a.args_hmac+"]")}),b.findWhere(c,a)?(d.selectiveRefresh.requestFullRefresh(),!0):!1},e.bindSettingListener=function(a,b){var c;return b=b||{},(c=a.id.match(/^nav_menu\[(-?\d+)]$/))?(a._navMenuId=parseInt(c[1],10),a.bind(this.onChangeNavMenuSetting),b.fire&&this.onChangeNavMenuSetting.call(a,a(),!1),!0):(c=a.id.match(/^nav_menu_item\[(-?\d+)]$/))?(a._navMenuItemId=parseInt(c[1],10),a.bind(this.onChangeNavMenuItemSetting),b.fire&&this.onChangeNavMenuItemSetting.call(a,a(),!1),!0):(c=a.id.match(/^nav_menu_locations\[(.+?)]/),c?(a._navMenuThemeLocation=c[1],a.bind(this.onChangeNavMenuLocationsSetting),b.fire&&this.onChangeNavMenuLocationsSetting.call(a,a(),!1),!0):!1)},e.unbindSettingListener=function(a){a.unbind(this.onChangeNavMenuSetting),a.unbind(this.onChangeNavMenuItemSetting),a.unbind(this.onChangeNavMenuLocationsSetting)},e.onChangeNavMenuSetting=function(){var a=this;e.handleUnplacedNavMenuInstances({menu:a._navMenuId}),d.each(function(b){b._navMenuThemeLocation&&a._navMenuId===b()&&e.handleUnplacedNavMenuInstances({theme_location:b._navMenuThemeLocation})})},e.onChangeNavMenuItemSetting=function(a,b){var c,f=a||b;c=d("nav_menu["+String(f.nav_menu_term_id)+"]"),c&&e.onChangeNavMenuSetting.call(c)},e.onChangeNavMenuLocationsSetting=function(){var a,c=this;e.handleUnplacedNavMenuInstances({theme_location:c._navMenuThemeLocation}),a=!!b.findWhere(b.values(e.data.navMenuInstanceArgs),{theme_location:c._navMenuThemeLocation}),a||d.selectiveRefresh.requestFullRefresh()}),e.highlightControls=function(){var b=".menu-item";a(document).on("click",b,function(b){var c;b.shiftKey&&(c=a(this).attr("class").match(/(?:^|\s)menu-item-(\d+)(?:\s|$)/),c&&(b.preventDefault(),b.stopPropagation(),d.preview.send("focus-nav-menu-item-control",parseInt(c[1],10))))})},d.bind("preview-ready",function(){e.init()}),e}(jQuery,_,wp,wp.customize);
wp.customize.navMenusPreview=wp.customize.MenusCustomizerPreview=function(a,b,c,d){"use strict";var e={data:{navMenuInstanceArgs:{}}};return"undefined"!=typeof _wpCustomizePreviewNavMenusExports&&b.extend(e.data,_wpCustomizePreviewNavMenusExports),e.init=function(){var a=this;d.selectiveRefresh&&(d.each(function(b){a.bindSettingListener(b)}),d.bind("add",function(b){a.bindSettingListener(b,{fire:!0})}),d.bind("remove",function(b){a.unbindSettingListener(b)}),d.selectiveRefresh.bind("render-partials-response",function(c){c.nav_menu_instance_args&&b.extend(a.data.navMenuInstanceArgs,c.nav_menu_instance_args)})),d.preview.bind("active",function(){a.highlightControls()})},d.selectiveRefresh&&(e.NavMenuInstancePartial=d.selectiveRefresh.Partial.extend({initialize:function(a,c){var e,f,g=this;if(e=a.match(/^nav_menu_instance\[([0-9a-f]{32})]$/),!e)throw new Error("Illegal id for nav_menu_instance partial. The key corresponds with the args HMAC.");if(f=e[1],c=c||{},c.params=b.extend({selector:'[data-customize-partial-id="'+a+'"]',navMenuArgs:c.constructingContainerContext||{},containerInclusive:!0},c.params||{}),d.selectiveRefresh.Partial.prototype.initialize.call(g,a,c),!b.isObject(g.params.navMenuArgs))throw new Error("Missing navMenuArgs");if(g.params.navMenuArgs.args_hmac!==f)throw new Error("args_hmac mismatch with id")},isRelatedSetting:function(a,c,e){var f,g,h,i,j,k,l=this;if(b.isString(a)&&(a=d(a)),h=/^nav_menu_item\[/.test(a.id),h&&b.isObject(c)&&b.isObject(e)&&(i=b.clone(c),j=b.clone(e),delete i.type_label,delete j.type_label,"https"===d.preview.scheme.get()&&(k=document.createElement("a"),k.href=i.url,k.protocol="https:",i.url=k.href,k.href=j.url,k.protocol="https:",j.url=k.href),b.isEqual(j,i)))return!1;if(l.params.navMenuArgs.theme_location){if("nav_menu_locations["+l.params.navMenuArgs.theme_location+"]"===a.id)return!0;f=d("nav_menu_locations["+l.params.navMenuArgs.theme_location+"]")}return g=l.params.navMenuArgs.menu,!g&&f&&(g=f()),g?"nav_menu["+g+"]"===a.id||h&&(c&&c.nav_menu_term_id===g||e&&e.nav_menu_term_id===g):!1},refresh:function(){var c,e=this,f=a.Deferred();return b.isNumber(e.params.navMenuArgs.menu)?c=e.params.navMenuArgs.menu:e.params.navMenuArgs.theme_location&&d.has("nav_menu_locations["+e.params.navMenuArgs.theme_location+"]")&&(c=d("nav_menu_locations["+e.params.navMenuArgs.theme_location+"]").get()),c?d.selectiveRefresh.Partial.prototype.refresh.call(e):(e.fallback(),f.reject(),f.promise())},renderContent:function(b){var c=this,e=b.container;""===b.addedContent&&b.partial.fallback(),d.selectiveRefresh.Partial.prototype.renderContent.call(c,b)&&a(document).trigger("customize-preview-menu-refreshed",[{instanceNumber:null,wpNavArgs:b.context,wpNavMenuArgs:b.context,oldContainer:e,newContainer:b.container}])}}),d.selectiveRefresh.partialConstructor.nav_menu_instance=e.NavMenuInstancePartial,e.handleUnplacedNavMenuInstances=function(a){var c;return c=b.filter(b.values(e.data.navMenuInstanceArgs),function(a){return!d.selectiveRefresh.partial.has("nav_menu_instance["+a.args_hmac+"]")}),b.findWhere(c,a)?(d.selectiveRefresh.requestFullRefresh(),!0):!1},e.bindSettingListener=function(a,b){var c;return b=b||{},(c=a.id.match(/^nav_menu\[(-?\d+)]$/))?(a._navMenuId=parseInt(c[1],10),a.bind(this.onChangeNavMenuSetting),b.fire&&this.onChangeNavMenuSetting.call(a,a(),!1),!0):(c=a.id.match(/^nav_menu_item\[(-?\d+)]$/))?(a._navMenuItemId=parseInt(c[1],10),a.bind(this.onChangeNavMenuItemSetting),b.fire&&this.onChangeNavMenuItemSetting.call(a,a(),!1),!0):(c=a.id.match(/^nav_menu_locations\[(.+?)]/),c?(a._navMenuThemeLocation=c[1],a.bind(this.onChangeNavMenuLocationsSetting),b.fire&&this.onChangeNavMenuLocationsSetting.call(a,a(),!1),!0):!1)},e.unbindSettingListener=function(a){a.unbind(this.onChangeNavMenuSetting),a.unbind(this.onChangeNavMenuItemSetting),a.unbind(this.onChangeNavMenuLocationsSetting)},e.onChangeNavMenuSetting=function(){var a=this;e.handleUnplacedNavMenuInstances({menu:a._navMenuId}),d.each(function(b){b._navMenuThemeLocation&&a._navMenuId===b()&&e.handleUnplacedNavMenuInstances({theme_location:b._navMenuThemeLocation})})},e.onChangeNavMenuItemSetting=function(a,b){var c,f=a||b;c=d("nav_menu["+String(f.nav_menu_term_id)+"]"),c&&e.onChangeNavMenuSetting.call(c)},e.onChangeNavMenuLocationsSetting=function(){var a,c=this;e.handleUnplacedNavMenuInstances({theme_location:c._navMenuThemeLocation}),a=!!b.findWhere(b.values(e.data.navMenuInstanceArgs),{theme_location:c._navMenuThemeLocation}),a||d.selectiveRefresh.requestFullRefresh()}),e.highlightControls=function(){var b=".menu-item";d.settings.channel&&a(document).on("click",b,function(b){var c;b.shiftKey&&(c=a(this).attr("class").match(/(?:^|\s)menu-item-(\d+)(?:\s|$)/),c&&(b.preventDefault(),b.stopPropagation(),d.preview.send("focus-nav-menu-item-control",parseInt(c[1],10))))})},d.bind("preview-ready",function(){e.init()}),e}(jQuery,_,wp,wp.customize);

View File

@ -572,6 +572,11 @@ wp.customize.widgetsPreview = wp.customize.WidgetCustomizerPreview = (function(
var self = this,
selector = this.widgetSelectors.join( ',' );
// Skip adding highlights if not in the customizer preview iframe.
if ( ! api.settings.channel ) {
return;
}
$( selector ).attr( 'title', this.l10n.widgetTooltip );
$( document ).on( 'mouseenter', selector, function() {

File diff suppressed because one or more lines are too long

View File

@ -3,7 +3,67 @@
*/
(function( exports, $ ){
var api = wp.customize,
debounce;
debounce,
currentHistoryState = {};
/*
* Capture the state that is passed into history.replaceState() and history.pushState()
* and also which is returned in the popstate event so that when the changeset_uuid
* gets updated when transitioning to a new changeset there the current state will
* be supplied in the call to history.replaceState().
*/
( function( history ) {
var injectUrlWithState;
if ( ! history.replaceState ) {
return;
}
/**
* Amend the supplied URL with the customized state.
*
* @since 4.7.0
* @access private
*
* @param {string} url URL.
* @returns {string} URL with customized state.
*/
injectUrlWithState = function( url ) {
var urlParser, queryParams;
urlParser = document.createElement( 'a' );
urlParser.href = url;
queryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.theme.channel ) {
queryParams.customize_messenger_channel = api.settings.channel;
}
urlParser.search = $.param( queryParams );
return url;
};
history.replaceState = ( function( nativeReplaceState ) {
return function historyReplaceState( data, title, url ) {
currentHistoryState = data;
return nativeReplaceState.call( history, data, title, injectUrlWithState( url ) );
};
} )( history.replaceState );
history.pushState = ( function( nativePushState ) {
return function historyPushState( data, title, url ) {
currentHistoryState = data;
return nativePushState.call( history, data, title, injectUrlWithState( url ) );
};
} )( history.pushState );
window.addEventListener( 'popstate', function( event ) {
currentHistoryState = event.state;
} );
}( history ) );
/**
* Returns a debounced version of the function.
@ -37,38 +97,73 @@
* @param {object} options - Extend any instance parameter or method with this object.
*/
initialize: function( params, options ) {
var self = this;
var preview = this, urlParser = document.createElement( 'a' );
api.Messenger.prototype.initialize.call( this, params, options );
api.Messenger.prototype.initialize.call( preview, params, options );
this.body = $( document.body );
this.body.on( 'click.preview', 'a', function( event ) {
urlParser.href = preview.origin();
preview.add( 'scheme', urlParser.protocol.replace( /:$/, '' ) );
preview.body = $( document.body );
preview.body.on( 'click.preview', 'a', function( event ) {
var link, isInternalJumpLink;
link = $( this );
isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
event.preventDefault();
if ( isInternalJumpLink && '#' !== link.attr( 'href' ) ) {
$( link.attr( 'href' ) ).each( function() {
this.scrollIntoView();
} );
// No-op if the anchor is not a link.
if ( _.isUndefined( link.attr( 'href' ) ) ) {
return;
}
isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
// Allow internal jump links to behave normally without preventing default.
if ( isInternalJumpLink ) {
return;
}
// If the link is not previewable, prevent the browser from navigating to it.
if ( ! api.isLinkPreviewable( link[0] ) ) {
wp.a11y.speak( api.settings.l10n.linkUnpreviewable );
event.preventDefault();
return;
}
// If not in an iframe, then allow the link click to proceed normally since the state query params are added.
if ( ! api.settings.channel ) {
return;
}
// Prevent initiating navigating from click and instead rely on sending url message to pane.
event.preventDefault();
/*
* Note the shift key is checked so shift+click on widgets or
* nav menu items can just result on focusing on the corresponding
* control instead of also navigating to the URL linked to.
*/
if ( event.shiftKey || isInternalJumpLink ) {
if ( event.shiftKey ) {
return;
}
self.send( 'scroll', 0 );
self.send( 'url', link.prop( 'href' ) );
});
// You cannot submit forms.
this.body.on( 'submit.preview', 'form', function( event ) {
var urlParser;
// Note: It's not relevant to send scroll because sending url message will have the same effect.
preview.send( 'url', link.prop( 'href' ) );
} );
preview.body.on( 'submit.preview', 'form', function( event ) {
var urlParser = document.createElement( 'a' );
urlParser.href = this.action;
// If the link is not previewable, prevent the browser from navigating to it.
if ( 'GET' !== this.method.toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
wp.a11y.speak( api.settings.l10n.formUnpreviewable );
event.preventDefault();
return;
}
// If not in an iframe, then allow the form submission to proceed normally with the state inputs injected.
if ( ! api.settings.channel ) {
return;
}
/*
* If the default wasn't prevented already (in which case the form
@ -81,30 +176,399 @@
* a no-op, which is the same behavior as when clicking a link to an
* external site in the preview.
*/
if ( ! event.isDefaultPrevented() && 'GET' === this.method.toUpperCase() ) {
urlParser = document.createElement( 'a' );
urlParser.href = this.action;
if ( urlParser.search.substr( 1 ).length > 1 ) {
if ( ! event.isDefaultPrevented() ) {
if ( urlParser.search.length > 1 ) {
urlParser.search += '&';
}
urlParser.search += $( this ).serialize();
api.preview.send( 'url', urlParser.href );
}
// Prevent default since navigation should be done via sending url message or via JS submit handler.
event.preventDefault();
});
this.window = $( window );
this.window.on( 'scroll.preview', debounce( function() {
self.send( 'scroll', self.window.scrollTop() );
}, 200 ));
preview.window = $( window );
this.bind( 'scroll', function( distance ) {
self.window.scrollTop( distance );
if ( api.settings.channel ) {
preview.window.on( 'scroll.preview', debounce( function() {
preview.send( 'scroll', preview.window.scrollTop() );
}, 200 ) );
preview.bind( 'scroll', function( distance ) {
preview.window.scrollTop( distance );
});
}
}
});
/**
* Inject the changeset UUID into links in the document.
*
* @since 4.7.0
* @access protected
*
* @access private
* @returns {void}
*/
api.addLinkPreviewing = function addLinkPreviewing() {
var linkSelectors = 'a[href], area';
// Inject links into initial document.
$( document.body ).find( linkSelectors ).each( function() {
api.prepareLinkPreview( this );
} );
// Inject links for new elements added to the page.
if ( 'undefined' !== typeof MutationObserver ) {
api.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( linkSelectors ).each( function() {
api.prepareLinkPreview( this );
} );
} );
} );
api.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
} else {
// If mutation observers aren't available, fallback to just-in-time injection.
$( document.documentElement ).on( 'click focus mouseover', linkSelectors, function() {
api.prepareLinkPreview( this );
} );
}
};
/**
* Should the supplied link is previewable.
*
* @since 4.7.0
* @access public
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {string} element.search Query string.
* @param {string} element.pathname Path.
* @param {string} element.hostname Hostname.
* @param {object} [options]
* @param {object} [options.allowAdminAjax=false] Allow admin-ajax.php requests.
* @returns {boolean} Is appropriate for changeset link.
*/
api.isLinkPreviewable = function isLinkPreviewable( element, options ) {
var hasMatchingHost, urlParser, args;
args = _.extend( {}, { allowAdminAjax: false }, options || {} );
if ( 'javascript:' === element.protocol ) { // jshint ignore:line
return true;
}
// Only web URLs can be previewed.
if ( 'https:' !== element.protocol && 'http:' !== element.protocol ) {
return false;
}
urlParser = document.createElement( 'a' );
hasMatchingHost = ! _.isUndefined( _.find( api.settings.url.allowed, function( allowedUrl ) {
urlParser.href = allowedUrl;
if ( urlParser.hostname === element.hostname && urlParser.protocol === element.protocol ) {
return true;
}
return false;
} ) );
if ( ! hasMatchingHost ) {
return false;
}
// Skip wp login and signup pages.
if ( /\/wp-(login|signup)\.php$/.test( element.pathname ) ) {
return false;
}
// Allow links to admin ajax as faux frontend URLs.
if ( /\/wp-admin\/admin-ajax\.php$/.test( element.pathname ) ) {
return args.allowAdminAjax;
}
// Disallow links to admin, includes, and content.
if ( /\/wp-(admin|includes|content)(\/|$)/.test( element.pathname ) ) {
return false;
}
return true;
};
/**
* Inject the customize_changeset_uuid query param into links on the frontend.
*
* @since 4.7.0
* @access protected
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {object} element.search Query string.
* @returns {void}
*/
api.prepareLinkPreview = function prepareLinkPreview( element ) {
var queryParams;
// Skip links in admin bar.
if ( $( element ).closest( '#wpadminbar' ).length ) {
return;
}
// Ignore links with href="#" or href="#id".
if ( '#' === $( element ).attr( 'href' ).substr( 0, 1 ) ) {
return;
}
// Make sure links in preview use HTTPS if parent frame uses HTTPS.
if ( 'https' === api.preview.scheme.get() && 'http:' === element.protocol && -1 !== api.settings.url.allowedHosts.indexOf( element.hostname ) ) {
element.protocol = 'https:';
}
if ( ! api.isLinkPreviewable( element ) ) {
$( element ).addClass( 'customize-unpreviewable' );
return;
}
$( element ).removeClass( 'customize-unpreviewable' );
queryParams = api.utils.parseQueryString( element.search.substring( 1 ) );
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.channel ) {
queryParams.customize_messenger_channel = api.settings.channel;
}
element.search = $.param( queryParams );
// Prevent links from breaking out of preview iframe.
if ( api.settings.channel ) {
element.target = '_self';
}
};
/**
* Inject the changeset UUID into Ajax requests.
*
* @since 4.7.0
* @access protected
*
* @return {void}
*/
api.addRequestPreviewing = function addRequestPreviewing() {
/**
* Rewrite Ajax requests to inject customizer state.
*
* @param {object} options Options.
* @param {string} options.type Type.
* @param {string} options.url URL.
* @param {object} originalOptions Original options.
* @param {XMLHttpRequest} xhr XHR.
* @returns {void}
*/
var prefilterAjax = function( options, originalOptions, xhr ) {
var urlParser, queryParams, requestMethod, dirtyValues = {};
urlParser = document.createElement( 'a' );
urlParser.href = options.url;
// Abort if the request is not for this site.
if ( ! api.isLinkPreviewable( urlParser, { allowAdminAjax: true } ) ) {
return;
}
queryParams = api.utils.parseQueryString( urlParser.search.substring( 1 ) );
// Note that _dirty flag will be cleared with changeset updates.
api.each( function( setting ) {
if ( setting._dirty ) {
dirtyValues[ setting.id ] = setting.get();
}
} );
if ( ! _.isEmpty( dirtyValues ) ) {
requestMethod = options.type.toUpperCase();
// Override underlying request method to ensure unsaved changes to changeset can be included (force Backbone.emulateHTTP).
if ( 'POST' !== requestMethod ) {
xhr.setRequestHeader( 'X-HTTP-Method-Override', requestMethod );
queryParams._method = requestMethod;
options.type = 'POST';
}
// Amend the post data with the customized values.
if ( options.data ) {
options.data += '&';
} else {
options.data = '';
}
options.data += $.param( {
customized: JSON.stringify( dirtyValues )
} );
}
// Include customized state query params in URL.
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
urlParser.search = $.param( queryParams );
options.url = urlParser.href;
};
$.ajaxPrefilter( prefilterAjax );
};
/**
* Inject changeset UUID into forms, allowing preview to persist through submissions.
*
* @since 4.7.0
* @access protected
*
* @returns {void}
*/
api.addFormPreviewing = function addFormPreviewing() {
// Inject inputs for forms in initial document.
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
// Inject inputs for new forms added to the page.
if ( 'undefined' !== typeof MutationObserver ) {
api.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
} );
} );
api.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
}
};
/**
* Inject changeset into form inputs.
*
* @since 4.7.0
* @access protected
*
* @param {HTMLFormElement} form Form.
* @returns {void}
*/
api.prepareFormPreview = function prepareFormPreview( form ) {
var urlParser, stateParams = {};
if ( ! form.action ) {
form.action = location.href;
}
urlParser = document.createElement( 'a' );
urlParser.href = form.action;
// Make sure forms in preview use HTTPS if parent frame uses HTTPS.
if ( 'https' === api.preview.scheme.get() && 'http:' === urlParser.protocol && -1 !== api.settings.url.allowedHosts.indexOf( urlParser.hostname ) ) {
urlParser.protocol = 'https:';
form.action = urlParser.href;
}
if ( 'GET' !== form.method.toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
$( form ).addClass( 'customize-unpreviewable' );
return;
}
$( form ).removeClass( 'customize-unpreviewable' );
stateParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
stateParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.channel ) {
stateParams.customize_messenger_channel = api.settings.channel;
}
_.each( stateParams, function( value, name ) {
var input = $( form ).find( 'input[name="' + name + '"]' );
if ( input.length ) {
input.val( value );
} else {
$( form ).prepend( $( '<input>', {
type: 'hidden',
name: name,
value: value
} ) );
}
} );
// Prevent links from breaking out of preview iframe.
if ( api.settings.channel ) {
form.target = '_self';
}
};
/**
* Watch current URL and send keep-alive (heartbeat) messages to the parent.
*
* Keep the customizer pane notified that the preview is still alive
* and that the user hasn't navigated to a non-customized URL.
*
* @since 4.7.0
* @access protected
*/
api.keepAliveCurrentUrl = ( function() {
var previousPathName = location.pathname,
previousQueryString = location.search.substr( 1 ),
previousQueryParams = null,
stateQueryParams = [ 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel' ];
return function keepAliveCurrentUrl() {
var urlParser, currentQueryParams;
// Short-circuit with keep-alive if previous URL is identical (as is normal case).
if ( previousQueryString === location.search.substr( 1 ) && previousPathName === location.pathname ) {
api.preview.send( 'keep-alive' );
return;
}
urlParser = document.createElement( 'a' );
if ( null === previousQueryParams ) {
urlParser.search = previousQueryString;
previousQueryParams = api.utils.parseQueryString( previousQueryString );
_.each( stateQueryParams, function( name ) {
delete previousQueryParams[ name ];
} );
}
// Determine if current URL minus customized state params and URL hash.
urlParser.href = location.href;
currentQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
_.each( stateQueryParams, function( name ) {
delete currentQueryParams[ name ];
} );
if ( previousPathName !== location.pathname || ! _.isEqual( previousQueryParams, currentQueryParams ) ) {
urlParser.search = $.param( currentQueryParams );
urlParser.hash = '';
api.settings.url.self = urlParser.href;
api.preview.send( 'ready', {
currentUrl: api.settings.url.self,
activePanels: api.settings.activePanels,
activeSections: api.settings.activeSections,
activeControls: api.settings.activeControls,
settingValidities: api.settings.settingValidities
} );
} else {
api.preview.send( 'keep-alive' );
}
previousQueryParams = currentQueryParams;
previousQueryString = location.search.substr( 1 );
previousPathName = location.pathname;
};
} )();
$( function() {
var bg, setValue;
@ -118,6 +582,10 @@
channel: api.settings.channel
});
api.addLinkPreviewing();
api.addRequestPreviewing();
api.addFormPreviewing();
/**
* Create/update a setting value.
*
@ -171,15 +639,47 @@
api.preview.send( 'nonce', api.settings.nonce );
api.preview.send( 'documentTitle', document.title );
// Send scroll in case of loading via non-refresh.
api.preview.send( 'scroll', $( window ).scrollTop() );
});
api.preview.bind( 'saved', function( response ) {
if ( response.next_changeset_uuid ) {
api.settings.changeset.uuid = response.next_changeset_uuid;
// Update UUIDs in links and forms.
$( document.body ).find( 'a[href], area' ).each( function() {
api.prepareLinkPreview( this );
} );
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
/*
* Replace the UUID in the URL. Note that the wrapped history.replaceState()
* will handle injecting the current api.settings.changeset.uuid into the URL,
* so this is merely to trigger that logic.
*/
if ( history.replaceState ) {
history.replaceState( currentHistoryState, '', location.href );
}
}
api.trigger( 'saved', response );
} );
api.bind( 'saved', function() {
api.each( function( setting ) {
/*
* Clear dirty flag for settings when saved to changeset so that they
* won't be needlessly included in selective refresh or ajax requests.
*/
api.preview.bind( 'changeset-saved', function( data ) {
_.each( data.saved_changeset_values, function( value, settingId ) {
var setting = api( settingId );
if ( setting && _.isEqual( setting.get(), value ) ) {
setting._dirty = false;
}
} );
} );
@ -192,12 +692,16 @@
* containers and controls are active.
*/
api.preview.send( 'ready', {
currentUrl: api.settings.url.self,
activePanels: api.settings.activePanels,
activeSections: api.settings.activeSections,
activeControls: api.settings.activeControls,
settingValidities: api.settings.settingValidities
} );
// Send ready when URL changes via JS.
setInterval( api.keepAliveCurrentUrl, api.settings.timeouts.keepAliveSend );
// Display a loading indicator when preview is reloading, and remove on failure.
api.preview.bind( 'loading-initiated', function () {
$( 'body' ).addClass( 'wp-customizer-unloading' );

File diff suppressed because one or more lines are too long

View File

@ -11,8 +11,7 @@ wp.customize.selectiveRefresh = ( function( $, api ) {
renderQueryVar: '',
l10n: {
shiftClickToEdit: ''
},
refreshBuffer: 250
}
},
currentRequest: null
};
@ -485,8 +484,9 @@ wp.customize.selectiveRefresh = ( function( $, api ) {
return {
wp_customize: 'on',
nonce: api.settings.nonce.preview,
theme: api.settings.theme.stylesheet,
customized: JSON.stringify( dirtyCustomized )
customize_theme: api.settings.theme.stylesheet,
customized: JSON.stringify( dirtyCustomized ),
customize_changeset_uuid: api.settings.changeset.uuid
};
};
@ -668,7 +668,7 @@ wp.customize.selectiveRefresh = ( function( $, api ) {
self._pendingPartialRequests = {};
} );
},
self.data.refreshBuffer
api.settings.timeouts.selectiveRefresh
);
return partialRequest.deferred.promise();

File diff suppressed because one or more lines are too long

View File

@ -111,6 +111,51 @@ function create_initial_post_types() {
'query_var' => false,
) );
register_post_type( 'customize_changeset', array(
'labels' => array(
'name' => _x( 'Changesets', 'post type general name' ),
'singular_name' => _x( 'Changeset', 'post type singular name' ),
'menu_name' => _x( 'Changesets', 'admin menu' ),
'name_admin_bar' => _x( 'Changeset', 'add new on admin bar' ),
'add_new' => _x( 'Add New', 'Customize Changeset' ),
'add_new_item' => __( 'Add New Changeset' ),
'new_item' => __( 'New Changeset' ),
'edit_item' => __( 'Edit Changeset' ),
'view_item' => __( 'View Changeset' ),
'all_items' => __( 'All Changesets' ),
'search_items' => __( 'Search Changesets' ),
'not_found' => __( 'No changesets found.' ),
'not_found_in_trash' => __( 'No changesets found in Trash.' ),
),
'public' => false,
'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'can_export' => false,
'delete_with_user' => false,
'supports' => array( 'title', 'author' ),
'capability_type' => 'customize_changeset',
'capabilities' => array(
'create_posts' => 'customize',
'delete_others_posts' => 'customize',
'delete_post' => 'customize',
'delete_posts' => 'customize',
'delete_private_posts' => 'customize',
'delete_published_posts' => 'customize',
'edit_others_posts' => 'customize',
'edit_post' => 'customize',
'edit_posts' => 'customize',
'edit_private_posts' => 'customize',
'edit_published_posts' => 'do_not_allow',
'publish_posts' => 'customize',
'read' => 'read',
'read_post' => 'customize',
'read_private_posts' => 'customize',
),
) );
register_post_status( 'publish', array(
'label' => _x( 'Published', 'post status' ),
'public' => true,

View File

@ -450,7 +450,7 @@ function wp_default_scripts( &$scripts ) {
$scripts->add( 'customize-base', "/wp-includes/js/customize-base$suffix.js", array( 'jquery', 'json2', 'underscore' ), false, 1 );
$scripts->add( 'customize-loader', "/wp-includes/js/customize-loader$suffix.js", array( 'customize-base' ), false, 1 );
$scripts->add( 'customize-preview', "/wp-includes/js/customize-preview$suffix.js", array( 'customize-base' ), false, 1 );
$scripts->add( 'customize-preview', "/wp-includes/js/customize-preview$suffix.js", array( 'wp-a11y', 'customize-base' ), false, 1 );
$scripts->add( 'customize-models', "/wp-includes/js/customize-models.js", array( 'underscore', 'backbone' ), false, 1 );
$scripts->add( 'customize-views', "/wp-includes/js/customize-views.js", array( 'jquery', 'underscore', 'imgareaselect', 'customize-models', 'media-editor', 'media-views' ), false, 1 );
$scripts->add( 'customize-controls', "/wp-admin/js/customize-controls$suffix.js", array( 'customize-base', 'wp-a11y', 'wp-util' ), false, 1 );

View File

@ -2066,9 +2066,9 @@ function check_theme_switched() {
* Includes and instantiates the WP_Customize_Manager class.
*
* Loads the Customizer at plugins_loaded when accessing the customize.php admin
* page or when any request includes a wp_customize=on param, either as a GET
* query var or as POST data. This param is a signal for whether to bootstrap
* the Customizer when WordPress is loading, especially in the Customizer preview
* page or when any request includes a wp_customize=on param or a customize_changeset
* param (a UUID). This param is a signal for whether to bootstrap the Customizer when
* WordPress is loading, especially in the Customizer preview
* or when making Customizer Ajax requests for widgets or menus.
*
* @since 3.4.0
@ -2076,14 +2076,140 @@ function check_theme_switched() {
* @global WP_Customize_Manager $wp_customize
*/
function _wp_customize_include() {
if ( ! ( ( isset( $_REQUEST['wp_customize'] ) && 'on' == $_REQUEST['wp_customize'] )
|| ( is_admin() && 'customize.php' == basename( $_SERVER['PHP_SELF'] ) )
) ) {
$is_customize_admin_page = ( is_admin() && 'customize.php' == basename( $_SERVER['PHP_SELF'] ) );
$should_include = (
$is_customize_admin_page
||
( isset( $_REQUEST['wp_customize'] ) && 'on' == $_REQUEST['wp_customize'] )
||
( ! empty( $_GET['customize_changeset_uuid'] ) || ! empty( $_POST['customize_changeset_uuid'] ) )
);
if ( ! $should_include ) {
return;
}
/*
* Note that wp_unslash() is not being used on the input vars because it is
* called before wp_magic_quotes() gets called. Besides this fact, none of
* the values should contain any characters needing slashes anyway.
*/
$keys = array( 'changeset_uuid', 'customize_changeset_uuid', 'customize_theme', 'theme', 'customize_messenger_channel' );
$input_vars = array_merge(
wp_array_slice_assoc( $_GET, $keys ),
wp_array_slice_assoc( $_POST, $keys )
);
$theme = null;
$changeset_uuid = null;
$messenger_channel = null;
if ( $is_customize_admin_page && isset( $input_vars['changeset_uuid'] ) ) {
$changeset_uuid = sanitize_key( $input_vars['changeset_uuid'] );
} elseif ( ! empty( $input_vars['customize_changeset_uuid'] ) ) {
$changeset_uuid = sanitize_key( $input_vars['customize_changeset_uuid'] );
}
// Note that theme will be sanitized via WP_Theme.
if ( $is_customize_admin_page && isset( $input_vars['theme'] ) ) {
$theme = $input_vars['theme'];
} elseif ( isset( $input_vars['customize_theme'] ) ) {
$theme = $input_vars['customize_theme'];
}
if ( isset( $input_vars['customize_messenger_channel'] ) ) {
$messenger_channel = sanitize_key( $input_vars['customize_messenger_channel'] );
}
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
$GLOBALS['wp_customize'] = new WP_Customize_Manager();
$GLOBALS['wp_customize'] = new WP_Customize_Manager( compact( 'changeset_uuid', 'theme', 'messenger_channel' ) );
}
/**
* Publish a snapshot's changes.
*
* @param string $new_status New post status.
* @param string $old_status Old post status.
* @param WP_Post $changeset_post Changeset post object.
*/
function _wp_customize_publish_changeset( $new_status, $old_status, $changeset_post ) {
global $wp_customize;
$is_publishing_changeset = (
'customize_changeset' === $changeset_post->post_type
&&
'publish' === $new_status
&&
'publish' !== $old_status
);
if ( ! $is_publishing_changeset ) {
return;
}
if ( empty( $wp_customize ) ) {
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
$wp_customize = new WP_Customize_Manager( $changeset_post->post_name );
}
if ( ! did_action( 'customize_register' ) ) {
/*
* When running from CLI or Cron, the customize_register action will need
* to be triggered in order for core, themes, and plugins to register their
* settings. Normally core will add_action( 'customize_register' ) at
* priority 10 to register the core settings, and if any themes/plugins
* also add_action( 'customize_register' ) at the same priority, they
* will have a $wp_customize with those settings registered since they
* call add_action() afterward, normally. However, when manually doing
* the customize_register action after the setup_theme, then the order
* will be reversed for two actions added at priority 10, resulting in
* the core settings no longer being available as expected to themes/plugins.
* So the following manually calls the method that registers the core
* settings up front before doing the action.
*/
remove_action( 'customize_register', array( $wp_customize, 'register_controls' ) );
$wp_customize->register_controls();
/** This filter is documented in /wp-includes/class-wp-customize-manager.php */
do_action( 'customize_register', $wp_customize );
}
$wp_customize->_publish_changeset_values( $changeset_post->ID ) ;
/*
* Trash the changeset post if revisions are not enabled. Unpublished
* changesets by default get garbage collected due to the auto-draft status.
* When a changeset post is published, however, it would no longer get cleaned
* out. Ths is a problem when the changeset posts are never displayed anywhere,
* since they would just be endlessly piling up. So here we use the revisions
* feature to indicate whether or not a published changeset should get trashed
* and thus garbage collected.
*/
if ( ! wp_revisions_enabled( $changeset_post ) ) {
wp_trash_post( $changeset_post->ID );
}
}
/**
* Filters changeset post data upon insert to ensure post_name is intact.
*
* This is needed to prevent the post_name from being dropped when the post is
* transitioned into pending status by a contributor.
*
* @since 4.7.0
* @see wp_insert_post()
*
* @param array $post_data An array of slashed post data.
* @param array $supplied_post_data An array of sanitized, but otherwise unmodified post data.
* @returns array Filtered data.
*/
function _wp_customize_changeset_filter_insert_post_data( $post_data, $supplied_post_data ) {
if ( isset( $post_data['post_type'] ) && 'customize_changeset' === $post_data['post_type'] ) {
// Prevent post_name from being dropped, such as when contributor saves a changeset post as pending.
if ( empty( $post_data['post_name'] ) && ! empty( $supplied_post_data['post_name'] ) ) {
$post_data['post_name'] = $supplied_post_data['post_name'];
}
}
return $post_data;
}
/**

View File

@ -4,7 +4,7 @@
*
* @global string $wp_version
*/
$wp_version = '4.7-alpha-38809';
$wp_version = '4.7-alpha-38810';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.