import classnames from 'classnames/dedupe';
import {
InspectorControls,
useBlockProps,
useInnerBlocksProps,
} from '@wordpress/block-editor';
import { createBlock } from '@wordpress/blocks';
import {
__experimentalNumberControl as ExperimentalNumberControl,
NumberControl as StableNumberControl,
PanelBody,
ToggleControl,
} from '@wordpress/components';
import { useDispatch, useSelect } from '@wordpress/data';
import { applyFilters } from '@wordpress/hooks';
import { __ } from '@wordpress/i18n';
import EditorStyles from '../../components/editor-styles';
import IconPicker from '../../components/icon-picker';
import RangeControl from '../../components/range-control';
import ToggleGroup from '../../components/toggle-group';
const NumberControl = StableNumberControl || ExperimentalNumberControl;
const slideBlockName = 'ghostkit/carousel-slide';
/**
* Block Edit Class.
*
* @param props
*/
export default function BlockEdit(props) {
const { attributes, setAttributes, clientId } = props;
let { className = '' } = props;
const {
effect,
speed,
autoplay,
autoplayHoverPause,
slidesPerView,
centeredSlides,
loop,
freeScroll,
fadeEdges,
fadeEdgesSize,
showArrows,
arrowPrevIcon,
arrowNextIcon,
showBullets,
dynamicBullets,
gap,
} = attributes;
const { getBlocks, slidesCount, block } = useSelect((select) => {
const blockEditorData = select('core/block-editor');
return {
getBlocks: blockEditorData.getBlocks,
slidesCount: blockEditorData.getBlockCount(clientId),
block: blockEditorData.getBlock(clientId),
};
});
const { removeBlock, replaceInnerBlocks } =
useDispatch('core/block-editor');
/**
* Updates the slides count
*
* @param {number} newSlidesCount New slides count.
*/
const updateSlidesCount = (newSlidesCount) => {
// Remove slider block.
if (newSlidesCount < 1) {
removeBlock(block.clientId);
// Add new slides.
} else if (newSlidesCount > slidesCount) {
const newCount = newSlidesCount - slidesCount;
const newInnerBlocks = [...getBlocks(block.clientId)];
for (let i = 1; i <= newCount; i += 1) {
newInnerBlocks.push(createBlock(slideBlockName, { size: 3 }));
}
replaceInnerBlocks(block.clientId, newInnerBlocks, false);
// Remove slides.
} else if (newSlidesCount < slidesCount) {
const newInnerBlocks = [...getBlocks(block.clientId)];
newInnerBlocks.splice(newSlidesCount, slidesCount - newSlidesCount);
replaceInnerBlocks(block.clientId, newInnerBlocks, false);
}
};
className = classnames(
className,
'ghostkit-carousel',
fadeEdges && 'ghostkit-carousel-fade-edges'
);
className = applyFilters('ghostkit.editor.className', className, props);
const blockProps = useBlockProps({ className });
const innerBlockProps = useInnerBlocksProps(
{ className: 'ghostkit-carousel-items' },
{
template: [[slideBlockName], [slideBlockName], [slideBlockName]],
allowedBlocks: [slideBlockName],
templateLock: false,
orientation: 'horizontal',
}
);
return (
<>