UNPKG

@wordpress/block-library

Version:
59 lines (58 loc) 2.18 kB
// packages/block-library/src/list-item/hooks/use-indent-list-item.js import { useCallback } from "@wordpress/element"; import { useSelect, useDispatch } from "@wordpress/data"; import { store as blockEditorStore } from "@wordpress/block-editor"; import { createBlock, cloneBlock } from "@wordpress/blocks"; function useIndentListItem(clientId) { const { replaceBlocks, selectionChange, multiSelect } = useDispatch(blockEditorStore); const { getBlock, getPreviousBlockClientId, getSelectionStart, getSelectionEnd, hasMultiSelection, getMultiSelectedBlockClientIds, getBlockRootClientId, getBlockAttributes } = useSelect(blockEditorStore); return useCallback(() => { const _hasMultiSelection = hasMultiSelection(); const clientIds = _hasMultiSelection ? getMultiSelectedBlockClientIds() : [clientId]; const clonedBlocks = clientIds.map( (_clientId) => cloneBlock(getBlock(_clientId)) ); const previousSiblingId = getPreviousBlockClientId(clientId); const newListItem = cloneBlock(getBlock(previousSiblingId)); const parentListId = getBlockRootClientId(clientId); const parentListAttributes = getBlockAttributes(parentListId); if (!newListItem.innerBlocks?.length) { newListItem.innerBlocks = [ createBlock("core/list", { ordered: parentListAttributes.ordered }) ]; } newListItem.innerBlocks[newListItem.innerBlocks.length - 1].innerBlocks.push(...clonedBlocks); const selectionStart = getSelectionStart(); const selectionEnd = getSelectionEnd(); replaceBlocks([previousSiblingId, ...clientIds], [newListItem]); if (!_hasMultiSelection) { selectionChange( clonedBlocks[0].clientId, selectionEnd.attributeKey, selectionEnd.clientId === selectionStart.clientId ? selectionStart.offset : selectionEnd.offset, selectionEnd.offset ); } else { multiSelect( clonedBlocks[0].clientId, clonedBlocks[clonedBlocks.length - 1].clientId ); } return true; }, [clientId]); } export { useIndentListItem as default }; //# sourceMappingURL=use-indent-list-item.mjs.map