UNPKG

@wordpress/block-library

Version:
95 lines (94 loc) 2.8 kB
// packages/block-library/src/list-item/hooks/use-outdent-list-item.js import { useCallback } from "@wordpress/element"; import { useSelect, useDispatch, useRegistry } from "@wordpress/data"; import { store as blockEditorStore } from "@wordpress/block-editor"; import { cloneBlock } from "@wordpress/blocks"; function useOutdentListItem() { const registry = useRegistry(); const { moveBlocksToPosition, removeBlock, insertBlock, updateBlockListSettings } = useDispatch(blockEditorStore); const { getBlockRootClientId, getBlockName, getBlockOrder, getBlockIndex, getSelectedBlockClientIds, getBlock, getBlockListSettings } = useSelect(blockEditorStore); function getParentListItemId(id) { const listId = getBlockRootClientId(id); const parentListItemId = getBlockRootClientId(listId); if (!parentListItemId) { return; } if (getBlockName(parentListItemId) !== "core/list-item") { return; } return parentListItemId; } return useCallback((clientIds = getSelectedBlockClientIds()) => { if (!Array.isArray(clientIds)) { clientIds = [clientIds]; } if (!clientIds.length) { return; } const firstClientId = clientIds[0]; if (getBlockName(firstClientId) !== "core/list-item") { return; } const parentListItemId = getParentListItemId(firstClientId); if (!parentListItemId) { return; } const parentListId = getBlockRootClientId(firstClientId); const lastClientId = clientIds[clientIds.length - 1]; const order = getBlockOrder(parentListId); const followingListItems = order.slice( getBlockIndex(lastClientId) + 1 ); registry.batch(() => { if (followingListItems.length) { let nestedListId = getBlockOrder(firstClientId)[0]; if (!nestedListId) { const nestedListBlock = cloneBlock( getBlock(parentListId), {}, [] ); nestedListId = nestedListBlock.clientId; insertBlock(nestedListBlock, 0, firstClientId, false); updateBlockListSettings( nestedListId, getBlockListSettings(parentListId) ); } moveBlocksToPosition( followingListItems, parentListId, nestedListId ); } moveBlocksToPosition( clientIds, parentListId, getBlockRootClientId(parentListItemId), getBlockIndex(parentListItemId) + 1 ); if (!getBlockOrder(parentListId).length) { const shouldSelectParent = false; removeBlock(parentListId, shouldSelectParent); } }); return true; }, []); } export { useOutdentListItem as default }; //# sourceMappingURL=use-outdent-list-item.mjs.map