/**
* External dependencies
*/
import { withDispatch, withSelect } from '@wordpress/data';
import { compose } from '@wordpress/compose';
import { Modal, Notice } from '@wordpress/components';
import { useState } from '@wordpress/element';
/**
* Internal dependencies
*/
import { STORE_KEY } from './data/constants';
import { default as OptionEditor } from './OptionEditor';
import './data';
function Options( {
options,
getOptions,
deleteOptionById,
isLoading,
invalidateResolution,
getOptionForEditing,
editingOption,
saveOption,
notice,
setNotice,
} ) {
const [ isEditModalOpen, setEditModalOpen ] = useState( false );
const deleteOption = ( optionId ) => {
// eslint-disable-next-line no-alert
if ( confirm( 'Are you sure you want to delete?' ) ) {
deleteOptionById( optionId );
}
};
const openEditModal = ( optionName ) => {
invalidateResolution( STORE_KEY, 'getOptionForEditing', [
optionName,
] );
getOptionForEditing( optionName );
setEditModalOpen( true );
};
const handleSaveOption = ( optionName, newValue ) => {
saveOption( optionName, newValue );
setEditModalOpen( false );
};
const renderLoading = () => {
return (
Loading...
|
);
};
const renderTableData = () => {
if ( options.length === 0 ) {
return (
No Options Found
|
);
}
return options.map( ( option ) => {
// eslint-disable-next-line camelcase
const { option_id, option_name, autoload } = option;
// eslint-disable-next-line camelcase
const optionId = option_id;
// eslint-disable-next-line camelcase
const optionName = option_name;
return (
{ optionId } |
{ optionName } |
{ autoload }
|
|
|
);
} );
};
const searchOption = ( event ) => {
event.preventDefault();
const keyword = event.target.search.value;
// Invalidate resolution of the same selector + arg
// so that entering the same keyword always works
invalidateResolution( STORE_KEY, 'getOptions', [ keyword ] );
getOptions( keyword );
};
return (
<>
{ isEditModalOpen && (
{
setEditModalOpen( false );
} }
>
) }
{ notice.message.length > 0 && (
{
setNotice( { message: '' } );
} }
>
{ notice.message }
) }
I.D
|
Name
|
Autoload
|
Delete
|
Edit
|
{ isLoading ? renderLoading() : renderTableData() }
>
);
}
export default compose(
withSelect( ( select ) => {
const {
getOptions,
getOptionForEditing,
getNotice,
isLoading,
} = select( STORE_KEY );
const options = getOptions();
const editingOption = getOptionForEditing();
const notice = getNotice();
return {
options,
getOptions,
isLoading: isLoading(),
editingOption,
getOptionForEditing,
notice,
};
} ),
withDispatch( ( dispatch ) => {
const { deleteOptionById, saveOption, setNotice } = dispatch(
STORE_KEY
);
const { invalidateResolution } = dispatch( 'core/data' );
return {
deleteOptionById,
invalidateResolution,
saveOption,
setNotice,
};
} )
)( Options );