import { $createCodeNode } from '@lexical/code'; import { INSERT_CHECK_LIST_COMMAND, INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND, REMOVE_LIST_COMMAND, } from '@lexical/list'; import { $createHeadingNode, $createQuoteNode } from '@lexical/rich-text'; import { $wrapNodes } from '@lexical/selection'; import { $createParagraphNode, $getSelection, $isRangeSelection, } from 'lexical'; import React, { useContext, useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import EditorContext from '../../../context/EditorContext'; import DropDown from '../../../ui/DropDown'; const BlockFormatDropdown = () => { const { initialEditor } = useContext(EditorContext); const { t } = useTranslation('toolbar'); const [blockType, setBlockType] = useState('paragraph'); const formatParagraph = () => { if (blockType !== 'paragraph') { initialEditor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { $wrapNodes(selection, () => $createParagraphNode()); } }); } }; const formatHeading = (headingSize) => { if (blockType !== headingSize) { initialEditor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { $wrapNodes(selection, () => $createHeadingNode(headingSize)); } }); } }; const formatBulletList = () => { if (blockType !== 'bullet') { initialEditor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined); } else { initialEditor.dispatchCommand(REMOVE_LIST_COMMAND, undefined); } }; const formatCheckList = () => { if (blockType !== 'check') { initialEditor.dispatchCommand(INSERT_CHECK_LIST_COMMAND, undefined); } else { initialEditor.dispatchCommand(REMOVE_LIST_COMMAND, undefined); } }; const formatNumberedList = () => { if (blockType !== 'number') { initialEditor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined); } else { initialEditor.dispatchCommand(REMOVE_LIST_COMMAND, undefined); } }; const formatQuote = () => { if (blockType !== 'quote') { initialEditor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { $wrapNodes(selection, () => $createQuoteNode()); } }); } }; const formatCode = () => { if (blockType !== 'code') { initialEditor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { if (selection.isCollapsed()) { $wrapNodes(selection, () => $createCodeNode()); } else { const textContent = selection.getTextContent(); const codeNode = $createCodeNode(); selection.removeText(); selection.insertNodes([codeNode]); selection.insertRawText(textContent); } } }); } }; const syncBlockType = (event: any) => { const blockType = event.detail.blockType; setBlockType(blockType); }; useEffect(() => { window.addEventListener('blockTypeChange', syncBlockType); return () => { window.removeEventListener('blockTypeChange', syncBlockType); }; }, []); return ( ); }; export default BlockFormatDropdown;