@wordpress/block-library
Version:
Block library for the WordPress editor.
48 lines (47 loc) • 1.73 kB
JavaScript
// packages/block-library/src/list-item/hooks/use-space.js
import { useRefEffect } from "@wordpress/compose";
import { SPACE, TAB } from "@wordpress/keycodes";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { useSelect } from "@wordpress/data";
import useIndentListItem from "./use-indent-list-item";
import useOutdentListItem from "./use-outdent-list-item";
function useSpace(clientId) {
const { getSelectionStart, getSelectionEnd, getBlockIndex } = useSelect(blockEditorStore);
const indentListItem = useIndentListItem(clientId);
const outdentListItem = useOutdentListItem();
return useRefEffect(
(element) => {
function onKeyDown(event) {
const { keyCode, shiftKey, altKey, metaKey, ctrlKey } = event;
if (event.defaultPrevented || keyCode !== SPACE && keyCode !== TAB || // Only override when no modifiers are pressed.
altKey || metaKey || ctrlKey) {
return;
}
const selectionStart = getSelectionStart();
const selectionEnd = getSelectionEnd();
if (selectionStart.offset === 0 && selectionEnd.offset === 0) {
if (shiftKey) {
if (keyCode === TAB) {
if (outdentListItem()) {
event.preventDefault();
}
}
} else if (getBlockIndex(clientId) !== 0) {
if (indentListItem()) {
event.preventDefault();
}
}
}
}
element.addEventListener("keydown", onKeyDown);
return () => {
element.removeEventListener("keydown", onKeyDown);
};
},
[clientId, indentListItem]
);
}
export {
useSpace as default
};
//# sourceMappingURL=use-space.js.map