@wordpress/block-library
Version:
Block library for the WordPress editor.
51 lines (50 loc) • 1.93 kB
JavaScript
// 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
} = 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));
if (!newListItem.innerBlocks?.length) {
newListItem.innerBlocks = [createBlock("core/list")];
}
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