import { useBuilder, useEditor } from '@tempi/core-editor'; import { ROOT } from '@tempi/core-renderer'; import { BLOCK_TYPES } from '@tempi/core-elements'; export const useSelectBlock = () => { const { insertIndex } = useBuilder(); const { query, selectedNodes } = useEditor((state) => ({ selectedNodes: state.events.selected, })); const { node } = query; const getInsertDestination = () => { const id = selectedNodes?.keys()?.next().value; if ( id && (id === BLOCK_TYPES.FOOTER || node(id).ancestors().includes(BLOCK_TYPES.FOOTER)) ) return BLOCK_TYPES.FOOTER; return ROOT; }; const findIndexInsert = () => { const insertDes = getInsertDestination(); const { nodes } = node(insertDes).get().data; const totalNodes = nodes.length; // Mặc định insertIndex = undefined -> thêm vô vị trí cuối let index = insertIndex || totalNodes; let minInsertIndex = 0; // Xác định vị trí thêm block khi có header, footer if (totalNodes && insertDes === ROOT) { const headerIndex = nodes.findIndex( (id) => node(id).get().data.props.blockType === BLOCK_TYPES.HEADER, ); if (headerIndex !== -1) { minInsertIndex = headerIndex + 1; // min insert index phải sau header } const footerIndex = nodes.findIndex( (id) => node(id).get().data.props.blockType === BLOCK_TYPES.FOOTER, ); // Nếu thêm block vào sau footer -> luôn thêm vào trước footer if (footerIndex !== -1 && index > footerIndex) { index = footerIndex; } } return Math.max(index, minInsertIndex); }; return { findIndexInsert, getInsertDestination, }; };