/** * WPForms Builder Dropdown List module. * * @since 1.8.4 */ /* Usage: dropdownList = WPForms.Admin.Builder.DropdownList.init( { class: 'insert-field-dropdown', // Additional CSS class. title: 'Dropdown Title', // Dropdown title. list: [ // Items list. { value: '1', text: 'Item 1' }, { value: '2', text: 'Item 2' }, { value: '3', text: 'Item 3' }, ], container: $( '.holder-container' ), // Holder container. Optional. scrollableContainer: $( '.scrollable-container' ), // Scrollable container. Optional. button: $( '.button' ), // Button. buttonDistance: 21, // Distance from dropdown to the button. itemFormat( item ) { // Item element renderer. Optional. return `${ item.text }`; }, onSelect( event, value, text, $item, instance ) { // On select event handler. console.log( 'Item selected:', text ); instance.close(); $button.removeClass( 'active' ); }, } ); */ var WPForms = window.WPForms || {}; // eslint-disable-line no-var WPForms.Admin = WPForms.Admin || {}; WPForms.Admin.Builder = WPForms.Admin.Builder || {}; WPForms.Admin.Builder.DropdownList = WPForms.Admin.Builder.DropdownList || ( function( document, window, $ ) { /** * DropdownList object constructor. * * @since 1.8.4 * * @type {Object} */ function DropdownList( options ) { // eslint-disable-line max-lines-per-function const self = this; /** * Default options. * * @since 1.8.4 * * @type {Object} */ const defaultOptions = { class: '', title: '', list: [], container: null, scrollableContainer: null, button: null, buttonDistance: 10, onSelect: null, itemFormat( item ) { return item.text; }, }; /** * Options. * * @since 1.8.4 * * @type {jQuery} */ self.options = $.extend( defaultOptions, options ); /** * Main dropdown container. * * @since 1.8.4 * * @type {jQuery} */ self.$el = null; /** * Form builder container. * * @since 1.8.4 * * @type {jQuery} */ self.$builder = $( '#wpforms-builder' ); /** * Close the dropdown. * * @since 1.8.4 */ self.close = function() { self.$el.addClass( 'closed' ); }; /** * Open the dropdown. * * @since 1.8.4 */ self.open = function() { self.$el.removeClass( 'closed' ); self.setPosition(); // Close dropdown on click outside. self.$builder.on( 'click.DropdowmList', function( e ) { const $target = $( e.target ); if ( $target.closest( self.$el ).length || $target.hasClass( 'button-insert-field' ) ) { return; } self.$builder.off( 'click.DropdowmList' ); const $button = $( self.options.button ); if ( $button.hasClass( 'active' ) ) { $button.trigger( 'click' ); } } ); }; /** * Generate the dropdown HTML. * * @since 1.8.4 * * @return {string} HTML. */ self.generateHtml = function() { const list = self.options.list; if ( ! list || list.length === 0 ) { return ''; } const itemFormat = typeof self.options.itemFormat === 'function' ? self.options.itemFormat : defaultOptions.itemFormat; // Generate HTML. const items = []; for ( const i in list ) { items.push( `