소재지 ₍₍◝(・'ω'・)◟⁾⁾ 🐟️?看XM(^_−)☆哈先看看刚看过卡卡国看过了回来冷藏柜好极过估计
PNG %k25u25%fgd5n!home/toreyh/public_html/wp-admin/js/customize-widgets.js 0000644 00000214057 15221403114 0017466 0 ustar 00 /**
* @output wp-admin/js/customize-widgets.js
*/
/* global _wpCustomizeWidgetsSettings */
(function( wp, $ ){
if ( ! wp || ! wp.customize ) { return; }
// Set up our namespace...
var api = wp.customize,
l10n;
/**
* @namespace wp.customize.Widgets
*/
api.Widgets = api.Widgets || {};
api.Widgets.savedWidgetIds = {};
// Link settings.
api.Widgets.data = _wpCustomizeWidgetsSettings || {};
l10n = api.Widgets.data.l10n;
/**
* wp.customize.Widgets.WidgetModel
*
* A single widget model.
*
* @class wp.customize.Widgets.WidgetModel
* @augments Backbone.Model
*/
api.Widgets.WidgetModel = Backbone.Model.extend(/** @lends wp.customize.Widgets.WidgetModel.prototype */{
id: null,
temp_id: null,
classname: null,
control_tpl: null,
description: null,
is_disabled: null,
is_multi: null,
multi_number: null,
name: null,
id_base: null,
transport: null,
params: [],
width: null,
height: null,
search_matched: true
});
/**
* wp.customize.Widgets.WidgetCollection
*
* Collection for widget models.
*
* @class wp.customize.Widgets.WidgetCollection
* @augments Backbone.Collection
*/
api.Widgets.WidgetCollection = Backbone.Collection.extend(/** @lends wp.customize.Widgets.WidgetCollection.prototype */{
model: api.Widgets.WidgetModel,
// Controls searching on the current widget collection
// and triggers an update event.
doSearch: function( value ) {
// Don't do anything if we've already done this search.
// Useful because the search handler fires multiple times per keystroke.
if ( this.terms === value ) {
return;
}
// Updates terms with the value passed.
this.terms = value;
// If we have terms, run a search...
if ( this.terms.length > 0 ) {
this.search( this.terms );
}
// If search is blank, set all the widgets as they matched the search to reset the views.
if ( this.terms === '' ) {
this.each( function ( widget ) {
widget.set( 'search_matched', true );
} );
}
},
// Performs a search within the collection.
// @uses RegExp
search: function( term ) {
var match, haystack;
// Escape the term string for RegExp meta characters.
term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
// Consider spaces as word delimiters and match the whole string
// so matching terms can be combined.
term = term.replace( / /g, ')(?=.*' );
match = new RegExp( '^(?=.*' + term + ').+', 'i' );
this.each( function ( data ) {
haystack = [ data.get( 'name' ), data.get( 'description' ) ].join( ' ' );
data.set( 'search_matched', match.test( haystack ) );
} );
}
});
api.Widgets.availableWidgets = new api.Widgets.WidgetCollection( api.Widgets.data.availableWidgets );
/**
* wp.customize.Widgets.SidebarModel
*
* A single sidebar model.
*
* @class wp.customize.Widgets.SidebarModel
* @augments Backbone.Model
*/
api.Widgets.SidebarModel = Backbone.Model.extend(/** @lends wp.customize.Widgets.SidebarModel.prototype */{
after_title: null,
after_widget: null,
before_title: null,
before_widget: null,
'class': null,
description: null,
id: null,
name: null,
is_rendered: false
});
/**
* wp.customize.Widgets.SidebarCollection
*
* Collection for sidebar models.
*
* @class wp.customize.Widgets.SidebarCollection
* @augments Backbone.Collection
*/
api.Widgets.SidebarCollection = Backbone.Collection.extend(/** @lends wp.customize.Widgets.SidebarCollection.prototype */{
model: api.Widgets.SidebarModel
});
api.Widgets.registeredSidebars = new api.Widgets.SidebarCollection( api.Widgets.data.registeredSidebars );
api.Widgets.AvailableWidgetsPanelView = wp.Backbone.View.extend(/** @lends wp.customize.Widgets.AvailableWidgetsPanelView.prototype */{
el: '#available-widgets',
events: {
'input #widgets-search': 'search',
'focus .widget-tpl' : 'focus',
'click .widget-tpl' : '_submit',
'keypress .widget-tpl' : '_submit',
'keydown' : 'keyboardAccessible'
},
// Cache current selected widget.
selected: null,
// Cache sidebar control which has opened panel.
currentSidebarControl: null,
$search: null,
$clearResults: null,
searchMatchesCount: null,
/**
* View class for the available widgets panel.
*
* @constructs wp.customize.Widgets.AvailableWidgetsPanelView
* @augments wp.Backbone.View
*/
initialize: function() {
var self = this;
this.$search = $( '#widgets-search' );
this.$clearResults = this.$el.find( '.clear-results' );
_.bindAll( this, 'close' );
this.listenTo( this.collection, 'change', this.updateList );
this.updateList();
// Set the initial search count to the number of available widgets.
this.searchMatchesCount = this.collection.length;
/*
* If the available widgets panel is open and the customize controls
* are interacted with (i.e. available widgets panel is blurred) then
* close the available widgets panel. Also close on back button click.
*/
$( '#customize-controls, #available-widgets .customize-section-title' ).on( 'click keydown', function( e ) {
var isAddNewBtn = $( e.target ).is( '.add-new-widget, .add-new-widget *' );
if ( $( 'body' ).hasClass( 'adding-widget' ) && ! isAddNewBtn ) {
self.close();
}
} );
// Clear the search results and trigger an `input` event to fire a new search.
this.$clearResults.on( 'click', function() {
self.$search.val( '' ).trigger( 'focus' ).trigger( 'input' );
} );
// Close the panel if the URL in the preview changes.
api.previewer.bind( 'url', this.close );
},
/**
* Performs a search and handles selected widget.
*/
search: _.debounce( function( event ) {
var firstVisible;
this.collection.doSearch( event.target.value );
// Update the search matches count.
this.updateSearchMatchesCount();
// Announce how many search results.
this.announceSearchMatches();
// Remove a widget from being selected if it is no longer visible.
if ( this.selected && ! this.selected.is( ':visible' ) ) {
this.selected.removeClass( 'selected' );
this.selected = null;
}
// If a widget was selected but the filter value has been cleared out, clear selection.
if ( this.selected && ! event.target.value ) {
this.selected.removeClass( 'selected' );
this.selected = null;
}
// If a filter has been entered and a widget hasn't been selected, select the first one shown.
if ( ! this.selected && event.target.value ) {
firstVisible = this.$el.find( '> .widget-tpl:visible:first' );
if ( firstVisible.length ) {
this.select( firstVisible );
}
}
// Toggle the clear search results button.
if ( '' !== event.target.value ) {
this.$clearResults.addClass( 'is-visible' );
} else if ( '' === event.target.value ) {
this.$clearResults.removeClass( 'is-visible' );
}
// Set a CSS class on the search container when there are no search results.
if ( ! this.searchMatchesCount ) {
this.$el.addClass( 'no-widgets-found' );
} else {
this.$el.removeClass( 'no-widgets-found' );
}
}, 500 ),
/**
* Updates the count of the available widgets that have the `search_matched` attribute.
*/
updateSearchMatchesCount: function() {
this.searchMatchesCount = this.collection.where({ search_matched: true }).length;
},
/**
* Sends a message to the aria-live region to announce how many search results.
*/
announceSearchMatches: function() {
var message = l10n.widgetsFound.replace( '%d', this.searchMatchesCount ) ;
if ( ! this.searchMatchesCount ) {
message = l10n.noWidgetsFound;
}
wp.a11y.speak( message );
},
/**
* Changes visibility of available widgets.
*/
updateList: function() {
this.collection.each( function( widget ) {
var widgetTpl = $( '#widget-tpl-' + widget.id );
widgetTpl.toggle( widget.get( 'search_matched' ) && ! widget.get( 'is_disabled' ) );
if ( widget.get( 'is_disabled' ) && widgetTpl.is( this.selected ) ) {
this.selected = null;
}
} );
},
/**
* Highlights a widget.
*/
select: function( widgetTpl ) {
this.selected = $( widgetTpl );
this.selected.siblings( '.widget-tpl' ).removeClass( 'selected' );
this.selected.addClass( 'selected' );
},
/**
* Highlights a widget on focus.
*/
focus: function( event ) {
this.select( $( event.currentTarget ) );
},
/**
* Handles submit for keypress and click on widget.
*/
_submit: function( event ) {
// Only proceed with keypress if it is Enter or Spacebar.
if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
return;
}
this.submit( $( event.currentTarget ) );
},
/**
* Adds a selected widget to the sidebar.
*/
submit: function( widgetTpl ) {
var widgetId, widget, widgetFormControl;
if ( ! widgetTpl ) {
widgetTpl = this.selected;
}
if ( ! widgetTpl || ! this.currentSidebarControl ) {
return;
}
this.select( widgetTpl );
widgetId = $( this.selected ).data( 'widget-id' );
widget = this.collection.findWhere( { id: widgetId } );
if ( ! widget ) {
return;
}
widgetFormControl = this.currentSidebarControl.addWidget( widget.get( 'id_base' ) );
if ( widgetFormControl ) {
widgetFormControl.focus();
}
this.close();
},
/**
* Opens the panel.
*/
open: function( sidebarControl ) {
this.currentSidebarControl = sidebarControl;
// Wide widget controls appear over the preview, and so they need to be collapsed when the panel opens.
_( this.currentSidebarControl.getWidgetFormControls() ).each( function( control ) {
if ( control.params.is_wide ) {
control.collapseForm();
}
} );
if ( api.section.has( 'publish_settings' ) ) {
api.section( 'publish_settings' ).collapse();
}
$( 'body' ).addClass( 'adding-widget' );
this.$el.find( '.selected' ).removeClass( 'selected' );
// Reset search.
this.collection.doSearch( '' );
if ( ! api.settings.browser.mobile ) {
this.$search.trigger( 'focus' );
}
},
/**
* Closes the panel.
*/
close: function( options ) {
options = options || {};
if ( options.returnFocus && this.currentSidebarControl ) {
this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
}
this.currentSidebarControl = null;
this.selected = null;
$( 'body' ).removeClass( 'adding-widget' );
this.$search.val( '' ).trigger( 'input' );
},
/**
* Adds keyboard accessibility to the panel.
*/
keyboardAccessible: function( event ) {
var isEnter = ( event.which === 13 ),
isEsc = ( event.which === 27 ),
isDown = ( event.which === 40 ),
isUp = ( event.which === 38 ),
isTab = ( event.which === 9 ),
isShift = ( event.shiftKey ),
selected = null,
firstVisible = this.$el.find( '> .widget-tpl:visible:first' ),
lastVisible = this.$el.find( '> .widget-tpl:visible:last' ),
isSearchFocused = $( event.target ).is( this.$search ),
isLastWidgetFocused = $( event.target ).is( '.widget-tpl:visible:last' );
if ( isDown || isUp ) {
if ( isDown ) {
if ( isSearchFocused ) {
selected = firstVisible;
} else if ( this.selected && this.selected.nextAll( '.widget-tpl:visible' ).length !== 0 ) {
selected = this.selected.nextAll( '.widget-tpl:visible:first' );
}
} else if ( isUp ) {
if ( isSearchFocused ) {
selected = lastVisible;
} else if ( this.selected && this.selected.prevAll( '.widget-tpl:visible' ).length !== 0 ) {
selected = this.selected.prevAll( '.widget-tpl:visible:first' );
}
}
this.select( selected );
if ( selected ) {
selected.trigger( 'focus' );
} else {
this.$search.trigger( 'focus' );
}
return;
}
// If enter pressed but nothing entered, don't do anything.
if ( isEnter && ! this.$search.val() ) {
return;
}
if ( isEnter ) {
this.submit();
} else if ( isEsc ) {
this.close( { returnFocus: true } );
}
if ( this.currentSidebarControl && isTab && ( isShift && isSearchFocused || ! isShift && isLastWidgetFocused ) ) {
this.currentSidebarControl.container.find( '.add-new-widget' ).focus();
event.preventDefault();
}
}
});
/**
* Handlers for the widget-synced event, organized by widget ID base.
* Other widgets may provide their own update handlers by adding
* listeners for the widget-synced event.
*
* @alias wp.customize.Widgets.formSyncHandlers
*/
api.Widgets.formSyncHandlers = {
/**
* @param {jQuery.Event} e
* @param {jQuery} widget
* @param {string} newForm
*/
rss: function( e, widget, newForm ) {
var oldWidgetError = widget.find( '.widget-error:first' ),
newWidgetError = $( '
' + newForm + '
' ).find( '.widget-error:first' );
if ( oldWidgetError.length && newWidgetError.length ) {
oldWidgetError.replaceWith( newWidgetError );
} else if ( oldWidgetError.length ) {
oldWidgetError.remove();
} else if ( newWidgetError.length ) {
widget.find( '.widget-content:first' ).prepend( newWidgetError );
}
}
};
api.Widgets.WidgetControl = api.Control.extend(/** @lends wp.customize.Widgets.WidgetControl.prototype */{
defaultExpandedArguments: {
duration: 'fast',
completeCallback: $.noop
},
/**
* wp.customize.Widgets.WidgetControl
*
* Customizer control for widgets.
* Note that 'widget_form' must match the WP_Widget_Form_Customize_Control::$type
*
* @since 4.1.0
*
* @constructs wp.customize.Widgets.WidgetControl
* @augments wp.customize.Control
*/
initialize: function( id, options ) {
var control = this;
control.widgetControlEmbedded = false;
control.widgetContentEmbedded = false;
control.expanded = new api.Value( false );
control.expandedArgumentsQueue = [];
control.expanded.bind( function( expanded ) {
var args = control.expandedArgumentsQueue.shift();
args = $.extend( {}, control.defaultExpandedArguments, args );
control.onChangeExpanded( expanded, args );
});
control.altNotice = true;
api.Control.prototype.initialize.call( control, id, options );
},
/**
* Set up the control.
*
* @since 3.9.0
*/
ready: function() {
var control = this;
/*
* Embed a placeholder once the section is expanded. The full widget
* form content will be embedded once the control itself is expanded,
* and at this point the widget-added event will be triggered.
*/
if ( ! control.section() ) {
control.embedWidgetControl();
} else {
api.section( control.section(), function( section ) {
var onExpanded = function( isExpanded ) {
if ( isExpanded ) {
control.embedWidgetControl();
section.expanded.unbind( onExpanded );
}
};
if ( section.expanded() ) {
onExpanded( true );
} else {
section.expanded.bind( onExpanded );
}
} );
}
},
/**
* Embed the .widget element inside the li container.
*
* @since 4.4.0
*/
embedWidgetControl: function() {
var control = this, widgetControl;
if ( control.widgetControlEmbedded ) {
return;
}
control.widgetControlEmbedded = true;
widgetControl = $( control.params.widget_control );
control.container.append( widgetControl );
control._setupModel();
control._setupWideWidget();
control._setupControlToggle();
control._setupWidgetTitle();
control._setupReorderUI();
control._setupHighlightEffects();
control._setupUpdateUI();
control._setupRemoveUI();
},
/**
* Embed the actual widget form inside of .widget-content and finally trigger the widget-added event.
*
* @since 4.4.0
*/
embedWidgetContent: function() {
var control = this, widgetContent;
control.embedWidgetControl();
if ( control.widgetContentEmbedded ) {
return;
}
control.widgetContentEmbedded = true;
// Update the notification container element now that the widget content has been embedded.
control.notifications.container = control.getNotificationsContainerElement();
control.notifications.render();
widgetContent = $( control.params.widget_content );
control.container.find( '.widget-content:first' ).append( widgetContent );
/*
* Trigger widget-added event so that plugins can attach any event
* listeners and dynamic UI elements.
*/
$( document ).trigger( 'widget-added', [ control.container.find( '.widget:first' ) ] );
},
/**
* Handle changes to the setting
*/
_setupModel: function() {
var self = this, rememberSavedWidgetId;
// Remember saved widgets so we know which to trash (move to inactive widgets sidebar).
rememberSavedWidgetId = function() {
api.Widgets.savedWidgetIds[self.params.widget_id] = true;
};
api.bind( 'ready', rememberSavedWidgetId );
api.bind( 'saved', rememberSavedWidgetId );
this._updateCount = 0;
this.isWidgetUpdating = false;
this.liveUpdateMode = true;
// Update widget whenever model changes.
this.setting.bind( function( to, from ) {
if ( ! _( from ).isEqual( to ) && ! self.isWidgetUpdating ) {
self.updateWidget( { instance: to } );
}
} );
},
/**
* Add special behaviors for wide widget controls
*/
_setupWideWidget: function() {
var self = this, $widgetInside, $widgetForm, $customizeSidebar,
$themeControlsContainer, positionWidget;
if ( ! this.params.is_wide || $( window ).width() <= 640 /* max-width breakpoint in customize-controls.css */ ) {
return;
}
$widgetInside = this.container.find( '.widget-inside' );
$widgetForm = $widgetInside.find( '> .form' );
$customizeSidebar = $( '.wp-full-overlay-sidebar-content:first' );
this.container.addClass( 'wide-widget-control' );
this.container.find( '.form:first' ).css( {
'max-width': this.params.width,
'min-height': this.params.height
} );
/**
* Keep the widget-inside positioned so the top of fixed-positioned
* element is at the same top position as the widget-top. When the
* widget-top is scrolled out of view, keep the widget-top in view;
* likewise, don't allow the widget to drop off the bottom of the window.
* If a widget is too tall to fit in the window, don't let the height
* exceed the window height so that the contents of the widget control
* will become scrollable (overflow:auto).
*/
positionWidget = function() {
var offsetTop = self.container.offset().top,
windowHeight = $( window ).height(),
formHeight = $widgetForm.outerHeight(),
top;
$widgetInside.css( 'max-height', windowHeight );
top = Math.max(
0, // Prevent top from going off screen.
Math.min(
Math.max( offsetTop, 0 ), // Distance widget in panel is from top of screen.
windowHeight - formHeight // Flush up against bottom of screen.
)
);
$widgetInside.css( 'top', top );
};
$themeControlsContainer = $( '#customize-theme-controls' );
this.container.on( 'expand', function() {
positionWidget();
$customizeSidebar.on( 'scroll', positionWidget );
$( window ).on( 'resize', positionWidget );
$themeControlsContainer.on( 'expanded collapsed', positionWidget );
} );
this.container.on( 'collapsed', function() {
$customizeSidebar.off( 'scroll', positionWidget );
$( window ).off( 'resize', positionWidget );
$themeControlsContainer.off( 'expanded collapsed', positionWidget );
} );
// Reposition whenever a sidebar's widgets are changed.
api.each( function( setting ) {
if ( 0 === setting.id.indexOf( 'sidebars_widgets[' ) ) {
setting.bind( function() {
if ( self.container.hasClass( 'expanded' ) ) {
positionWidget();
}
} );
}
} );
},
/**
* Show/hide the control when clicking on the form title, when clicking
* the close button
*/
_setupControlToggle: function() {
var self = this, $closeBtn;
this.container.find( '.widget-top' ).on( 'click', function( e ) {
e.preventDefault();
var sidebarWidgetsControl = self.getSidebarWidgetsControl();
if ( sidebarWidgetsControl.isReordering ) {
return;
}
self.expanded( ! self.expanded() );
} );
$closeBtn = this.container.find( '.widget-control-close' );
$closeBtn.on( 'click', function() {
self.collapse();
self.container.find( '.widget-top .widget-action:first' ).focus(); // Keyboard accessibility.
} );
},
/**
* Update the title of the form if a title field is entered
*/
_setupWidgetTitle: function() {
var self = this, updateTitle;
updateTitle = function() {
var title = self.setting().title,
inWidgetTitle = self.container.find( '.in-widget-title' );
if ( title ) {
inWidgetTitle.text( ': ' + title );
} else {
inWidgetTitle.text( '' );
}
};
this.setting.bind( updateTitle );
updateTitle();
},
/**
* Set up the widget-reorder-nav
*/
_setupReorderUI: function() {
var self = this, selectSidebarItem, $moveWidgetArea,
$reorderNav, updateAvailableSidebars, template;
/**
* select the provided sidebar list item in the move widget area
*
* @param {jQuery} li
*/
selectSidebarItem = function( li ) {
li.siblings( '.selected' ).removeClass( 'selected' );
li.addClass( 'selected' );
var isSelfSidebar = ( li.data( 'id' ) === self.params.sidebar_id );
self.container.find( '.move-widget-btn' ).prop( 'disabled', isSelfSidebar );
};
/**
* Add the widget reordering elements to the widget control
*/
this.container.find( '.widget-title-action' ).after( $( api.Widgets.data.tpl.widgetReorderNav ) );
template = _.template( api.Widgets.data.tpl.moveWidgetArea );
$moveWidgetArea = $( template( {
sidebars: _( api.Widgets.registeredSidebars.toArray() ).pluck( 'attributes' )
} )
);
this.container.find( '.widget-top' ).after( $moveWidgetArea );
/**
* Update available sidebars when their rendered state changes
*/
updateAvailableSidebars = function() {
var $sidebarItems = $moveWidgetArea.find( 'li' ), selfSidebarItem,
renderedSidebarCount = 0;
selfSidebarItem = $sidebarItems.filter( function(){
return $( this ).data( 'id' ) === self.params.sidebar_id;
} );
$sidebarItems.each( function() {
var li = $( this ),
sidebarId, sidebar, sidebarIsRendered;
sidebarId = li.data( 'id' );
sidebar = api.Widgets.registeredSidebars.get( sidebarId );
sidebarIsRendered = sidebar.get( 'is_rendered' );
li.toggle( sidebarIsRendered );
if ( sidebarIsRendered ) {
renderedSidebarCount += 1;
}
if ( li.hasClass( 'selected' ) && ! sidebarIsRendered ) {
selectSidebarItem( selfSidebarItem );
}
} );
if ( renderedSidebarCount > 1 ) {
self.container.find( '.move-widget' ).show();
} else {
self.container.find( '.move-widget' ).hide();
}
};
updateAvailableSidebars();
api.Widgets.registeredSidebars.on( 'change:is_rendered', updateAvailableSidebars );
/**
* Handle clicks for up/down/move on the reorder nav
*/
$reorderNav = this.container.find( '.widget-reorder-nav' );
$reorderNav.find( '.move-widget, .move-widget-down, .move-widget-up' ).each( function() {
$( this ).prepend( self.container.find( '.widget-title' ).text() + ': ' );
} ).on( 'click keypress', function( event ) {
if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
return;
}
$( this ).trigger( 'focus' );
if ( $( this ).is( '.move-widget' ) ) {
self.toggleWidgetMoveArea();
} else {
var isMoveDown = $( this ).is( '.move-widget-down' ),
isMoveUp = $( this ).is( '.move-widget-up' ),
i = self.getWidgetSidebarPosition();
if ( ( isMoveUp && i === 0 ) || ( isMoveDown && i === self.getSidebarWidgetsControl().setting().length - 1 ) ) {
return;
}
if ( isMoveUp ) {
self.moveUp();
wp.a11y.speak( l10n.widgetMovedUp );
} else {
self.moveDown();
wp.a11y.speak( l10n.widgetMovedDown );
}
$( this ).trigger( 'focus' ); // Re-focus after the container was moved.
}
} );
/**
* Handle selecting a sidebar to move to
*/
this.container.find( '.widget-area-select' ).on( 'click keypress', 'li', function( event ) {
if ( event.type === 'keypress' && ( event.which !== 13 && event.which !== 32 ) ) {
return;
}
event.preventDefault();
selectSidebarItem( $( this ) );
} );
/**
* Move widget to another sidebar
*/
this.container.find( '.move-widget-btn' ).click( function() {
self.getSidebarWidgetsControl().toggleReordering( false );
var oldSidebarId = self.params.sidebar_id,
newSidebarId = self.container.find( '.widget-area-select li.selected' ).data( 'id' ),
oldSidebarWidgetsSetting, newSidebarWidgetsSetting,
oldSidebarWidgetIds, newSidebarWidgetIds, i;
oldSidebarWidgetsSetting = api( 'sidebars_widgets[' + oldSidebarId + ']' );
newSidebarWidgetsSetting = api( 'sidebars_widgets[' + newSidebarId + ']' );
oldSidebarWidgetIds = Array.prototype.slice.call( oldSidebarWidgetsSetting() );
newSidebarWidgetIds = Array.prototype.slice.call( newSidebarWidgetsSetting() );
i = self.getWidgetSidebarPosition();
oldSidebarWidgetIds.splice( i, 1 );
newSidebarWidgetIds.push( self.params.widget_id );
oldSidebarWidgetsSetting( oldSidebarWidgetIds );
newSidebarWidgetsSetting( newSidebarWidgetIds );
self.focus();
} );
},
/**
* Highlight widgets in preview when interacted with in the Customizer
*/
_setupHighlightEffects: function() {
var self = this;
// Highlight whenever hovering or clicking over the form.
this.container.on( 'mouseenter click', function() {
self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
} );
// Highlight when the setting is updated.
this.setting.bind( function() {
self.setting.previewer.send( 'highlight-widget', self.params.widget_id );
} );
},
/**
* Set up event handlers for widget updating
*/
_setupUpdateUI: function() {
var self = this, $widgetRoot, $widgetContent,
$saveBtn, updateWidgetDebounced, formSyncHandler;
$widgetRoot = this.container.find( '.widget:first' );
$widgetContent = $widgetRoot.find( '.widget-content:first' );
// Configure update button.
$saveBtn = this.container.find( '.widget-control-save' );
$saveBtn.val( l10n.saveBtnLabel );
$saveBtn.attr( 'title', l10n.saveBtnTooltip );
$saveBtn.removeClass( 'button-primary' );
$saveBtn.on( 'click', function( e ) {
e.preventDefault();
self.updateWidget( { disable_form: true } ); // @todo disable_form is unused?
} );
updateWidgetDebounced = _.debounce( function() {
self.updateWidget();
}, 250 );
// Trigger widget form update when hitting Enter within an input.
$widgetContent.on( 'keydown', 'input', function( e ) {
if ( 13 === e.which ) { // Enter.
e.preventDefault();
self.updateWidget( { ignoreActiveElement: true } );
}
} );
// Handle widgets that support live previews.
$widgetContent.on( 'change input propertychange', ':input', function( e ) {
if ( ! self.liveUpdateMode ) {
return;
}
if ( e.type === 'change' || ( this.checkValidity && this.checkValidity() ) ) {
updateWidgetDebounced();
}
} );
// Remove loading indicators when the setting is saved and the preview updates.
this.setting.previewer.channel.bind( 'synced', function() {
self.container.removeClass( 'previewer-loading' );
} );
api.previewer.bind( 'widget-updated', function( updatedWidgetId ) {
if ( updatedWidgetId === self.params.widget_id ) {
self.container.removeClass( 'previewer-loading' );
}
} );
formSyncHandler = api.Widgets.formSyncHandlers[ this.params.widget_id_base ];
if ( formSyncHandler ) {
$( document ).on( 'widget-synced', function( e, widget ) {
if ( $widgetRoot.is( widget ) ) {
formSyncHandler.apply( document, arguments );
}
} );
}
},
/**
* Update widget control to indicate whether it is currently rendered.
*
* Overrides api.Control.toggle()
*
* @since 4.1.0
*
* @param {boolean} active
* @param {Object} args
* @param {function} args.completeCallback
*/
onChangeActive: function ( active, args ) {
// Note: there is a second 'args' parameter being passed, merged on top of this.defaultActiveArguments.
this.container.toggleClass( 'widget-rendered', active );
if ( args.completeCallback ) {
args.completeCallback();
}
},
/**
* Set up event handlers for widget removal
*/
_setupRemoveUI: function() {
var self = this, $removeBtn, replaceDeleteWithRemove;
// Configure remove button.
$removeBtn = this.container.find( '.widget-control-remove' );
$removeBtn.on( 'click', function() {
// Find an adjacent element to add focus to when this widget goes away.
var $adjacentFocusTarget;
if ( self.container.next().is( '.customize-control-widget_form' ) ) {
$adjacentFocusTarget = self.container.next().find( '.widget-action:first' );
} else if ( self.container.prev().is( '.customize-control-widget_form' ) ) {
$adjacentFocusTarget = self.container.prev().find( '.widget-action:first' );
} else {
$adjacentFocusTarget = self.container.next( '.customize-control-sidebar_widgets' ).find( '.add-new-widget:first' );
}
self.container.slideUp( function() {
var sidebarsWidgetsControl = api.Widgets.getSidebarWidgetControlContainingWidget( self.params.widget_id ),
sidebarWidgetIds, i;
if ( ! sidebarsWidgetsControl ) {
return;
}
sidebarWidgetIds = sidebarsWidgetsControl.setting().slice();
i = _.indexOf( sidebarWidgetIds, self.params.widget_id );
if ( -1 === i ) {
return;
}
sidebarWidgetIds.splice( i, 1 );
sidebarsWidgetsControl.setting( sidebarWidgetIds );
$adjacentFocusTarget.focus(); // Keyboard accessibility.
} );
} );
replaceDeleteWithRemove = function() {
$removeBtn.text( l10n.removeBtnLabel ); // wp_widget_control() outputs the button as "Delete".
$removeBtn.attr( 'title', l10n.removeBtnTooltip );
};
if ( this.params.is_new ) {
api.bind( 'saved', replaceDeleteWithRemove );
} else {
replaceDeleteWithRemove();
}
},
/**
* Find all inputs in a widget container that should be considered when
* comparing the loaded form with the sanitized form, whose fields will
* be aligned to copy the sanitized over. The elements returned by this
* are passed into this._getInputsSignature(), and they are iterated
* over when copying sanitized values over to the form loaded.
*
* @param {jQuery} container element in which to look for inputs
* @return {jQuery} inputs
* @private
*/
_getInputs: function( container ) {
return $( container ).find( ':input[name]' );
},
/**
* Iterate over supplied inputs and create a signature string for all of them together.
* This string can be used to compare whether or not the form has all of the same fields.
*
* @param {jQuery} inputs
* @return {string}
* @private
*/
_getInputsSignature: function( inputs ) {
var inputsSignatures = _( inputs ).map( function( input ) {
var $input = $( input ), signatureParts;
if ( $input.is( ':checkbox, :radio' ) ) {
signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ), $input.prop( 'value' ) ];
} else {
signatureParts = [ $input.attr( 'id' ), $input.attr( 'name' ) ];
}
return signatureParts.join( ',' );
} );
return inputsSignatures.join( ';' );
},
/**
* Get the state for an input depending on its type.
*
* @param {jQuery|Element} input
* @return {string|boolean|Array|*}
* @private
*/
_getInputState: function( input ) {
input = $( input );
if ( input.is( ':radio, :checkbox' ) ) {
return input.prop( 'checked' );
} else if ( input.is( 'select[multiple]' ) ) {
return input.find( 'option:selected' ).map( function () {
return $( this ).val();
} ).get();
} else {
return input.val();
}
},
/**
* Update an input's state based on its type.
*
* @param {jQuery|Element} input
* @param {string|boolean|Array|*} state
* @private
*/
_setInputState: function ( input, state ) {
input = $( input );
if ( input.is( ':radio, :checkbox' ) ) {
input.prop( 'checked', state );
} else if ( input.is( 'select[multiple]' ) ) {
if ( ! Array.isArray( state ) ) {
state = [];
} else {
// Make sure all state items are strings since the DOM value is a string.
state = _.map( state, function ( value ) {
return String( value );
} );
}
input.find( 'option' ).each( function () {
$( this ).prop( 'selected', -1 !== _.indexOf( state, String( this.value ) ) );
} );
} else {
input.val( state );
}
},
/***********************************************************************
* Begin public API methods
**********************************************************************/
/**
* @return {wp.customize.controlConstructor.sidebar_widgets[]}
*/
getSidebarWidgetsControl: function() {
var settingId, sidebarWidgetsControl;
settingId = 'sidebars_widgets[' + this.params.sidebar_id + ']';
sidebarWidgetsControl = api.control( settingId );
if ( ! sidebarWidgetsControl ) {
return;
}
return sidebarWidgetsControl;
},
/**
* Submit the widget form via Ajax and get back the updated instance,
* along with the new widget control form to render.
*
* @param {Object} [args]
* @param {Object|null} [args.instance=null] When the model changes, the instance is sent here; otherwise, the inputs from the form are used
* @param {Function|null} [args.complete=null] Function which is called when the request finishes. Context is bound to the control. First argument is any error. Following arguments are for success.
* @param {boolean} [args.ignoreActiveElement=false] Whether or not updating a field will be deferred if focus is still on the element.
*/
updateWidget: function( args ) {
var self = this, instanceOverride, completeCallback, $widgetRoot, $widgetContent,
updateNumber, params, data, $inputs, processing, jqxhr, isChanged;
// The updateWidget logic requires that the form fields to be fully present.
self.embedWidgetContent();
args = $.extend( {
instance: null,
complete: null,
ignoreActiveElement: false
}, args );
instanceOverride = args.instance;
completeCallback = args.complete;
this._updateCount += 1;
updateNumber = this._updateCount;
$widgetRoot = this.container.find( '.widget:first' );
$widgetContent = $widgetRoot.find( '.widget-content:first' );
// Remove a previous error message.
$widgetContent.find( '.widget-error' ).remove();
this.container.addClass( 'widget-form-loading' );
this.container.addClass( 'previewer-loading' );
processing = api.state( 'processing' );
processing( processing() + 1 );
if ( ! this.liveUpdateMode ) {
this.container.addClass( 'widget-form-disabled' );
}
params = {};
params.action = 'update-widget';
params.wp_customize = 'on';
params.nonce = api.settings.nonce['update-widget'];
params.customize_theme = api.settings.theme.stylesheet;
params.customized = wp.customize.previewer.query().customized;
data = $.param( params );
$inputs = this._getInputs( $widgetContent );
/*
* Store the value we're submitting in data so that when the response comes back,
* we know if it got sanitized; if there is no difference in the sanitized value,
* then we do not need to touch the UI and mess up the user's ongoing editing.
*/
$inputs.each( function() {
$( this ).data( 'state' + updateNumber, self._getInputState( this ) );
} );
if ( instanceOverride ) {
data += '&' + $.param( { 'sanitized_widget_setting': JSON.stringify( instanceOverride ) } );
} else {
data += '&' + $inputs.serialize();
}
data += '&' + $widgetContent.find( '~ :input' ).serialize();
if ( this._previousUpdateRequest ) {
this._previousUpdateRequest.abort();
}
jqxhr = $.post( wp.ajax.settings.url, data );
this._previousUpdateRequest = jqxhr;
jqxhr.done( function( r ) {
var message, sanitizedForm, $sanitizedInputs, hasSameInputsInResponse,
isLiveUpdateAborted = false;
// Check if the user is logged out.
if ( '0' === r ) {
api.previewer.preview.iframe.hide();
api.previewer.login().done( function() {
self.updateWidget( args );
api.previewer.preview.iframe.show();
} );
return;
}
// Check for cheaters.
if ( '-1' === r ) {
api.previewer.cheatin();
return;
}
if ( r.success ) {
sanitizedForm = $( '' + r.data.form + '
' );
$sanitizedInputs = self._getInputs( sanitizedForm );
hasSameInputsInResponse = self._getInputsSignature( $inputs ) === self._getInputsSignature( $sanitizedInputs );
// Restore live update mode if sanitized fields are now aligned with the existing fields.
if ( hasSameInputsInResponse && ! self.liveUpdateMode ) {
self.liveUpdateMode = true;
self.container.removeClass( 'widget-form-disabled' );
self.container.find( 'input[name="savewidget"]' ).hide();
}
// Sync sanitized field states to existing fields if they are aligned.
if ( hasSameInputsInResponse && self.liveUpdateMode ) {
$inputs.each( function( i ) {
var $input = $( this ),
$sanitizedInput = $( $sanitizedInputs[i] ),
submittedState, sanitizedState, canUpdateState;
submittedState = $input.data( 'state' + updateNumber );
sanitizedState = self._getInputState( $sanitizedInput );
$input.data( 'sanitized', sanitizedState );
canUpdateState = ( ! _.isEqual( submittedState, sanitizedState ) && ( args.ignoreActiveElement || ! $input.is( document.activeElement ) ) );
if ( canUpdateState ) {
self._setInputState( $input, sanitizedState );
}
} );
$( document ).trigger( 'widget-synced', [ $widgetRoot, r.data.form ] );
// Otherwise, if sanitized fields are not aligned with existing fields, disable live update mode if enabled.
} else if ( self.liveUpdateMode ) {
self.liveUpdateMode = false;
self.container.find( 'input[name="savewidget"]' ).show();
isLiveUpdateAborted = true;
// Otherwise, replace existing form with the sanitized form.
} else {
$widgetContent.html( r.data.form );
self.container.removeClass( 'widget-form-disabled' );
$( document ).trigger( 'widget-updated', [ $widgetRoot ] );
}
/**
* If the old instance is identical to the new one, there is nothing new
* needing to be rendered, and so we can preempt the event for the
* preview finishing loading.
*/
isChanged = ! isLiveUpdateAborted && ! _( self.setting() ).isEqual( r.data.instance );
if ( isChanged ) {
self.isWidgetUpdating = true; // Suppress triggering another updateWidget.
self.setting( r.data.instance );
self.isWidgetUpdating = false;
} else {
// No change was made, so stop the spinner now instead of when the preview would updates.
self.container.removeClass( 'previewer-loading' );
}
if ( completeCallback ) {
completeCallback.call( self, null, { noChange: ! isChanged, ajaxFinished: true } );
}
} else {
// General error message.
message = l10n.error;
if ( r.data && r.data.message ) {
message = r.data.message;
}
if ( completeCallback ) {
completeCallback.call( self, message );
} else {
$widgetContent.prepend( '' + message + '
' );
}
}
} );
jqxhr.fail( function( jqXHR, textStatus ) {
if ( completeCallback ) {
completeCallback.call( self, textStatus );
}
} );
jqxhr.always( function() {
self.container.removeClass( 'widget-form-loading' );
$inputs.each( function() {
$( this ).removeData( 'state' + updateNumber );
} );
processing( processing() - 1 );
} );
},
/**
* Expand the accordion section containing a control
*/
expandControlSection: function() {
api.Control.prototype.expand.call( this );
},
/**
* @since 4.1.0
*
* @param {Boolean} expanded
* @param {Object} [params]
* @return {Boolean} False if state already applied.
*/
_toggleExpanded: api.Section.prototype._toggleExpanded,
/**
* @since 4.1.0
*
* @param {Object} [params]
* @return {Boolean} False if already expanded.
*/
expand: api.Section.prototype.expand,
/**
* Expand the widget form control
*
* @deprecated 4.1.0 Use this.expand() instead.
*/
expandForm: function() {
this.expand();
},
/**
* @since 4.1.0
*
* @param {Object} [params]
* @return {Boolean} False if already collapsed.
*/
collapse: api.Section.prototype.collapse,
/**
* Collapse the widget form control
*
* @deprecated 4.1.0 Use this.collapse() instead.
*/
collapseForm: function() {
this.collapse();
},
/**
* Expand or collapse the widget control
*
* @deprecated this is poor naming, and it is better to directly set control.expanded( showOrHide )
*
* @param {boolean|undefined} [showOrHide] If not supplied, will be inverse of current visibility
*/
toggleForm: function( showOrHide ) {
if ( typeof showOrHide === 'undefined' ) {
showOrHide = ! this.expanded();
}
this.expanded( showOrHide );
},
/**
* Respond to change in the expanded state.
*
* @param {boolean} expanded
* @param {Object} args merged on top of this.defaultActiveArguments
*/
onChangeExpanded: function ( expanded, args ) {
var self = this, $widget, $inside, complete, prevComplete, expandControl, $toggleBtn;
self.embedWidgetControl(); // Make sure the outer form is embedded so that the expanded state can be set in the UI.
if ( expanded ) {
self.embedWidgetContent();
}
// If the expanded state is unchanged only manipulate container expanded states.
if ( args.unchanged ) {
if ( expanded ) {
api.Control.prototype.expand.call( self, {
completeCallback: args.completeCallback
});
}
return;
}
$widget = this.container.find( 'div.widget:first' );
$inside = $widget.find( '.widget-inside:first' );
$toggleBtn = this.container.find( '.widget-top button.widget-action' );
expandControl = function() {
// Close all other widget controls before expanding this one.
api.control.each( function( otherControl ) {
if ( self.params.type === otherControl.params.type && self !== otherControl ) {
otherControl.collapse();
}
} );
complete = function() {
self.container.removeClass( 'expanding' );
self.container.addClass( 'expanded' );
$widget.addClass( 'open' );
$toggleBtn.attr( 'aria-expanded', 'true' );
self.container.trigger( 'expanded' );
};
if ( args.completeCallback ) {
prevComplete = complete;
complete = function () {
prevComplete();
args.completeCallback();
};
}
if ( self.params.is_wide ) {
$inside.fadeIn( args.duration, complete );
} else {
$inside.slideDown( args.duration, complete );
}
self.container.trigger( 'expand' );
self.container.addClass( 'expanding' );
};
if ( $toggleBtn.attr( 'aria-expanded' ) === 'false' ) {
if ( api.section.has( self.section() ) ) {
api.section( self.section() ).expand( {
completeCallback: expandControl
} );
} else {
expandControl();
}
} else {
complete = function() {
self.container.removeClass( 'collapsing' );
self.container.removeClass( 'expanded' );
$widget.removeClass( 'open' );
$toggleBtn.attr( 'aria-expanded', 'false' );
self.container.trigger( 'collapsed' );
};
if ( args.completeCallback ) {
prevComplete = complete;
complete = function () {
prevComplete();
args.completeCallback();
};
}
self.container.trigger( 'collapse' );
self.container.addClass( 'collapsing' );
if ( self.params.is_wide ) {
$inside.fadeOut( args.duration, complete );
} else {
$inside.slideUp( args.duration, function() {
$widget.css( { width:'', margin:'' } );
complete();
} );
}
}
},
/**
* Get the position (index) of the widget in the containing sidebar
*
* @return {number}
*/
getWidgetSidebarPosition: function() {
var sidebarWidgetIds, position;
sidebarWidgetIds = this.getSidebarWidgetsControl().setting();
position = _.indexOf( sidebarWidgetIds, this.params.widget_id );
if ( position === -1 ) {
return;
}
return position;
},
/**
* Move widget up one in the sidebar
*/
moveUp: function() {
this._moveWidgetByOne( -1 );
},
/**
* Move widget up one in the sidebar
*/
moveDown: function() {
this._moveWidgetByOne( 1 );
},
/**
* @private
*
* @param {number} offset 1|-1
*/
_moveWidgetByOne: function( offset ) {
var i, sidebarWidgetsSetting, sidebarWidgetIds, adjacentWidgetId;
i = this.getWidgetSidebarPosition();
sidebarWidgetsSetting = this.getSidebarWidgetsControl().setting;
sidebarWidgetIds = Array.prototype.slice.call( sidebarWidgetsSetting() ); // Clone.
adjacentWidgetId = sidebarWidgetIds[i + offset];
sidebarWidgetIds[i + offset] = this.params.widget_id;
sidebarWidgetIds[i] = adjacentWidgetId;
sidebarWidgetsSetting( sidebarWidgetIds );
},
/**
* Toggle visibility of the widget move area
*
* @param {boolean} [showOrHide]
*/
toggleWidgetMoveArea: function( showOrHide ) {
var self = this, $moveWidgetArea;
$moveWidgetArea = this.container.find( '.move-widget-area' );
if ( typeof showOrHide === 'undefined' ) {
showOrHide = ! $moveWidgetArea.hasClass( 'active' );
}
if ( showOrHide ) {
// Reset the selected sidebar.
$moveWidgetArea.find( '.selected' ).removeClass( 'selected' );
$moveWidgetArea.find( 'li' ).filter( function() {
return $( this ).data( 'id' ) === self.params.sidebar_id;
} ).addClass( 'selected' );
this.container.find( '.move-widget-btn' ).prop( 'disabled', true );
}
$moveWidgetArea.toggleClass( 'active', showOrHide );
},
/**
* Highlight the widget control and section
*/
highlightSectionAndControl: function() {
var $target;
if ( this.container.is( ':hidden' ) ) {
$target = this.container.closest( '.control-section' );
} else {
$target = this.container;
}
$( '.highlighted' ).removeClass( 'highlighted' );
$target.addClass( 'highlighted' );
setTimeout( function() {
$target.removeClass( 'highlighted' );
}, 500 );
}
} );
/**
* wp.customize.Widgets.WidgetsPanel
*
* Customizer panel containing the widget area sections.
*
* @since 4.4.0
*
* @class wp.customize.Widgets.WidgetsPanel
* @augments wp.customize.Panel
*/
api.Widgets.WidgetsPanel = api.Panel.extend(/** @lends wp.customize.Widgets.WigetsPanel.prototype */{
/**
* Add and manage the display of the no-rendered-areas notice.
*
* @since 4.4.0
*/
ready: function () {
var panel = this;
api.Panel.prototype.ready.call( panel );
panel.deferred.embedded.done(function() {
var panelMetaContainer, noticeContainer, updateNotice, getActiveSectionCount, shouldShowNotice;
panelMetaContainer = panel.container.find( '.panel-meta' );
// @todo This should use the Notifications API introduced to panels. See .
noticeContainer = $( '', {
'class': 'no-widget-areas-rendered-notice',
'role': 'alert'
});
panelMetaContainer.append( noticeContainer );
/**
* Get the number of active sections in the panel.
*
* @return {number} Number of active sidebar sections.
*/
getActiveSectionCount = function() {
return _.filter( panel.sections(), function( section ) {
return 'sidebar' === section.params.type && section.active();
} ).length;
};
/**
* Determine whether or not the notice should be displayed.
*
* @return {boolean}
*/
shouldShowNotice = function() {
var activeSectionCount = getActiveSectionCount();
if ( 0 === activeSectionCount ) {
return true;
} else {
return activeSectionCount !== api.Widgets.data.registeredSidebars.length;
}
};
/**
* Update the notice.
*
* @return {void}
*/
updateNotice = function() {
var activeSectionCount = getActiveSectionCount(), someRenderedMessage, nonRenderedAreaCount, registeredAreaCount;
noticeContainer.empty();
registeredAreaCount = api.Widgets.data.registeredSidebars.length;
if ( activeSectionCount !== registeredAreaCount ) {
if ( 0 !== activeSectionCount ) {
nonRenderedAreaCount = registeredAreaCount - activeSectionCount;
someRenderedMessage = l10n.someAreasShown[ nonRenderedAreaCount ];
} else {
someRenderedMessage = l10n.noAreasShown;
}
if ( someRenderedMessage ) {
noticeContainer.append( $( '', {
text: someRenderedMessage
} ) );
}
noticeContainer.append( $( '', {
text: l10n.navigatePreview
} ) );
}
};
updateNotice();
/*
* Set the initial visibility state for rendered notice.
* Update the visibility of the notice whenever a reflow happens.
*/
noticeContainer.toggle( shouldShowNotice() );
api.previewer.deferred.active.done( function () {
noticeContainer.toggle( shouldShowNotice() );
});
api.bind( 'pane-contents-reflowed', function() {
var duration = ( 'resolved' === api.previewer.deferred.active.state() ) ? 'fast' : 0;
updateNotice();
if ( shouldShowNotice() ) {
noticeContainer.slideDown( duration );
} else {
noticeContainer.slideUp( duration );
}
});
});
},
/**
* Allow an active widgets panel to be contextually active even when it has no active sections (widget areas).
*
* This ensures that the widgets panel appears even when there are no
* sidebars displayed on the URL currently being previewed.
*
* @since 4.4.0
*
* @return {boolean}
*/
isContextuallyActive: function() {
var panel = this;
return panel.active();
}
});
/**
* wp.customize.Widgets.SidebarSection
*
* Customizer section representing a widget area widget
*
* @since 4.1.0
*
* @class wp.customize.Widgets.SidebarSection
* @augments wp.customize.Section
*/
api.Widgets.SidebarSection = api.Section.extend(/** @lends wp.customize.Widgets.SidebarSection.prototype */{
/**
* Sync the section's active state back to the Backbone model's is_rendered attribute
*
* @since 4.1.0
*/
ready: function () {
var section = this, registeredSidebar;
api.Section.prototype.ready.call( this );
registeredSidebar = api.Widgets.registeredSidebars.get( section.params.sidebarId );
section.active.bind( function ( active ) {
registeredSidebar.set( 'is_rendered', active );
});
registeredSidebar.set( 'is_rendered', section.active() );
}
});
/**
* wp.customize.Widgets.SidebarControl
*
* Customizer control for widgets.
* Note that 'sidebar_widgets' must match the WP_Widget_Area_Customize_Control::$type
*
* @since 3.9.0
*
* @class wp.customize.Widgets.SidebarControl
* @augments wp.customize.Control
*/
api.Widgets.SidebarControl = api.Control.extend(/** @lends wp.customize.Widgets.SidebarControl.prototype */{
/**
* Set up the control
*/
ready: function() {
this.$controlSection = this.container.closest( '.control-section' );
this.$sectionContent = this.container.closest( '.accordion-section-content' );
this._setupModel();
this._setupSortable();
this._setupAddition();
this._applyCardinalOrderClassNames();
},
/**
* Update ordering of widget control forms when the setting is updated
*/
_setupModel: function() {
var self = this;
this.setting.bind( function( newWidgetIds, oldWidgetIds ) {
var widgetFormControls, removedWidgetIds, priority;
removedWidgetIds = _( oldWidgetIds ).difference( newWidgetIds );
// Filter out any persistent widget IDs for widgets which have been deactivated.
newWidgetIds = _( newWidgetIds ).filter( function( newWidgetId ) {
var parsedWidgetId = parseWidgetId( newWidgetId );
return !! api.Widgets.availableWidgets.findWhere( { id_base: parsedWidgetId.id_base } );
} );
widgetFormControls = _( newWidgetIds ).map( function( widgetId ) {
var widgetFormControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
if ( ! widgetFormControl ) {
widgetFormControl = self.addWidget( widgetId );
}
return widgetFormControl;
} );
// Sort widget controls to their new positions.
widgetFormControls.sort( function( a, b ) {
var aIndex = _.indexOf( newWidgetIds, a.params.widget_id ),
bIndex = _.indexOf( newWidgetIds, b.params.widget_id );
return aIndex - bIndex;
});
priority = 0;
_( widgetFormControls ).each( function ( control ) {
control.priority( priority );
control.section( self.section() );
priority += 1;
});
self.priority( priority ); // Make sure sidebar control remains at end.
// Re-sort widget form controls (including widgets form other sidebars newly moved here).
self._applyCardinalOrderClassNames();
// If the widget was dragged into the sidebar, make sure the sidebar_id param is updated.
_( widgetFormControls ).each( function( widgetFormControl ) {
widgetFormControl.params.sidebar_id = self.params.sidebar_id;
} );
// Cleanup after widget removal.
_( removedWidgetIds ).each( function( removedWidgetId ) {
// Using setTimeout so that when moving a widget to another sidebar,
// the other sidebars_widgets settings get a chance to update.
setTimeout( function() {
var removedControl, wasDraggedToAnotherSidebar, inactiveWidgets, removedIdBase,
widget, isPresentInAnotherSidebar = false;
// Check if the widget is in another sidebar.
api.each( function( otherSetting ) {
if ( otherSetting.id === self.setting.id || 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) || otherSetting.id === 'sidebars_widgets[wp_inactive_widgets]' ) {
return;
}
var otherSidebarWidgets = otherSetting(), i;
i = _.indexOf( otherSidebarWidgets, removedWidgetId );
if ( -1 !== i ) {
isPresentInAnotherSidebar = true;
}
} );
// If the widget is present in another sidebar, abort!
if ( isPresentInAnotherSidebar ) {
return;
}
removedControl = api.Widgets.getWidgetFormControlForWidget( removedWidgetId );
// Detect if widget control was dragged to another sidebar.
wasDraggedToAnotherSidebar = removedControl && $.contains( document, removedControl.container[0] ) && ! $.contains( self.$sectionContent[0], removedControl.container[0] );
// Delete any widget form controls for removed widgets.
if ( removedControl && ! wasDraggedToAnotherSidebar ) {
api.control.remove( removedControl.id );
removedControl.container.remove();
}
// Move widget to inactive widgets sidebar (move it to Trash) if has been previously saved.
// This prevents the inactive widgets sidebar from overflowing with throwaway widgets.
if ( api.Widgets.savedWidgetIds[removedWidgetId] ) {
inactiveWidgets = api.value( 'sidebars_widgets[wp_inactive_widgets]' )().slice();
inactiveWidgets.push( removedWidgetId );
api.value( 'sidebars_widgets[wp_inactive_widgets]' )( _( inactiveWidgets ).unique() );
}
// Make old single widget available for adding again.
removedIdBase = parseWidgetId( removedWidgetId ).id_base;
widget = api.Widgets.availableWidgets.findWhere( { id_base: removedIdBase } );
if ( widget && ! widget.get( 'is_multi' ) ) {
widget.set( 'is_disabled', false );
}
} );
} );
} );
},
/**
* Allow widgets in sidebar to be re-ordered, and for the order to be previewed
*/
_setupSortable: function() {
var self = this;
this.isReordering = false;
/**
* Update widget order setting when controls are re-ordered
*/
this.$sectionContent.sortable( {
items: '> .customize-control-widget_form',
handle: '.widget-top',
axis: 'y',
tolerance: 'pointer',
connectWith: '.accordion-section-content:has(.customize-control-sidebar_widgets)',
update: function() {
var widgetContainerIds = self.$sectionContent.sortable( 'toArray' ), widgetIds;
widgetIds = $.map( widgetContainerIds, function( widgetContainerId ) {
return $( '#' + widgetContainerId ).find( ':input[name=widget-id]' ).val();
} );
self.setting( widgetIds );
}
} );
/**
* Expand other Customizer sidebar section when dragging a control widget over it,
* allowing the control to be dropped into another section
*/
this.$controlSection.find( '.accordion-section-title' ).droppable({
accept: '.customize-control-widget_form',
over: function() {
var section = api.section( self.section.get() );
section.expand({
allowMultiple: true, // Prevent the section being dragged from to be collapsed.
completeCallback: function () {
// @todo It is not clear when refreshPositions should be called on which sections, or if it is even needed.
api.section.each( function ( otherSection ) {
if ( otherSection.container.find( '.customize-control-sidebar_widgets' ).length ) {
otherSection.container.find( '.accordion-section-content:first' ).sortable( 'refreshPositions' );
}
} );
}
});
}
});
/**
* Keyboard-accessible reordering
*/
this.container.find( '.reorder-toggle' ).on( 'click', function() {
self.toggleReordering( ! self.isReordering );
} );
},
/**
* Set up UI for adding a new widget
*/
_setupAddition: function() {
var self = this;
this.container.find( '.add-new-widget' ).on( 'click', function() {
var addNewWidgetBtn = $( this );
if ( self.$sectionContent.hasClass( 'reordering' ) ) {
return;
}
if ( ! $( 'body' ).hasClass( 'adding-widget' ) ) {
addNewWidgetBtn.attr( 'aria-expanded', 'true' );
api.Widgets.availableWidgetsPanel.open( self );
} else {
addNewWidgetBtn.attr( 'aria-expanded', 'false' );
api.Widgets.availableWidgetsPanel.close();
}
} );
},
/**
* Add classes to the widget_form controls to assist with styling
*/
_applyCardinalOrderClassNames: function() {
var widgetControls = [];
_.each( this.setting(), function ( widgetId ) {
var widgetControl = api.Widgets.getWidgetFormControlForWidget( widgetId );
if ( widgetControl ) {
widgetControls.push( widgetControl );
}
});
if ( 0 === widgetControls.length || ( 1 === api.Widgets.registeredSidebars.length && widgetControls.length <= 1 ) ) {
this.container.find( '.reorder-toggle' ).hide();
return;
} else {
this.container.find( '.reorder-toggle' ).show();
}
$( widgetControls ).each( function () {
$( this.container )
.removeClass( 'first-widget' )
.removeClass( 'last-widget' )
.find( '.move-widget-down, .move-widget-up' ).prop( 'tabIndex', 0 );
});
_.first( widgetControls ).container
.addClass( 'first-widget' )
.find( '.move-widget-up' ).prop( 'tabIndex', -1 );
_.last( widgetControls ).container
.addClass( 'last-widget' )
.find( '.move-widget-down' ).prop( 'tabIndex', -1 );
},
/***********************************************************************
* Begin public API methods
**********************************************************************/
/**
* Enable/disable the reordering UI
*
* @param {boolean} showOrHide to enable/disable reordering
*
* @todo We should have a reordering state instead and rename this to onChangeReordering
*/
toggleReordering: function( showOrHide ) {
var addNewWidgetBtn = this.$sectionContent.find( '.add-new-widget' ),
reorderBtn = this.container.find( '.reorder-toggle' ),
widgetsTitle = this.$sectionContent.find( '.widget-title' );
showOrHide = Boolean( showOrHide );
if ( showOrHide === this.$sectionContent.hasClass( 'reordering' ) ) {
return;
}
this.isReordering = showOrHide;
this.$sectionContent.toggleClass( 'reordering', showOrHide );
if ( showOrHide ) {
_( this.getWidgetFormControls() ).each( function( formControl ) {
formControl.collapse();
} );
addNewWidgetBtn.attr({ 'tabindex': '-1', 'aria-hidden': 'true' });
reorderBtn.attr( 'aria-label', l10n.reorderLabelOff );
wp.a11y.speak( l10n.reorderModeOn );
// Hide widget titles while reordering: title is already in the reorder controls.
widgetsTitle.attr( 'aria-hidden', 'true' );
} else {
addNewWidgetBtn.removeAttr( 'tabindex aria-hidden' );
reorderBtn.attr( 'aria-label', l10n.reorderLabelOn );
wp.a11y.speak( l10n.reorderModeOff );
widgetsTitle.attr( 'aria-hidden', 'false' );
}
},
/**
* Get the widget_form Customize controls associated with the current sidebar.
*
* @since 3.9.0
* @return {wp.customize.controlConstructor.widget_form[]}
*/
getWidgetFormControls: function() {
var formControls = [];
_( this.setting() ).each( function( widgetId ) {
var settingId = widgetIdToSettingId( widgetId ),
formControl = api.control( settingId );
if ( formControl ) {
formControls.push( formControl );
}
} );
return formControls;
},
/**
* @param {string} widgetId or an id_base for adding a previously non-existing widget.
* @return {Object|false} widget_form control instance, or false on error.
*/
addWidget: function( widgetId ) {
var self = this, controlHtml, $widget, controlType = 'widget_form', controlContainer, controlConstructor,
parsedWidgetId = parseWidgetId( widgetId ),
widgetNumber = parsedWidgetId.number,
widgetIdBase = parsedWidgetId.id_base,
widget = api.Widgets.availableWidgets.findWhere( {id_base: widgetIdBase} ),
settingId, isExistingWidget, widgetFormControl, sidebarWidgets, settingArgs, setting;
if ( ! widget ) {
return false;
}
if ( widgetNumber && ! widget.get( 'is_multi' ) ) {
return false;
}
// Set up new multi widget.
if ( widget.get( 'is_multi' ) && ! widgetNumber ) {
widget.set( 'multi_number', widget.get( 'multi_number' ) + 1 );
widgetNumber = widget.get( 'multi_number' );
}
controlHtml = $( '#widget-tpl-' + widget.get( 'id' ) ).html().trim();
if ( widget.get( 'is_multi' ) ) {
controlHtml = controlHtml.replace( /<[^<>]+>/g, function( m ) {
return m.replace( /__i__|%i%/g, widgetNumber );
} );
} else {
widget.set( 'is_disabled', true ); // Prevent single widget from being added again now.
}
$widget = $( controlHtml );
controlContainer = $( '' )
.addClass( 'customize-control' )
.addClass( 'customize-control-' + controlType )
.append( $widget );
// Remove icon which is visible inside the panel.
controlContainer.find( '> .widget-icon' ).remove();
if ( widget.get( 'is_multi' ) ) {
controlContainer.find( 'input[name="widget_number"]' ).val( widgetNumber );
controlContainer.find( 'input[name="multi_number"]' ).val( widgetNumber );
}
widgetId = controlContainer.find( '[name="widget-id"]' ).val();
controlContainer.hide(); // To be slid-down below.
settingId = 'widget_' + widget.get( 'id_base' );
if ( widget.get( 'is_multi' ) ) {
settingId += '[' + widgetNumber + ']';
}
controlContainer.attr( 'id', 'customize-control-' + settingId.replace( /\]/g, '' ).replace( /\[/g, '-' ) );
// Only create setting if it doesn't already exist (if we're adding a pre-existing inactive widget).
isExistingWidget = api.has( settingId );
if ( ! isExistingWidget ) {
settingArgs = {
transport: api.Widgets.data.selectiveRefreshableWidgets[ widget.get( 'id_base' ) ] ? 'postMessage' : 'refresh',
previewer: this.setting.previewer
};
setting = api.create( settingId, settingId, '', settingArgs );
setting.set( {} ); // Mark dirty, changing from '' to {}.
}
controlConstructor = api.controlConstructor[controlType];
widgetFormControl = new controlConstructor( settingId, {
settings: {
'default': settingId
},
content: controlContainer,
sidebar_id: self.params.sidebar_id,
widget_id: widgetId,
widget_id_base: widget.get( 'id_base' ),
type: controlType,
is_new: ! isExistingWidget,
width: widget.get( 'width' ),
height: widget.get( 'height' ),
is_wide: widget.get( 'is_wide' )
} );
api.control.add( widgetFormControl );
// Make sure widget is removed from the other sidebars.
api.each( function( otherSetting ) {
if ( otherSetting.id === self.setting.id ) {
return;
}
if ( 0 !== otherSetting.id.indexOf( 'sidebars_widgets[' ) ) {
return;
}
var otherSidebarWidgets = otherSetting().slice(),
i = _.indexOf( otherSidebarWidgets, widgetId );
if ( -1 !== i ) {
otherSidebarWidgets.splice( i );
otherSetting( otherSidebarWidgets );
}
} );
// Add widget to this sidebar.
sidebarWidgets = this.setting().slice();
if ( -1 === _.indexOf( sidebarWidgets, widgetId ) ) {
sidebarWidgets.push( widgetId );
this.setting( sidebarWidgets );
}
controlContainer.slideDown( function() {
if ( isExistingWidget ) {
widgetFormControl.updateWidget( {
instance: widgetFormControl.setting()
} );
}
} );
return widgetFormControl;
}
} );
// Register models for custom panel, section, and control types.
$.extend( api.panelConstructor, {
widgets: api.Widgets.WidgetsPanel
});
$.extend( api.sectionConstructor, {
sidebar: api.Widgets.SidebarSection
});
$.extend( api.controlConstructor, {
widget_form: api.Widgets.WidgetControl,
sidebar_widgets: api.Widgets.SidebarControl
});
/**
* Init Customizer for widgets.
*/
api.bind( 'ready', function() {
// Set up the widgets panel.
api.Widgets.availableWidgetsPanel = new api.Widgets.AvailableWidgetsPanelView({
collection: api.Widgets.availableWidgets
});
// Highlight widget control.
api.previewer.bind( 'highlight-widget-control', api.Widgets.highlightWidgetFormControl );
// Open and focus widget control.
api.previewer.bind( 'focus-widget-control', api.Widgets.focusWidgetFormControl );
} );
/**
* Highlight a widget control.
*
* @param {string} widgetId
*/
api.Widgets.highlightWidgetFormControl = function( widgetId ) {
var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
if ( control ) {
control.highlightSectionAndControl();
}
},
/**
* Focus a widget control.
*
* @param {string} widgetId
*/
api.Widgets.focusWidgetFormControl = function( widgetId ) {
var control = api.Widgets.getWidgetFormControlForWidget( widgetId );
if ( control ) {
control.focus();
}
},
/**
* Given a widget control, find the sidebar widgets control that contains it.
* @param {string} widgetId
* @return {Object|null}
*/
api.Widgets.getSidebarWidgetControlContainingWidget = function( widgetId ) {
var foundControl = null;
// @todo This can use widgetIdToSettingId(), then pass into wp.customize.control( x ).getSidebarWidgetsControl().
api.control.each( function( control ) {
if ( control.params.type === 'sidebar_widgets' && -1 !== _.indexOf( control.setting(), widgetId ) ) {
foundControl = control;
}
} );
return foundControl;
};
/**
* Given a widget ID for a widget appearing in the preview, get the widget form control associated with it.
*
* @param {string} widgetId
* @return {Object|null}
*/
api.Widgets.getWidgetFormControlForWidget = function( widgetId ) {
var foundControl = null;
// @todo We can just use widgetIdToSettingId() here.
api.control.each( function( control ) {
if ( control.params.type === 'widget_form' && control.params.widget_id === widgetId ) {
foundControl = control;
}
} );
return foundControl;
};
/**
* Initialize Edit Menu button in Nav Menu widget.
*/
$( document ).on( 'widget-added', function( event, widgetContainer ) {
var parsedWidgetId, widgetControl, navMenuSelect, editMenuButton;
parsedWidgetId = parseWidgetId( widgetContainer.find( '> .widget-inside > .form > .widget-id' ).val() );
if ( 'nav_menu' !== parsedWidgetId.id_base ) {
return;
}
widgetControl = api.control( 'widget_nav_menu[' + String( parsedWidgetId.number ) + ']' );
if ( ! widgetControl ) {
return;
}
navMenuSelect = widgetContainer.find( 'select[name*="nav_menu"]' );
editMenuButton = widgetContainer.find( '.edit-selected-nav-menu > button' );
if ( 0 === navMenuSelect.length || 0 === editMenuButton.length ) {
return;
}
navMenuSelect.on( 'change', function() {
if ( api.section.has( 'nav_menu[' + navMenuSelect.val() + ']' ) ) {
editMenuButton.parent().show();
} else {
editMenuButton.parent().hide();
}
});
editMenuButton.on( 'click', function() {
var section = api.section( 'nav_menu[' + navMenuSelect.val() + ']' );
if ( section ) {
focusConstructWithBreadcrumb( section, widgetControl );
}
} );
} );
/**
* Focus (expand) one construct and then focus on another construct after the first is collapsed.
*
* This overrides the back button to serve the purpose of breadcrumb navigation.
*
* @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} focusConstruct - The object to initially focus.
* @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} returnConstruct - The object to return focus.
*/
function focusConstructWithBreadcrumb( focusConstruct, returnConstruct ) {
focusConstruct.focus();
function onceCollapsed( isExpanded ) {
if ( ! isExpanded ) {
focusConstruct.expanded.unbind( onceCollapsed );
returnConstruct.focus();
}
}
focusConstruct.expanded.bind( onceCollapsed );
}
/**
* @param {string} widgetId
* @return {Object}
*/
function parseWidgetId( widgetId ) {
var matches, parsed = {
number: null,
id_base: null
};
matches = widgetId.match( /^(.+)-(\d+)$/ );
if ( matches ) {
parsed.id_base = matches[1];
parsed.number = parseInt( matches[2], 10 );
} else {
// Likely an old single widget.
parsed.id_base = widgetId;
}
return parsed;
}
/**
* @param {string} widgetId
* @return {string} settingId
*/
function widgetIdToSettingId( widgetId ) {
var parsed = parseWidgetId( widgetId ), settingId;
settingId = 'widget_' + parsed.id_base;
if ( parsed.number ) {
settingId += '[' + parsed.number + ']';
}
return settingId;
}
})( window.wp, jQuery );
home/toreyh/public_html/wp-includes/js/dist/customize-widgets.js 0000644 00000267112 15221426341 0021156 0 ustar 00 var wp;
(wp ||= {}).customizeWidgets = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// package-external:@wordpress/element
var require_element = __commonJS({
"package-external:@wordpress/element"(exports, module) {
module.exports = window.wp.element;
}
});
// package-external:@wordpress/block-library
var require_block_library = __commonJS({
"package-external:@wordpress/block-library"(exports, module) {
module.exports = window.wp.blockLibrary;
}
});
// package-external:@wordpress/widgets
var require_widgets = __commonJS({
"package-external:@wordpress/widgets"(exports, module) {
module.exports = window.wp.widgets;
}
});
// package-external:@wordpress/blocks
var require_blocks = __commonJS({
"package-external:@wordpress/blocks"(exports, module) {
module.exports = window.wp.blocks;
}
});
// package-external:@wordpress/data
var require_data = __commonJS({
"package-external:@wordpress/data"(exports, module) {
module.exports = window.wp.data;
}
});
// package-external:@wordpress/preferences
var require_preferences = __commonJS({
"package-external:@wordpress/preferences"(exports, module) {
module.exports = window.wp.preferences;
}
});
// package-external:@wordpress/components
var require_components = __commonJS({
"package-external:@wordpress/components"(exports, module) {
module.exports = window.wp.components;
}
});
// package-external:@wordpress/i18n
var require_i18n = __commonJS({
"package-external:@wordpress/i18n"(exports, module) {
module.exports = window.wp.i18n;
}
});
// package-external:@wordpress/block-editor
var require_block_editor = __commonJS({
"package-external:@wordpress/block-editor"(exports, module) {
module.exports = window.wp.blockEditor;
}
});
// package-external:@wordpress/compose
var require_compose = __commonJS({
"package-external:@wordpress/compose"(exports, module) {
module.exports = window.wp.compose;
}
});
// package-external:@wordpress/hooks
var require_hooks = __commonJS({
"package-external:@wordpress/hooks"(exports, module) {
module.exports = window.wp.hooks;
}
});
// vendor-external:react/jsx-runtime
var require_jsx_runtime = __commonJS({
"vendor-external:react/jsx-runtime"(exports, module) {
module.exports = window.ReactJSXRuntime;
}
});
// package-external:@wordpress/core-data
var require_core_data = __commonJS({
"package-external:@wordpress/core-data"(exports, module) {
module.exports = window.wp.coreData;
}
});
// package-external:@wordpress/media-utils
var require_media_utils = __commonJS({
"package-external:@wordpress/media-utils"(exports, module) {
module.exports = window.wp.mediaUtils;
}
});
// package-external:@wordpress/keycodes
var require_keycodes = __commonJS({
"package-external:@wordpress/keycodes"(exports, module) {
module.exports = window.wp.keycodes;
}
});
// package-external:@wordpress/primitives
var require_primitives = __commonJS({
"package-external:@wordpress/primitives"(exports, module) {
module.exports = window.wp.primitives;
}
});
// package-external:@wordpress/keyboard-shortcuts
var require_keyboard_shortcuts = __commonJS({
"package-external:@wordpress/keyboard-shortcuts"(exports, module) {
module.exports = window.wp.keyboardShortcuts;
}
});
// node_modules/fast-deep-equal/es6/index.js
var require_es6 = __commonJS({
"node_modules/fast-deep-equal/es6/index.js"(exports, module) {
"use strict";
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == "object" && typeof b == "object") {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0; )
if (!equal(a[i], b[i])) return false;
return true;
}
if (a instanceof Map && b instanceof Map) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if (a instanceof Set && b instanceof Set) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0; )
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0; )
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0; ) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
return a !== a && b !== b;
};
}
});
// package-external:@wordpress/is-shallow-equal
var require_is_shallow_equal = __commonJS({
"package-external:@wordpress/is-shallow-equal"(exports, module) {
module.exports = window.wp.isShallowEqual;
}
});
// package-external:@wordpress/private-apis
var require_private_apis = __commonJS({
"package-external:@wordpress/private-apis"(exports, module) {
module.exports = window.wp.privateApis;
}
});
// package-external:@wordpress/dom
var require_dom = __commonJS({
"package-external:@wordpress/dom"(exports, module) {
module.exports = window.wp.dom;
}
});
// packages/customize-widgets/build-module/index.mjs
var index_exports = {};
__export(index_exports, {
initialize: () => initialize,
store: () => store
});
var import_element17 = __toESM(require_element(), 1);
var import_block_library2 = __toESM(require_block_library(), 1);
var import_widgets5 = __toESM(require_widgets(), 1);
var import_blocks2 = __toESM(require_blocks(), 1);
var import_data17 = __toESM(require_data(), 1);
var import_preferences4 = __toESM(require_preferences(), 1);
// packages/customize-widgets/build-module/components/customize-widgets/index.mjs
var import_element16 = __toESM(require_element(), 1);
var import_components8 = __toESM(require_components(), 1);
// packages/customize-widgets/build-module/components/error-boundary/index.mjs
var import_element = __toESM(require_element(), 1);
var import_i18n = __toESM(require_i18n(), 1);
var import_components = __toESM(require_components(), 1);
var import_block_editor = __toESM(require_block_editor(), 1);
var import_compose = __toESM(require_compose(), 1);
var import_hooks = __toESM(require_hooks(), 1);
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
function CopyButton({ text, children }) {
const ref = (0, import_compose.useCopyToClipboard)(text);
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_components.Button, { size: "compact", variant: "secondary", ref, children });
}
var ErrorBoundary = class extends import_element.Component {
constructor() {
super(...arguments);
this.state = {
error: null
};
}
componentDidCatch(error) {
this.setState({ error });
(0, import_hooks.doAction)("editor.ErrorBoundary.errorLogged", error);
}
render() {
const { error } = this.state;
if (!error) {
return this.props.children;
}
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
import_block_editor.Warning,
{
className: "customize-widgets-error-boundary",
actions: [
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CopyButton, { text: error.stack, children: (0, import_i18n.__)("Copy Error") }, "copy-error")
],
children: (0, import_i18n.__)("The editor has encountered an unexpected error.")
}
);
}
};
// packages/customize-widgets/build-module/components/sidebar-block-editor/index.mjs
var import_compose3 = __toESM(require_compose(), 1);
var import_core_data = __toESM(require_core_data(), 1);
var import_data12 = __toESM(require_data(), 1);
var import_element13 = __toESM(require_element(), 1);
var import_block_editor8 = __toESM(require_block_editor(), 1);
var import_media_utils = __toESM(require_media_utils(), 1);
var import_preferences3 = __toESM(require_preferences(), 1);
var import_block_library = __toESM(require_block_library(), 1);
// packages/customize-widgets/build-module/components/block-inspector-button/index.mjs
var import_element2 = __toESM(require_element(), 1);
var import_i18n2 = __toESM(require_i18n(), 1);
var import_components2 = __toESM(require_components(), 1);
var import_data = __toESM(require_data(), 1);
var import_block_editor2 = __toESM(require_block_editor(), 1);
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
function BlockInspectorButton({ inspector, closeMenu, ...props }) {
const selectedBlockClientId = (0, import_data.useSelect)(
(select) => select(import_block_editor2.store).getSelectedBlockClientId(),
[]
);
const selectedBlock = (0, import_element2.useMemo)(
() => document.getElementById(`block-${selectedBlockClientId}`),
[selectedBlockClientId]
);
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
import_components2.MenuItem,
{
onClick: () => {
inspector.open({
returnFocusWhenClose: selectedBlock
});
closeMenu();
},
...props,
children: (0, import_i18n2.__)("Show more settings")
}
);
}
var block_inspector_button_default = BlockInspectorButton;
// node_modules/clsx/dist/clsx.mjs
function r(e) {
var t, f, n = "";
if ("string" == typeof e || "number" == typeof e) n += e;
else if ("object" == typeof e) if (Array.isArray(e)) {
var o = e.length;
for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
} else for (f in e) e[f] && (n && (n += " "), n += f);
return n;
}
function clsx() {
for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
return n;
}
var clsx_default = clsx;
// packages/customize-widgets/build-module/components/header/index.mjs
var import_components6 = __toESM(require_components(), 1);
var import_block_editor4 = __toESM(require_block_editor(), 1);
var import_element6 = __toESM(require_element(), 1);
var import_keycodes3 = __toESM(require_keycodes(), 1);
var import_i18n7 = __toESM(require_i18n(), 1);
// packages/icons/build-module/library/close-small.mjs
var import_primitives = __toESM(require_primitives(), 1);
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var close_small_default = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives.Path, { d: "M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z" }) });
// packages/icons/build-module/library/external.mjs
var import_primitives2 = __toESM(require_primitives(), 1);
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var external_default = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives2.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives2.Path, { d: "M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z" }) });
// packages/icons/build-module/library/more-vertical.mjs
var import_primitives3 = __toESM(require_primitives(), 1);
var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
var more_vertical_default = /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives3.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives3.Path, { d: "M13 19h-2v-2h2v2zm0-6h-2v-2h2v2zm0-6h-2V5h2v2z" }) });
// packages/icons/build-module/library/plus.mjs
var import_primitives4 = __toESM(require_primitives(), 1);
var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
var plus_default = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives4.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives4.Path, { d: "M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z" }) });
// packages/icons/build-module/library/redo.mjs
var import_primitives5 = __toESM(require_primitives(), 1);
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
var redo_default = /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives5.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives5.Path, { d: "M15.6 6.5l-1.1 1 2.9 3.3H8c-.9 0-1.7.3-2.3.9-1.4 1.5-1.4 4.2-1.4 5.6v.2h1.5v-.3c0-1.1 0-3.5 1-4.5.3-.3.7-.5 1.3-.5h9.2L14.5 15l1.1 1.1 4.6-4.6-4.6-5z" }) });
// packages/icons/build-module/library/undo.mjs
var import_primitives6 = __toESM(require_primitives(), 1);
var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
var undo_default = /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_primitives6.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_primitives6.Path, { d: "M18.3 11.7c-.6-.6-1.4-.9-2.3-.9H6.7l2.9-3.3-1.1-1-4.5 5L8.5 16l1-1-2.7-2.7H16c.5 0 .9.2 1.3.5 1 1 1 3.4 1 4.5v.3h1.5v-.2c0-1.5 0-4.3-1.5-5.7z" }) });
// packages/customize-widgets/build-module/components/inserter/index.mjs
var import_i18n3 = __toESM(require_i18n(), 1);
var import_block_editor3 = __toESM(require_block_editor(), 1);
var import_components3 = __toESM(require_components(), 1);
var import_compose2 = __toESM(require_compose(), 1);
var import_data4 = __toESM(require_data(), 1);
// packages/customize-widgets/build-module/store/index.mjs
var import_data3 = __toESM(require_data(), 1);
// packages/customize-widgets/build-module/store/reducer.mjs
var import_data2 = __toESM(require_data(), 1);
function blockInserterPanel(state = false, action) {
switch (action.type) {
case "SET_IS_INSERTER_OPENED":
return action.value;
}
return state;
}
var reducer_default = (0, import_data2.combineReducers)({
blockInserterPanel
});
// packages/customize-widgets/build-module/store/selectors.mjs
var selectors_exports = {};
__export(selectors_exports, {
__experimentalGetInsertionPoint: () => __experimentalGetInsertionPoint,
isInserterOpened: () => isInserterOpened
});
var EMPTY_INSERTION_POINT = {
rootClientId: void 0,
insertionIndex: void 0
};
function isInserterOpened(state) {
return !!state.blockInserterPanel;
}
function __experimentalGetInsertionPoint(state) {
if (typeof state.blockInserterPanel === "boolean") {
return EMPTY_INSERTION_POINT;
}
return state.blockInserterPanel;
}
// packages/customize-widgets/build-module/store/actions.mjs
var actions_exports = {};
__export(actions_exports, {
setIsInserterOpened: () => setIsInserterOpened
});
function setIsInserterOpened(value) {
return {
type: "SET_IS_INSERTER_OPENED",
value
};
}
// packages/customize-widgets/build-module/store/constants.mjs
var STORE_NAME = "core/customize-widgets";
// packages/customize-widgets/build-module/store/index.mjs
var storeConfig = {
reducer: reducer_default,
selectors: selectors_exports,
actions: actions_exports
};
var store = (0, import_data3.createReduxStore)(STORE_NAME, storeConfig);
(0, import_data3.register)(store);
// packages/customize-widgets/build-module/components/inserter/index.mjs
var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
function Inserter({ setIsOpened }) {
const inserterTitleId = (0, import_compose2.useInstanceId)(
Inserter,
"customize-widget-layout__inserter-panel-title"
);
const insertionPoint = (0, import_data4.useSelect)(
(select) => select(store).__experimentalGetInsertionPoint(),
[]
);
return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
"div",
{
className: "customize-widgets-layout__inserter-panel",
"aria-labelledby": inserterTitleId,
children: [
/* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("div", { className: "customize-widgets-layout__inserter-panel-header", children: [
/* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
"h2",
{
id: inserterTitleId,
className: "customize-widgets-layout__inserter-panel-header-title",
children: (0, import_i18n3.__)("Add a block")
}
),
/* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
import_components3.Button,
{
size: "small",
icon: close_small_default,
onClick: () => setIsOpened(false),
"aria-label": (0, import_i18n3.__)("Close inserter")
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime9.jsx)("div", { className: "customize-widgets-layout__inserter-panel-content", children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
import_block_editor3.__experimentalLibrary,
{
rootClientId: insertionPoint.rootClientId,
__experimentalInsertionIndex: insertionPoint.insertionIndex,
showInserterHelpPanel: true,
onSelect: () => setIsOpened(false)
}
) })
]
}
);
}
var inserter_default = Inserter;
// packages/customize-widgets/build-module/components/more-menu/index.mjs
var import_components5 = __toESM(require_components(), 1);
var import_element5 = __toESM(require_element(), 1);
var import_i18n6 = __toESM(require_i18n(), 1);
var import_keycodes2 = __toESM(require_keycodes(), 1);
var import_keyboard_shortcuts3 = __toESM(require_keyboard_shortcuts(), 1);
var import_preferences = __toESM(require_preferences(), 1);
// packages/customize-widgets/build-module/components/keyboard-shortcut-help-modal/index.mjs
var import_components4 = __toESM(require_components(), 1);
var import_i18n5 = __toESM(require_i18n(), 1);
var import_keyboard_shortcuts2 = __toESM(require_keyboard_shortcuts(), 1);
var import_data6 = __toESM(require_data(), 1);
var import_element4 = __toESM(require_element(), 1);
// packages/customize-widgets/build-module/components/keyboard-shortcut-help-modal/config.mjs
var import_i18n4 = __toESM(require_i18n(), 1);
var textFormattingShortcuts = [
{
keyCombination: { modifier: "primary", character: "b" },
description: (0, import_i18n4.__)("Make the selected text bold.")
},
{
keyCombination: { modifier: "primary", character: "i" },
description: (0, import_i18n4.__)("Make the selected text italic.")
},
{
keyCombination: { modifier: "primary", character: "k" },
description: (0, import_i18n4.__)("Convert the selected text into a link.")
},
{
keyCombination: { modifier: "primaryShift", character: "k" },
description: (0, import_i18n4.__)("Remove a link.")
},
{
keyCombination: { character: "[[" },
description: (0, import_i18n4.__)("Insert a link to a post or page.")
},
{
keyCombination: { modifier: "primary", character: "u" },
description: (0, import_i18n4.__)("Underline the selected text.")
},
{
keyCombination: { modifier: "access", character: "d" },
description: (0, import_i18n4.__)("Strikethrough the selected text.")
},
{
keyCombination: { modifier: "access", character: "x" },
description: (0, import_i18n4.__)("Make the selected text inline code.")
},
{
keyCombination: {
modifier: "access",
character: "0"
},
aliases: [
{
modifier: "access",
character: "7"
}
],
description: (0, import_i18n4.__)("Convert the current heading to a paragraph.")
},
{
keyCombination: { modifier: "access", character: "1-6" },
description: (0, import_i18n4.__)(
"Convert the current paragraph or heading to a heading of level 1 to 6."
)
},
{
keyCombination: { modifier: "primaryShift", character: "SPACE" },
description: (0, import_i18n4.__)("Add non breaking space.")
}
];
// packages/customize-widgets/build-module/components/keyboard-shortcut-help-modal/shortcut.mjs
var import_element3 = __toESM(require_element(), 1);
var import_keycodes = __toESM(require_keycodes(), 1);
var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
function KeyCombination({ keyCombination, forceAriaLabel }) {
const shortcut = keyCombination.modifier ? import_keycodes.displayShortcutList[keyCombination.modifier](
keyCombination.character
) : keyCombination.character;
const ariaLabel = keyCombination.modifier ? import_keycodes.shortcutAriaLabel[keyCombination.modifier](
keyCombination.character
) : keyCombination.character;
return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
"kbd",
{
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-key-combination",
"aria-label": forceAriaLabel || ariaLabel,
children: (Array.isArray(shortcut) ? shortcut : [shortcut]).map(
(character, index) => {
if (character === "+") {
return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_element3.Fragment, { children: character }, index);
}
return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
"kbd",
{
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-key",
children: character
},
index
);
}
)
}
);
}
function Shortcut({ description, keyCombination, aliases = [], ariaLabel }) {
return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-description", children: description }),
/* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-term", children: [
/* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
KeyCombination,
{
keyCombination,
forceAriaLabel: ariaLabel
}
),
aliases.map((alias, index) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
KeyCombination,
{
keyCombination: alias,
forceAriaLabel: ariaLabel
},
index
))
] })
] });
}
var shortcut_default = Shortcut;
// packages/customize-widgets/build-module/components/keyboard-shortcut-help-modal/dynamic-shortcut.mjs
var import_data5 = __toESM(require_data(), 1);
var import_keyboard_shortcuts = __toESM(require_keyboard_shortcuts(), 1);
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
function DynamicShortcut({ name }) {
const { keyCombination, description, aliases } = (0, import_data5.useSelect)(
(select) => {
const {
getShortcutKeyCombination,
getShortcutDescription,
getShortcutAliases
} = select(import_keyboard_shortcuts.store);
return {
keyCombination: getShortcutKeyCombination(name),
aliases: getShortcutAliases(name),
description: getShortcutDescription(name)
};
},
[name]
);
if (!keyCombination) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
shortcut_default,
{
keyCombination,
description,
aliases
}
);
}
var dynamic_shortcut_default = DynamicShortcut;
// packages/customize-widgets/build-module/components/keyboard-shortcut-help-modal/index.mjs
var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
var ShortcutList = ({ shortcuts }) => (
/*
* Disable reason: The `list` ARIA role is redundant but
* Safari+VoiceOver won't announce the list otherwise.
*/
/* eslint-disable jsx-a11y/no-redundant-roles */
/* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
"ul",
{
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut-list",
role: "list",
children: shortcuts.map((shortcut, index) => /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
"li",
{
className: "customize-widgets-keyboard-shortcut-help-modal__shortcut",
children: typeof shortcut === "string" ? /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(dynamic_shortcut_default, { name: shortcut }) : /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(shortcut_default, { ...shortcut })
},
index
))
}
)
);
var ShortcutSection = ({ title, shortcuts, className }) => /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
"section",
{
className: clsx_default(
"customize-widgets-keyboard-shortcut-help-modal__section",
className
),
children: [
!!title && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("h2", { className: "customize-widgets-keyboard-shortcut-help-modal__section-title", children: title }),
/* @__PURE__ */ (0, import_jsx_runtime12.jsx)(ShortcutList, { shortcuts })
]
}
);
var ShortcutCategorySection = ({
title,
categoryName,
additionalShortcuts = []
}) => {
const categoryShortcuts = (0, import_data6.useSelect)(
(select) => {
return select(import_keyboard_shortcuts2.store).getCategoryShortcuts(
categoryName
);
},
[categoryName]
);
return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
ShortcutSection,
{
title,
shortcuts: categoryShortcuts.concat(additionalShortcuts)
}
);
};
function KeyboardShortcutHelpModal({
isModalActive,
toggleModal
}) {
const { registerShortcut } = (0, import_data6.useDispatch)(import_keyboard_shortcuts2.store);
(0, import_element4.useEffect)(() => {
registerShortcut({
name: "core/customize-widgets/keyboard-shortcuts",
category: "main",
description: (0, import_i18n5.__)("Display these keyboard shortcuts."),
keyCombination: {
modifier: "access",
character: "h"
}
});
}, [registerShortcut]);
(0, import_keyboard_shortcuts2.useShortcut)("core/customize-widgets/keyboard-shortcuts", toggleModal);
if (!isModalActive) {
return null;
}
return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
import_components4.Modal,
{
className: "customize-widgets-keyboard-shortcut-help-modal",
title: (0, import_i18n5.__)("Keyboard shortcuts"),
onRequestClose: toggleModal,
children: [
/* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
ShortcutSection,
{
className: "customize-widgets-keyboard-shortcut-help-modal__main-shortcuts",
shortcuts: ["core/customize-widgets/keyboard-shortcuts"]
}
),
/* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
ShortcutCategorySection,
{
title: (0, import_i18n5.__)("Global shortcuts"),
categoryName: "global"
}
),
/* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
ShortcutCategorySection,
{
title: (0, import_i18n5.__)("Selection shortcuts"),
categoryName: "selection"
}
),
/* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
ShortcutCategorySection,
{
title: (0, import_i18n5.__)("Block shortcuts"),
categoryName: "block",
additionalShortcuts: [
{
keyCombination: { character: "/" },
description: (0, import_i18n5.__)(
"Change the block type after adding a new paragraph."
),
/* translators: The forward-slash character. e.g. '/'. */
ariaLabel: (0, import_i18n5.__)("Forward-slash")
}
]
}
),
/* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
ShortcutSection,
{
title: (0, import_i18n5.__)("Text formatting"),
shortcuts: textFormattingShortcuts
}
)
]
}
);
}
// packages/customize-widgets/build-module/components/more-menu/index.mjs
var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
function MoreMenu() {
const [
isKeyboardShortcutsModalActive,
setIsKeyboardShortcutsModalVisible
] = (0, import_element5.useState)(false);
const toggleKeyboardShortcutsModal = () => setIsKeyboardShortcutsModalVisible(!isKeyboardShortcutsModalActive);
(0, import_keyboard_shortcuts3.useShortcut)(
"core/customize-widgets/keyboard-shortcuts",
toggleKeyboardShortcutsModal
);
return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_jsx_runtime13.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
import_components5.ToolbarDropdownMenu,
{
icon: more_vertical_default,
label: (0, import_i18n6.__)("Options"),
popoverProps: {
placement: "bottom-end",
className: "more-menu-dropdown__content"
},
toggleProps: {
tooltipPosition: "bottom",
size: "compact"
},
children: () => /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_jsx_runtime13.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_components5.MenuGroup, { label: (0, import_i18n6._x)("View", "noun"), children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
import_preferences.PreferenceToggleMenuItem,
{
scope: "core/customize-widgets",
name: "fixedToolbar",
label: (0, import_i18n6.__)("Top toolbar"),
info: (0, import_i18n6.__)(
"Access all block and document tools in a single place"
),
messageActivated: (0, import_i18n6.__)(
"Top toolbar activated"
),
messageDeactivated: (0, import_i18n6.__)(
"Top toolbar deactivated"
)
}
) }),
/* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_components5.MenuGroup, { label: (0, import_i18n6.__)("Tools"), children: [
/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
import_components5.MenuItem,
{
onClick: () => {
setIsKeyboardShortcutsModalVisible(true);
},
shortcut: import_keycodes2.displayShortcut.access("h"),
children: (0, import_i18n6.__)("Keyboard shortcuts")
}
),
/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
import_preferences.PreferenceToggleMenuItem,
{
scope: "core/customize-widgets",
name: "welcomeGuide",
label: (0, import_i18n6.__)("Welcome Guide")
}
),
/* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
import_components5.MenuItem,
{
role: "menuitem",
icon: external_default,
href: (0, import_i18n6.__)(
"https://wordpress.org/documentation/article/block-based-widgets-editor/"
),
target: "_blank",
rel: "noopener noreferrer",
children: [
(0, import_i18n6.__)("Help"),
/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_components5.VisuallyHidden, {
as: "span",
/* translators: accessibility text */
children: (0, import_i18n6.__)("(opens in a new tab)")
})
]
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_components5.MenuGroup, { label: (0, import_i18n6.__)("Preferences"), children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
import_preferences.PreferenceToggleMenuItem,
{
scope: "core/customize-widgets",
name: "keepCaretInsideBlock",
label: (0, import_i18n6.__)(
"Contain text cursor inside block"
),
info: (0, import_i18n6.__)(
"Aids screen readers by stopping text caret from leaving blocks."
),
messageActivated: (0, import_i18n6.__)(
"Contain text cursor inside block activated"
),
messageDeactivated: (0, import_i18n6.__)(
"Contain text cursor inside block deactivated"
)
}
) })
] })
}
),
/* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
KeyboardShortcutHelpModal,
{
isModalActive: isKeyboardShortcutsModalActive,
toggleModal: toggleKeyboardShortcutsModal
}
)
] });
}
// packages/customize-widgets/build-module/components/header/index.mjs
var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
function Header({
sidebar,
inserter,
isInserterOpened: isInserterOpened2,
setIsInserterOpened: setIsInserterOpened2,
isFixedToolbarActive
}) {
const [[hasUndo, hasRedo], setUndoRedo] = (0, import_element6.useState)([
sidebar.hasUndo(),
sidebar.hasRedo()
]);
const shortcut = (0, import_keycodes3.isAppleOS)() ? import_keycodes3.displayShortcut.primaryShift("z") : import_keycodes3.displayShortcut.primary("y");
(0, import_element6.useEffect)(() => {
return sidebar.subscribeHistory(() => {
setUndoRedo([sidebar.hasUndo(), sidebar.hasRedo()]);
});
}, [sidebar]);
return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
"div",
{
className: clsx_default("customize-widgets-header", {
"is-fixed-toolbar-active": isFixedToolbarActive
}),
children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
import_block_editor4.NavigableToolbar,
{
className: "customize-widgets-header-toolbar",
"aria-label": (0, import_i18n7.__)("Document tools"),
children: [
/* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
import_components6.ToolbarButton,
{
icon: !(0, import_i18n7.isRTL)() ? undo_default : redo_default,
label: (0, import_i18n7.__)("Undo"),
shortcut: import_keycodes3.displayShortcut.primary("z"),
disabled: !hasUndo,
onClick: sidebar.undo,
className: "customize-widgets-editor-history-button undo-button"
}
),
/* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
import_components6.ToolbarButton,
{
icon: !(0, import_i18n7.isRTL)() ? redo_default : undo_default,
label: (0, import_i18n7.__)("Redo"),
shortcut,
disabled: !hasRedo,
onClick: sidebar.redo,
className: "customize-widgets-editor-history-button redo-button"
}
),
/* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
import_components6.ToolbarButton,
{
className: "customize-widgets-header-toolbar__inserter-toggle",
isPressed: isInserterOpened2,
variant: "primary",
icon: plus_default,
label: (0, import_i18n7._x)(
"Add block",
"Generic label for block inserter button"
),
onClick: () => {
setIsInserterOpened2((isOpen) => !isOpen);
}
}
),
/* @__PURE__ */ (0, import_jsx_runtime14.jsx)(MoreMenu, {})
]
}
)
}
),
(0, import_element6.createPortal)(
/* @__PURE__ */ (0, import_jsx_runtime14.jsx)(inserter_default, { setIsOpened: setIsInserterOpened2 }),
inserter.contentContainer[0]
)
] });
}
var header_default = Header;
// packages/customize-widgets/build-module/components/inserter/use-inserter.mjs
var import_element7 = __toESM(require_element(), 1);
var import_data7 = __toESM(require_data(), 1);
function useInserter(inserter) {
const isInserterOpened2 = (0, import_data7.useSelect)(
(select) => select(store).isInserterOpened(),
[]
);
const { setIsInserterOpened: setIsInserterOpened2 } = (0, import_data7.useDispatch)(store);
(0, import_element7.useEffect)(() => {
if (isInserterOpened2) {
inserter.open();
} else {
inserter.close();
}
}, [inserter, isInserterOpened2]);
return [
isInserterOpened2,
(0, import_element7.useCallback)(
(updater) => {
let isOpen = updater;
if (typeof updater === "function") {
isOpen = updater(
(0, import_data7.select)(store).isInserterOpened()
);
}
setIsInserterOpened2(isOpen);
},
[setIsInserterOpened2]
)
];
}
// packages/customize-widgets/build-module/components/sidebar-block-editor/sidebar-editor-provider.mjs
var import_block_editor6 = __toESM(require_block_editor(), 1);
// packages/customize-widgets/build-module/components/sidebar-block-editor/use-sidebar-block-editor.mjs
var import_es6 = __toESM(require_es6(), 1);
var import_element8 = __toESM(require_element(), 1);
var import_is_shallow_equal = __toESM(require_is_shallow_equal(), 1);
var import_widgets2 = __toESM(require_widgets(), 1);
// packages/customize-widgets/build-module/utils.mjs
var import_blocks = __toESM(require_blocks(), 1);
var import_widgets = __toESM(require_widgets(), 1);
function settingIdToWidgetId(settingId) {
const matches = settingId.match(/^widget_(.+)(?:\[(\d+)\])$/);
if (matches) {
const idBase = matches[1];
const number = parseInt(matches[2], 10);
return `${idBase}-${number}`;
}
return settingId;
}
function blockToWidget(block, existingWidget = null) {
let widget;
const isValidLegacyWidgetBlock = block.name === "core/legacy-widget" && (block.attributes.id || block.attributes.instance);
if (isValidLegacyWidgetBlock) {
if (block.attributes.id) {
widget = {
id: block.attributes.id
};
} else {
const { encoded, hash, raw, ...rest } = block.attributes.instance;
widget = {
idBase: block.attributes.idBase,
instance: {
...existingWidget?.instance,
// Required only for the customizer.
is_widget_customizer_js_value: true,
encoded_serialized_instance: encoded,
instance_hash_key: hash,
raw_instance: raw,
...rest
}
};
}
} else {
const instance = {
content: (0, import_blocks.serialize)(block)
};
widget = {
idBase: "block",
widgetClass: "WP_Widget_Block",
instance: {
raw_instance: instance
}
};
}
const { form, rendered, ...restExistingWidget } = existingWidget || {};
return {
...restExistingWidget,
...widget
};
}
function widgetToBlock({ id, idBase, number, instance }) {
let block;
const {
encoded_serialized_instance: encoded,
instance_hash_key: hash,
raw_instance: raw,
...rest
} = instance;
if (idBase === "block") {
const parsedBlocks = (0, import_blocks.parse)(raw.content ?? "", {
__unstableSkipAutop: true
});
block = parsedBlocks.length ? parsedBlocks[0] : (0, import_blocks.createBlock)("core/paragraph", {});
} else if (number) {
block = (0, import_blocks.createBlock)("core/legacy-widget", {
idBase,
instance: {
encoded,
hash,
raw,
...rest
}
});
} else {
block = (0, import_blocks.createBlock)("core/legacy-widget", {
id
});
}
return (0, import_widgets.addWidgetIdToBlock)(block, id);
}
// packages/customize-widgets/build-module/components/sidebar-block-editor/use-sidebar-block-editor.mjs
function widgetsToBlocks(widgets) {
return widgets.map((widget) => widgetToBlock(widget));
}
function useSidebarBlockEditor(sidebar) {
const [blocks, setBlocks] = (0, import_element8.useState)(
() => widgetsToBlocks(sidebar.getWidgets())
);
(0, import_element8.useEffect)(() => {
return sidebar.subscribe((prevWidgets, nextWidgets) => {
setBlocks((prevBlocks) => {
const prevWidgetsMap = new Map(
prevWidgets.map((widget) => [widget.id, widget])
);
const prevBlocksMap = new Map(
prevBlocks.map((block) => [
(0, import_widgets2.getWidgetIdFromBlock)(block),
block
])
);
const nextBlocks = nextWidgets.map((nextWidget) => {
const prevWidget = prevWidgetsMap.get(nextWidget.id);
if (prevWidget && prevWidget === nextWidget) {
return prevBlocksMap.get(nextWidget.id);
}
return widgetToBlock(nextWidget);
});
if ((0, import_is_shallow_equal.isShallowEqual)(prevBlocks, nextBlocks)) {
return prevBlocks;
}
return nextBlocks;
});
});
}, [sidebar]);
const onChangeBlocks = (0, import_element8.useCallback)(
(nextBlocks) => {
setBlocks((prevBlocks) => {
if ((0, import_is_shallow_equal.isShallowEqual)(prevBlocks, nextBlocks)) {
return prevBlocks;
}
const prevBlocksMap = new Map(
prevBlocks.map((block) => [
(0, import_widgets2.getWidgetIdFromBlock)(block),
block
])
);
const nextWidgets = nextBlocks.map((nextBlock) => {
const widgetId = (0, import_widgets2.getWidgetIdFromBlock)(nextBlock);
if (widgetId && prevBlocksMap.has(widgetId)) {
const prevBlock = prevBlocksMap.get(widgetId);
const prevWidget = sidebar.getWidget(widgetId);
if ((0, import_es6.default)(nextBlock, prevBlock) && prevWidget) {
return prevWidget;
}
return blockToWidget(nextBlock, prevWidget);
}
return blockToWidget(nextBlock);
});
if ((0, import_is_shallow_equal.isShallowEqual)(sidebar.getWidgets(), nextWidgets)) {
return prevBlocks;
}
const addedWidgetIds = sidebar.setWidgets(nextWidgets);
return nextBlocks.reduce(
(updatedNextBlocks, nextBlock, index) => {
const addedWidgetId = addedWidgetIds[index];
if (addedWidgetId !== null) {
if (updatedNextBlocks === nextBlocks) {
updatedNextBlocks = nextBlocks.slice();
}
updatedNextBlocks[index] = (0, import_widgets2.addWidgetIdToBlock)(
nextBlock,
addedWidgetId
);
}
return updatedNextBlocks;
},
nextBlocks
);
});
},
[sidebar]
);
return [blocks, onChangeBlocks, onChangeBlocks];
}
// packages/customize-widgets/build-module/components/focus-control/use-blocks-focus-control.mjs
var import_element10 = __toESM(require_element(), 1);
var import_data8 = __toESM(require_data(), 1);
var import_block_editor5 = __toESM(require_block_editor(), 1);
var import_widgets3 = __toESM(require_widgets(), 1);
// packages/customize-widgets/build-module/components/focus-control/index.mjs
var import_element9 = __toESM(require_element(), 1);
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
var FocusControlContext = (0, import_element9.createContext)();
FocusControlContext.displayName = "FocusControlContext";
function FocusControl({ api, sidebarControls, children }) {
const [focusedWidgetIdRef, setFocusedWidgetIdRef] = (0, import_element9.useState)({
current: null
});
const focusWidget = (0, import_element9.useCallback)(
(widgetId) => {
for (const sidebarControl of sidebarControls) {
const widgets = sidebarControl.setting.get();
if (widgets.includes(widgetId)) {
sidebarControl.sectionInstance.expand({
// Schedule it after the complete callback so that
// it won't be overridden by the "Back" button focus.
completeCallback() {
setFocusedWidgetIdRef({ current: widgetId });
}
});
break;
}
}
},
[sidebarControls]
);
(0, import_element9.useEffect)(() => {
function handleFocus(settingId) {
const widgetId = settingIdToWidgetId(settingId);
focusWidget(widgetId);
}
let previewBound = false;
function handleReady() {
api.previewer.preview.bind(
"focus-control-for-setting",
handleFocus
);
previewBound = true;
}
api.previewer.bind("ready", handleReady);
return () => {
api.previewer.unbind("ready", handleReady);
if (previewBound) {
api.previewer.preview.unbind(
"focus-control-for-setting",
handleFocus
);
}
};
}, [api, focusWidget]);
const context = (0, import_element9.useMemo)(
() => [focusedWidgetIdRef, focusWidget],
[focusedWidgetIdRef, focusWidget]
);
return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(FocusControlContext.Provider, { value: context, children });
}
var useFocusControl = () => (0, import_element9.useContext)(FocusControlContext);
// packages/customize-widgets/build-module/components/focus-control/use-blocks-focus-control.mjs
function useBlocksFocusControl(blocks) {
const { selectBlock } = (0, import_data8.useDispatch)(import_block_editor5.store);
const [focusedWidgetIdRef] = useFocusControl();
const blocksRef = (0, import_element10.useRef)(blocks);
(0, import_element10.useEffect)(() => {
blocksRef.current = blocks;
}, [blocks]);
(0, import_element10.useEffect)(() => {
if (focusedWidgetIdRef.current) {
const focusedBlock = blocksRef.current.find(
(block) => (0, import_widgets3.getWidgetIdFromBlock)(block) === focusedWidgetIdRef.current
);
if (focusedBlock) {
selectBlock(focusedBlock.clientId);
const blockNode = document.querySelector(
`[data-block="${focusedBlock.clientId}"]`
);
blockNode?.focus();
}
}
}, [focusedWidgetIdRef, selectBlock]);
}
// packages/customize-widgets/build-module/lock-unlock.mjs
var import_private_apis = __toESM(require_private_apis(), 1);
var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
"I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
"@wordpress/customize-widgets"
);
// packages/customize-widgets/build-module/components/sidebar-block-editor/sidebar-editor-provider.mjs
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var { ExperimentalBlockEditorProvider } = unlock(import_block_editor6.privateApis);
function SidebarEditorProvider({
sidebar,
settings,
children
}) {
const [blocks, onInput, onChange] = useSidebarBlockEditor(sidebar);
useBlocksFocusControl(blocks);
return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
ExperimentalBlockEditorProvider,
{
value: blocks,
onInput,
onChange,
settings,
useSubRegistry: false,
children
}
);
}
// packages/customize-widgets/build-module/components/welcome-guide/index.mjs
var import_i18n8 = __toESM(require_i18n(), 1);
var import_components7 = __toESM(require_components(), 1);
var import_data9 = __toESM(require_data(), 1);
var import_preferences2 = __toESM(require_preferences(), 1);
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
function WelcomeGuide({ sidebar }) {
const { toggle } = (0, import_data9.useDispatch)(import_preferences2.store);
const isEntirelyBlockWidgets = sidebar.getWidgets().every((widget) => widget.id.startsWith("block-"));
return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("div", { className: "customize-widgets-welcome-guide", children: [
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)("div", { className: "customize-widgets-welcome-guide__image__wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("picture", { children: [
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
"source",
{
srcSet: "https://s.w.org/images/block-editor/welcome-editor.svg",
media: "(prefers-reduced-motion: reduce)"
}
),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
"img",
{
className: "customize-widgets-welcome-guide__image",
src: "https://s.w.org/images/block-editor/welcome-editor.gif",
width: "312",
height: "240",
alt: ""
}
)
] }) }),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)("h1", { className: "customize-widgets-welcome-guide__heading", children: (0, import_i18n8.__)("Welcome to block Widgets") }),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)("p", { className: "customize-widgets-welcome-guide__text", children: isEntirelyBlockWidgets ? (0, import_i18n8.__)(
"Your theme provides different \u201Cblock\u201D areas for you to add and edit content.\xA0Try adding a search bar, social icons, or other types of blocks here and see how they\u2019ll look on your site."
) : (0, import_i18n8.__)(
"You can now add any block to your site\u2019s widget areas. Don\u2019t worry, all of your favorite widgets still work flawlessly."
) }),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
import_components7.Button,
{
size: "compact",
variant: "primary",
onClick: () => toggle("core/customize-widgets", "welcomeGuide"),
children: (0, import_i18n8.__)("Got it")
}
),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)("hr", { className: "customize-widgets-welcome-guide__separator" }),
!isEntirelyBlockWidgets && /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("p", { className: "customize-widgets-welcome-guide__more-info", children: [
(0, import_i18n8.__)("Want to stick with the old widgets?"),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)("br", {}),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
import_components7.ExternalLink,
{
href: (0, import_i18n8.__)(
"https://wordpress.org/plugins/classic-widgets/"
),
children: (0, import_i18n8.__)("Get the Classic Widgets plugin.")
}
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("p", { className: "customize-widgets-welcome-guide__more-info", children: [
(0, import_i18n8.__)("New to the block editor?"),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)("br", {}),
/* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
import_components7.ExternalLink,
{
href: (0, import_i18n8.__)(
"https://wordpress.org/documentation/article/wordpress-block-editor/"
),
children: (0, import_i18n8.__)("Here's a detailed guide.")
}
)
] })
] });
}
// packages/customize-widgets/build-module/components/keyboard-shortcuts/index.mjs
var import_element11 = __toESM(require_element(), 1);
var import_keyboard_shortcuts4 = __toESM(require_keyboard_shortcuts(), 1);
var import_keycodes4 = __toESM(require_keycodes(), 1);
var import_data10 = __toESM(require_data(), 1);
var import_i18n9 = __toESM(require_i18n(), 1);
function KeyboardShortcuts({ undo, redo, save }) {
(0, import_keyboard_shortcuts4.useShortcut)("core/customize-widgets/undo", (event) => {
undo();
event.preventDefault();
});
(0, import_keyboard_shortcuts4.useShortcut)("core/customize-widgets/redo", (event) => {
redo();
event.preventDefault();
});
(0, import_keyboard_shortcuts4.useShortcut)("core/customize-widgets/save", (event) => {
event.preventDefault();
save();
});
return null;
}
function KeyboardShortcutsRegister() {
const { registerShortcut, unregisterShortcut } = (0, import_data10.useDispatch)(
import_keyboard_shortcuts4.store
);
(0, import_element11.useEffect)(() => {
registerShortcut({
name: "core/customize-widgets/undo",
category: "global",
description: (0, import_i18n9.__)("Undo your last changes."),
keyCombination: {
modifier: "primary",
character: "z"
}
});
registerShortcut({
name: "core/customize-widgets/redo",
category: "global",
description: (0, import_i18n9.__)("Redo your last undo."),
keyCombination: {
modifier: "primaryShift",
character: "z"
},
// Disable on Apple OS because it conflicts with the browser's
// history shortcut. It's a fine alias for both Windows and Linux.
// Since there's no conflict for Ctrl+Shift+Z on both Windows and
// Linux, we keep it as the default for consistency.
aliases: (0, import_keycodes4.isAppleOS)() ? [] : [
{
modifier: "primary",
character: "y"
}
]
});
registerShortcut({
name: "core/customize-widgets/save",
category: "global",
description: (0, import_i18n9.__)("Save your changes."),
keyCombination: {
modifier: "primary",
character: "s"
}
});
return () => {
unregisterShortcut("core/customize-widgets/undo");
unregisterShortcut("core/customize-widgets/redo");
unregisterShortcut("core/customize-widgets/save");
};
}, [registerShortcut]);
return null;
}
KeyboardShortcuts.Register = KeyboardShortcutsRegister;
var keyboard_shortcuts_default = KeyboardShortcuts;
// packages/customize-widgets/build-module/components/block-appender/index.mjs
var import_element12 = __toESM(require_element(), 1);
var import_block_editor7 = __toESM(require_block_editor(), 1);
var import_data11 = __toESM(require_data(), 1);
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
function BlockAppender(props) {
const ref = (0, import_element12.useRef)();
const isBlocksListEmpty = (0, import_data11.useSelect)(
(select) => select(import_block_editor7.store).getBlockCount() === 0
);
(0, import_element12.useEffect)(() => {
if (isBlocksListEmpty && ref.current) {
const { ownerDocument } = ref.current;
if (!ownerDocument.activeElement || ownerDocument.activeElement === ownerDocument.body) {
ref.current.focus();
}
}
}, [isBlocksListEmpty]);
return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(import_block_editor7.ButtonBlockAppender, { ...props, ref });
}
// packages/customize-widgets/build-module/components/sidebar-block-editor/index.mjs
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
var { ExperimentalBlockCanvas: BlockCanvas } = unlock(
import_block_editor8.privateApis
);
var { BlockKeyboardShortcuts } = unlock(import_block_library.privateApis);
function SidebarBlockEditor({
blockEditorSettings,
sidebar,
inserter,
inspector
}) {
const [isInserterOpened2, setIsInserterOpened2] = useInserter(inserter);
const isMediumViewport = (0, import_compose3.useViewportMatch)("small");
const {
hasUploadPermissions,
isFixedToolbarActive,
keepCaretInsideBlock,
isWelcomeGuideActive
} = (0, import_data12.useSelect)((select) => {
const { get } = select(import_preferences3.store);
return {
hasUploadPermissions: select(import_core_data.store).canUser("create", {
kind: "postType",
name: "attachment"
}) ?? true,
isFixedToolbarActive: !!get(
"core/customize-widgets",
"fixedToolbar"
),
keepCaretInsideBlock: !!get(
"core/customize-widgets",
"keepCaretInsideBlock"
),
isWelcomeGuideActive: !!get(
"core/customize-widgets",
"welcomeGuide"
)
};
}, []);
const settings = (0, import_element13.useMemo)(() => {
let mediaUploadBlockEditor;
if (hasUploadPermissions) {
mediaUploadBlockEditor = ({ onError, ...argumentsObject }) => {
(0, import_media_utils.uploadMedia)({
wpAllowedMimeTypes: blockEditorSettings.allowedMimeTypes,
onError: ({ message }) => onError(message),
...argumentsObject
});
};
}
return {
...blockEditorSettings,
__experimentalSetIsInserterOpened: setIsInserterOpened2,
mediaUpload: mediaUploadBlockEditor,
hasFixedToolbar: isFixedToolbarActive || !isMediumViewport,
keepCaretInsideBlock,
editorTool: "edit",
__unstableHasCustomAppender: true
};
}, [
hasUploadPermissions,
blockEditorSettings,
isFixedToolbarActive,
isMediumViewport,
keepCaretInsideBlock,
setIsInserterOpened2
]);
if (isWelcomeGuideActive) {
return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(WelcomeGuide, { sidebar });
}
return /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(import_jsx_runtime19.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime19.jsx)(keyboard_shortcuts_default.Register, {}),
/* @__PURE__ */ (0, import_jsx_runtime19.jsx)(BlockKeyboardShortcuts, {}),
/* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(SidebarEditorProvider, { sidebar, settings, children: [
/* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
keyboard_shortcuts_default,
{
undo: sidebar.undo,
redo: sidebar.redo,
save: sidebar.save
}
),
/* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
header_default,
{
sidebar,
inserter,
isInserterOpened: isInserterOpened2,
setIsInserterOpened: setIsInserterOpened2,
isFixedToolbarActive: isFixedToolbarActive || !isMediumViewport
}
),
(isFixedToolbarActive || !isMediumViewport) && /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_block_editor8.BlockToolbar, { hideDragHandle: true }),
/* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
BlockCanvas,
{
shouldIframe: false,
styles: settings.defaultEditorStyles,
height: "100%",
children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_block_editor8.BlockList, { renderAppender: BlockAppender })
}
),
(0, import_element13.createPortal)(
// This is a temporary hack to prevent button component inside
// from submitting form when type="button" is not specified.
/* @__PURE__ */ (0, import_jsx_runtime19.jsx)("form", { onSubmit: (event) => event.preventDefault(), children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_block_editor8.BlockInspector, {}) }),
inspector.contentContainer[0]
)
] }),
/* @__PURE__ */ (0, import_jsx_runtime19.jsx)(import_block_editor8.__unstableBlockSettingsMenuFirstItem, { children: ({ onClose }) => /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
block_inspector_button_default,
{
inspector,
closeMenu: onClose
}
) })
] });
}
// packages/customize-widgets/build-module/components/sidebar-controls/index.mjs
var import_element14 = __toESM(require_element(), 1);
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var SidebarControlsContext = (0, import_element14.createContext)();
SidebarControlsContext.displayName = "SidebarControlsContext";
function SidebarControls({
sidebarControls,
activeSidebarControl,
children
}) {
const context = (0, import_element14.useMemo)(
() => ({
sidebarControls,
activeSidebarControl
}),
[sidebarControls, activeSidebarControl]
);
return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(SidebarControlsContext.Provider, { value: context, children });
}
function useSidebarControls() {
const { sidebarControls } = (0, import_element14.useContext)(SidebarControlsContext);
return sidebarControls;
}
function useActiveSidebarControl() {
const { activeSidebarControl } = (0, import_element14.useContext)(SidebarControlsContext);
return activeSidebarControl;
}
// packages/customize-widgets/build-module/components/customize-widgets/use-clear-selected-block.mjs
var import_element15 = __toESM(require_element(), 1);
var import_data13 = __toESM(require_data(), 1);
var import_block_editor9 = __toESM(require_block_editor(), 1);
function useClearSelectedBlock(sidebarControl, popoverRef) {
const { hasSelectedBlock, hasMultiSelection } = (0, import_data13.useSelect)(import_block_editor9.store);
const { clearSelectedBlock } = (0, import_data13.useDispatch)(import_block_editor9.store);
(0, import_element15.useEffect)(() => {
if (popoverRef.current && sidebarControl) {
let handleClearSelectedBlock = function(element) {
if (
// 1. Make sure there are blocks being selected.
(hasSelectedBlock() || hasMultiSelection()) && // 2. The element should exist in the DOM (not deleted).
element && ownerDocument.contains(element) && // 3. It should also not exist in the container, the popover, nor the dialog.
!container.contains(element) && !popoverRef.current.contains(element) && !element.closest('[role="dialog"]') && // 4. The inspector should not be opened.
!inspector.expanded()
) {
clearSelectedBlock();
}
}, handleMouseDown = function(event) {
handleClearSelectedBlock(event.target);
}, handleBlur = function() {
handleClearSelectedBlock(ownerDocument.activeElement);
};
const inspector = sidebarControl.inspector;
const container = sidebarControl.container[0];
const ownerDocument = container.ownerDocument;
const ownerWindow = ownerDocument.defaultView;
ownerDocument.addEventListener("mousedown", handleMouseDown);
ownerWindow.addEventListener("blur", handleBlur);
return () => {
ownerDocument.removeEventListener(
"mousedown",
handleMouseDown
);
ownerWindow.removeEventListener("blur", handleBlur);
};
}
}, [
popoverRef,
sidebarControl,
hasSelectedBlock,
hasMultiSelection,
clearSelectedBlock
]);
}
// packages/customize-widgets/build-module/components/customize-widgets/index.mjs
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
function CustomizeWidgets({
api,
sidebarControls,
blockEditorSettings
}) {
const [activeSidebarControl, setActiveSidebarControl] = (0, import_element16.useState)(null);
const parentContainer = document.getElementById(
"customize-theme-controls"
);
const popoverRef = (0, import_element16.useRef)();
useClearSelectedBlock(activeSidebarControl, popoverRef);
(0, import_element16.useEffect)(() => {
const unsubscribers = sidebarControls.map(
(sidebarControl) => sidebarControl.subscribe((expanded) => {
if (expanded) {
setActiveSidebarControl(sidebarControl);
}
})
);
return () => {
unsubscribers.forEach((unsubscriber) => unsubscriber());
};
}, [sidebarControls]);
const activeSidebar = activeSidebarControl && (0, import_element16.createPortal)(
/* @__PURE__ */ (0, import_jsx_runtime21.jsx)(ErrorBoundary, { children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
SidebarBlockEditor,
{
blockEditorSettings,
sidebar: activeSidebarControl.sidebarAdapter,
inserter: activeSidebarControl.inserter,
inspector: activeSidebarControl.inspector
},
activeSidebarControl.id
) }),
activeSidebarControl.container[0]
);
const popover = parentContainer && (0, import_element16.createPortal)(
/* @__PURE__ */ (0, import_jsx_runtime21.jsx)("div", { className: "customize-widgets-popover", ref: popoverRef, children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_components8.Popover.Slot, {}) }),
parentContainer
);
return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(import_components8.SlotFillProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
SidebarControls,
{
sidebarControls,
activeSidebarControl,
children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(FocusControl, { api, sidebarControls, children: [
activeSidebar,
popover
] })
}
) });
}
// packages/customize-widgets/build-module/controls/sidebar-section.mjs
var import_i18n10 = __toESM(require_i18n(), 1);
// packages/customize-widgets/build-module/controls/inspector-section.mjs
function getInspectorSection() {
const {
wp: { customize }
} = window;
return class InspectorSection extends customize.Section {
constructor(id, options) {
super(id, options);
this.parentSection = options.parentSection;
this.returnFocusWhenClose = null;
this._isOpen = false;
}
get isOpen() {
return this._isOpen;
}
set isOpen(value) {
this._isOpen = value;
this.triggerActiveCallbacks();
}
ready() {
this.contentContainer[0].classList.add(
"customize-widgets-layout__inspector"
);
}
isContextuallyActive() {
return this.isOpen;
}
onChangeExpanded(expanded, args) {
super.onChangeExpanded(expanded, args);
if (this.parentSection && !args.unchanged) {
if (expanded) {
this.parentSection.collapse({
manualTransition: true
});
} else {
this.parentSection.expand({
manualTransition: true,
completeCallback: () => {
if (this.returnFocusWhenClose && !this.contentContainer[0].contains(
this.returnFocusWhenClose
)) {
this.returnFocusWhenClose.focus();
}
}
});
}
}
}
open({ returnFocusWhenClose } = {}) {
this.isOpen = true;
this.returnFocusWhenClose = returnFocusWhenClose;
this.expand({
allowMultiple: true
});
}
close() {
this.collapse({
allowMultiple: true
});
}
collapse(options) {
this.isOpen = false;
super.collapse(options);
}
triggerActiveCallbacks() {
this.active.callbacks.fireWith(this.active, [false, true]);
}
};
}
// packages/customize-widgets/build-module/controls/sidebar-section.mjs
var getInspectorSectionId = (sidebarId) => `widgets-inspector-${sidebarId}`;
function getSidebarSection() {
const {
wp: { customize }
} = window;
const reduceMotionMediaQuery = window.matchMedia(
"(prefers-reduced-motion: reduce)"
);
let isReducedMotion = reduceMotionMediaQuery.matches;
reduceMotionMediaQuery.addEventListener("change", (event) => {
isReducedMotion = event.matches;
});
return class SidebarSection extends customize.Section {
ready() {
const InspectorSection = getInspectorSection();
this.inspector = new InspectorSection(
getInspectorSectionId(this.id),
{
title: (0, import_i18n10.__)("Block Settings"),
parentSection: this,
customizeAction: [
(0, import_i18n10.__)("Customizing"),
(0, import_i18n10.__)("Widgets"),
this.params.title
].join(" \u25B8 ")
}
);
customize.section.add(this.inspector);
this.contentContainer[0].classList.add(
"customize-widgets__sidebar-section"
);
}
hasSubSectionOpened() {
return this.inspector.expanded();
}
onChangeExpanded(expanded, _args) {
const controls = this.controls();
const args = {
..._args,
completeCallback() {
controls.forEach((control) => {
control.onChangeSectionExpanded?.(expanded, args);
});
_args.completeCallback?.();
}
};
if (args.manualTransition) {
if (expanded) {
this.contentContainer.addClass(["busy", "open"]);
this.contentContainer.removeClass("is-sub-section-open");
this.contentContainer.closest(".wp-full-overlay").addClass("section-open");
} else {
this.contentContainer.addClass([
"busy",
"is-sub-section-open"
]);
this.contentContainer.closest(".wp-full-overlay").addClass("section-open");
this.contentContainer.removeClass("open");
}
const handleTransitionEnd = () => {
this.contentContainer.removeClass("busy");
args.completeCallback();
};
if (isReducedMotion) {
handleTransitionEnd();
} else {
this.contentContainer.one(
"transitionend",
handleTransitionEnd
);
}
} else {
super.onChangeExpanded(expanded, args);
}
}
};
}
// packages/customize-widgets/build-module/controls/sidebar-control.mjs
var import_data15 = __toESM(require_data(), 1);
// packages/customize-widgets/build-module/components/sidebar-block-editor/sidebar-adapter.mjs
var { wp } = window;
function parseWidgetId(widgetId) {
const matches = widgetId.match(/^(.+)-(\d+)$/);
if (matches) {
return {
idBase: matches[1],
number: parseInt(matches[2], 10)
};
}
return { idBase: widgetId };
}
function widgetIdToSettingId(widgetId) {
const { idBase, number } = parseWidgetId(widgetId);
if (number) {
return `widget_${idBase}[${number}]`;
}
return `widget_${idBase}`;
}
function debounce(leading, callback, timeout) {
let isLeading = false;
let timerID;
function debounced(...args) {
const result = (isLeading ? callback : leading).apply(this, args);
isLeading = true;
clearTimeout(timerID);
timerID = setTimeout(() => {
isLeading = false;
}, timeout);
return result;
}
debounced.cancel = () => {
isLeading = false;
clearTimeout(timerID);
};
return debounced;
}
var SidebarAdapter = class {
constructor(setting, api) {
this.setting = setting;
this.api = api;
this.locked = false;
this.widgetsCache = /* @__PURE__ */ new WeakMap();
this.subscribers = /* @__PURE__ */ new Set();
this.history = [
this._getWidgetIds().map(
(widgetId) => this.getWidget(widgetId)
)
];
this.historyIndex = 0;
this.historySubscribers = /* @__PURE__ */ new Set();
this._debounceSetHistory = debounce(
this._pushHistory,
this._replaceHistory,
1e3
);
this.setting.bind(this._handleSettingChange.bind(this));
this.api.bind("change", this._handleAllSettingsChange.bind(this));
this.undo = this.undo.bind(this);
this.redo = this.redo.bind(this);
this.save = this.save.bind(this);
}
subscribe(callback) {
this.subscribers.add(callback);
return () => {
this.subscribers.delete(callback);
};
}
getWidgets() {
return this.history[this.historyIndex];
}
_emit(...args) {
for (const callback of this.subscribers) {
callback(...args);
}
}
_getWidgetIds() {
return this.setting.get();
}
_pushHistory() {
this.history = [
...this.history.slice(0, this.historyIndex + 1),
this._getWidgetIds().map(
(widgetId) => this.getWidget(widgetId)
)
];
this.historyIndex += 1;
this.historySubscribers.forEach((listener) => listener());
}
_replaceHistory() {
this.history[this.historyIndex] = this._getWidgetIds().map(
(widgetId) => this.getWidget(widgetId)
);
}
_handleSettingChange() {
if (this.locked) {
return;
}
const prevWidgets = this.getWidgets();
this._pushHistory();
this._emit(prevWidgets, this.getWidgets());
}
_handleAllSettingsChange(setting) {
if (this.locked) {
return;
}
if (!setting.id.startsWith("widget_")) {
return;
}
const widgetId = settingIdToWidgetId(setting.id);
if (!this.setting.get().includes(widgetId)) {
return;
}
const prevWidgets = this.getWidgets();
this._pushHistory();
this._emit(prevWidgets, this.getWidgets());
}
_createWidget(widget) {
const widgetModel = wp.customize.Widgets.availableWidgets.findWhere({
id_base: widget.idBase
});
let number = widget.number;
if (widgetModel.get("is_multi") && !number) {
widgetModel.set(
"multi_number",
widgetModel.get("multi_number") + 1
);
number = widgetModel.get("multi_number");
}
const settingId = number ? `widget_${widget.idBase}[${number}]` : `widget_${widget.idBase}`;
const settingArgs = {
transport: wp.customize.Widgets.data.selectiveRefreshableWidgets[widgetModel.get("id_base")] ? "postMessage" : "refresh",
previewer: this.setting.previewer
};
const setting = this.api.create(
settingId,
settingId,
"",
settingArgs
);
setting.set(widget.instance);
const widgetId = settingIdToWidgetId(settingId);
return widgetId;
}
_removeWidget(widget) {
const settingId = widgetIdToSettingId(widget.id);
const setting = this.api(settingId);
if (setting) {
const instance = setting.get();
this.widgetsCache.delete(instance);
}
this.api.remove(settingId);
}
_updateWidget(widget) {
const prevWidget = this.getWidget(widget.id);
if (prevWidget === widget) {
return widget.id;
}
if (prevWidget.idBase && widget.idBase && prevWidget.idBase === widget.idBase) {
const settingId = widgetIdToSettingId(widget.id);
this.api(settingId).set(widget.instance);
return widget.id;
}
this._removeWidget(widget);
return this._createWidget(widget);
}
getWidget(widgetId) {
if (!widgetId) {
return null;
}
const { idBase, number } = parseWidgetId(widgetId);
const settingId = widgetIdToSettingId(widgetId);
const setting = this.api(settingId);
if (!setting) {
return null;
}
const instance = setting.get();
if (this.widgetsCache.has(instance)) {
return this.widgetsCache.get(instance);
}
const widget = {
id: widgetId,
idBase,
number,
instance
};
this.widgetsCache.set(instance, widget);
return widget;
}
_updateWidgets(nextWidgets) {
this.locked = true;
const addedWidgetIds = [];
const nextWidgetIds = nextWidgets.map((nextWidget) => {
if (nextWidget.id && this.getWidget(nextWidget.id)) {
addedWidgetIds.push(null);
return this._updateWidget(nextWidget);
}
const widgetId = this._createWidget(nextWidget);
addedWidgetIds.push(widgetId);
return widgetId;
});
const deletedWidgets = this.getWidgets().filter(
(widget) => !nextWidgetIds.includes(widget.id)
);
deletedWidgets.forEach((widget) => this._removeWidget(widget));
this.setting.set(nextWidgetIds);
this.locked = false;
return addedWidgetIds;
}
setWidgets(nextWidgets) {
const addedWidgetIds = this._updateWidgets(nextWidgets);
this._debounceSetHistory();
return addedWidgetIds;
}
/**
* Undo/Redo related features
*/
hasUndo() {
return this.historyIndex > 0;
}
hasRedo() {
return this.historyIndex < this.history.length - 1;
}
_seek(historyIndex) {
const currentWidgets = this.getWidgets();
this.historyIndex = historyIndex;
const widgets = this.history[this.historyIndex];
this._updateWidgets(widgets);
this._emit(currentWidgets, this.getWidgets());
this.historySubscribers.forEach((listener) => listener());
this._debounceSetHistory.cancel();
}
undo() {
if (!this.hasUndo()) {
return;
}
this._seek(this.historyIndex - 1);
}
redo() {
if (!this.hasRedo()) {
return;
}
this._seek(this.historyIndex + 1);
}
subscribeHistory(listener) {
this.historySubscribers.add(listener);
return () => {
this.historySubscribers.delete(listener);
};
}
save() {
this.api.previewer.save();
}
};
// packages/customize-widgets/build-module/controls/inserter-outer-section.mjs
var import_keycodes5 = __toESM(require_keycodes(), 1);
var import_dom = __toESM(require_dom(), 1);
var import_data14 = __toESM(require_data(), 1);
function getInserterOuterSection() {
const {
wp: { customize }
} = window;
const OuterSection = customize.OuterSection;
customize.OuterSection = class extends OuterSection {
onChangeExpanded(expanded, args) {
if (expanded) {
customize.section.each((section) => {
if (section.params.type === "outer" && section.id !== this.id) {
if (section.expanded()) {
section.collapse();
}
}
});
}
return super.onChangeExpanded(expanded, args);
}
};
customize.sectionConstructor.outer = customize.OuterSection;
return class InserterOuterSection extends customize.OuterSection {
constructor(...args) {
super(...args);
this.params.type = "outer";
this.activeElementBeforeExpanded = null;
const ownerWindow = this.contentContainer[0].ownerDocument.defaultView;
ownerWindow.addEventListener(
"keydown",
(event) => {
if (this.expanded() && (event.keyCode === import_keycodes5.ESCAPE || event.code === "Escape") && !event.defaultPrevented) {
event.preventDefault();
event.stopPropagation();
(0, import_data14.dispatch)(store).setIsInserterOpened(
false
);
}
},
// Use capture mode to make this run before other event listeners.
true
);
this.contentContainer.addClass("widgets-inserter");
this.isFromInternalAction = false;
this.expanded.bind(() => {
if (!this.isFromInternalAction) {
(0, import_data14.dispatch)(store).setIsInserterOpened(
this.expanded()
);
}
this.isFromInternalAction = false;
});
}
open() {
if (!this.expanded()) {
const contentContainer = this.contentContainer[0];
this.activeElementBeforeExpanded = contentContainer.ownerDocument.activeElement;
this.isFromInternalAction = true;
this.expand({
completeCallback() {
const searchBox = import_dom.focus.tabbable.find(contentContainer)[1];
if (searchBox) {
searchBox.focus();
}
}
});
}
}
close() {
if (this.expanded()) {
const contentContainer = this.contentContainer[0];
const activeElement = contentContainer.ownerDocument.activeElement;
this.isFromInternalAction = true;
this.collapse({
completeCallback() {
if (contentContainer.contains(activeElement)) {
if (this.activeElementBeforeExpanded) {
this.activeElementBeforeExpanded.focus();
}
}
}
});
}
}
};
}
// packages/customize-widgets/build-module/controls/sidebar-control.mjs
var getInserterId = (controlId) => `widgets-inserter-${controlId}`;
function getSidebarControl() {
const {
wp: { customize }
} = window;
return class SidebarControl extends customize.Control {
constructor(...args) {
super(...args);
this.subscribers = /* @__PURE__ */ new Set();
}
ready() {
const InserterOuterSection = getInserterOuterSection();
this.inserter = new InserterOuterSection(
getInserterId(this.id),
{}
);
customize.section.add(this.inserter);
this.sectionInstance = customize.section(this.section());
this.inspector = this.sectionInstance.inspector;
this.sidebarAdapter = new SidebarAdapter(this.setting, customize);
}
subscribe(callback) {
this.subscribers.add(callback);
return () => {
this.subscribers.delete(callback);
};
}
onChangeSectionExpanded(expanded, args) {
if (!args.unchanged) {
if (!expanded) {
(0, import_data15.dispatch)(store).setIsInserterOpened(
false
);
}
this.subscribers.forEach(
(subscriber) => subscriber(expanded, args)
);
}
}
};
}
// packages/customize-widgets/build-module/filters/move-to-sidebar.mjs
var import_block_editor10 = __toESM(require_block_editor(), 1);
var import_compose4 = __toESM(require_compose(), 1);
var import_data16 = __toESM(require_data(), 1);
var import_hooks2 = __toESM(require_hooks(), 1);
var import_widgets4 = __toESM(require_widgets(), 1);
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
var withMoveToSidebarToolbarItem = (0, import_compose4.createHigherOrderComponent)(
(BlockEdit) => (props) => {
let widgetId = (0, import_widgets4.getWidgetIdFromBlock)(props);
const sidebarControls = useSidebarControls();
const activeSidebarControl = useActiveSidebarControl();
const hasMultipleSidebars = sidebarControls?.length > 1;
const blockName = props.name;
const clientId = props.clientId;
const canInsertBlockInSidebar = (0, import_data16.useSelect)(
(select) => {
return select(import_block_editor10.store).canInsertBlockType(
blockName,
""
);
},
[blockName]
);
const block = (0, import_data16.useSelect)(
(select) => select(import_block_editor10.store).getBlock(clientId),
[clientId]
);
const { removeBlock } = (0, import_data16.useDispatch)(import_block_editor10.store);
const [, focusWidget] = useFocusControl();
function moveToSidebar(sidebarControlId) {
const newSidebarControl = sidebarControls.find(
(sidebarControl) => sidebarControl.id === sidebarControlId
);
if (widgetId) {
const oldSetting = activeSidebarControl.setting;
const newSetting = newSidebarControl.setting;
oldSetting(oldSetting().filter((id) => id !== widgetId));
newSetting([...newSetting(), widgetId]);
} else {
const sidebarAdapter = newSidebarControl.sidebarAdapter;
removeBlock(clientId);
const addedWidgetIds = sidebarAdapter.setWidgets([
...sidebarAdapter.getWidgets(),
blockToWidget(block)
]);
widgetId = addedWidgetIds.reverse().find((id) => !!id);
}
focusWidget(widgetId);
}
return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(import_jsx_runtime22.Fragment, { children: [
/* @__PURE__ */ (0, import_jsx_runtime22.jsx)(BlockEdit, { ...props }, "edit"),
hasMultipleSidebars && canInsertBlockInSidebar && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(import_block_editor10.BlockControls, { children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
import_widgets4.MoveToWidgetArea,
{
widgetAreas: sidebarControls.map(
(sidebarControl) => ({
id: sidebarControl.id,
name: sidebarControl.params.label,
description: sidebarControl.params.description
})
),
currentWidgetAreaId: activeSidebarControl?.id,
onSelect: moveToSidebar
}
) })
] });
},
"withMoveToSidebarToolbarItem"
);
(0, import_hooks2.addFilter)(
"editor.BlockEdit",
"core/customize-widgets/block-edit",
withMoveToSidebarToolbarItem
);
// packages/customize-widgets/build-module/filters/replace-media-upload.mjs
var import_hooks3 = __toESM(require_hooks(), 1);
var import_media_utils2 = __toESM(require_media_utils(), 1);
var replaceMediaUpload = () => import_media_utils2.MediaUpload;
(0, import_hooks3.addFilter)(
"editor.MediaUpload",
"core/edit-widgets/replace-media-upload",
replaceMediaUpload
);
// packages/customize-widgets/build-module/filters/wide-widget-display.mjs
var import_compose5 = __toESM(require_compose(), 1);
var import_hooks4 = __toESM(require_hooks(), 1);
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
var { wp: wp2 } = window;
var withWideWidgetDisplay = (0, import_compose5.createHigherOrderComponent)(
(BlockEdit) => (props) => {
const { idBase } = props.attributes;
const isWide = wp2.customize.Widgets.data.availableWidgets.find(
(widget) => widget.id_base === idBase
)?.is_wide ?? false;
return /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(BlockEdit, { ...props, isWide }, "edit");
},
"withWideWidgetDisplay"
);
(0, import_hooks4.addFilter)(
"editor.BlockEdit",
"core/customize-widgets/wide-widget-display",
withWideWidgetDisplay
);
// packages/customize-widgets/build-module/index.mjs
var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
var { wp: wp3 } = window;
var DISABLED_BLOCKS = [
"core/more",
"core/block",
"core/freeform",
"core/template-part"
];
function initialize(editorName, blockEditorSettings) {
(0, import_data17.dispatch)(import_preferences4.store).setDefaults("core/customize-widgets", {
fixedToolbar: false,
welcomeGuide: true
});
(0, import_data17.dispatch)(import_blocks2.store).reapplyBlockTypeFilters();
const coreBlocks = (0, import_block_library2.__experimentalGetCoreBlocks)().filter((block) => {
return !(DISABLED_BLOCKS.includes(block.name) || block.name.startsWith("core/post") || block.name.startsWith("core/query") || block.name.startsWith("core/site") || block.name.startsWith("core/navigation") || block.name.startsWith("core/term"));
});
(0, import_block_library2.registerCoreBlocks)(coreBlocks);
(0, import_widgets5.registerLegacyWidgetBlock)();
if (false) {
(0, import_block_library2.__experimentalRegisterExperimentalCoreBlocks)({
enableFSEBlocks: ENABLE_EXPERIMENTAL_FSE_BLOCKS
});
}
(0, import_widgets5.registerLegacyWidgetVariations)(blockEditorSettings);
(0, import_widgets5.registerWidgetGroupBlock)();
(0, import_blocks2.setFreeformContentHandlerName)("core/html");
const SidebarControl = getSidebarControl(blockEditorSettings);
wp3.customize.sectionConstructor.sidebar = getSidebarSection();
wp3.customize.controlConstructor.sidebar_block_editor = SidebarControl;
const container = document.createElement("div");
document.body.appendChild(container);
wp3.customize.bind("ready", () => {
const sidebarControls = [];
wp3.customize.control.each((control) => {
if (control instanceof SidebarControl) {
sidebarControls.push(control);
}
});
(0, import_element17.createRoot)(container).render(
/* @__PURE__ */ (0, import_jsx_runtime24.jsx)(import_element17.StrictMode, { children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
CustomizeWidgets,
{
api: wp3.customize,
sidebarControls,
blockEditorSettings
}
) })
);
});
}
return __toCommonJS(index_exports);
})();