fix: delete code block on backspace when code block is empty (#877)

This commit is contained in:
Daniel Lautzenheiser 2023-09-14 10:14:42 -04:00 committed by GitHub
parent 1338ad2f57
commit 48b472163f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 5 deletions

View File

@ -1,4 +1,4 @@
import { findNodePath, setNodes } from '@udecode/plate';
import { findNodePath, focusEditor, removeNodes, setNodes } from '@udecode/plate';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Frame from 'react-frame-component';
@ -32,15 +32,24 @@ const CodeBlockElement: FC<PlateRenderElementProps<MdValue, MdCodeBlockElement>>
[editor, element],
);
const handleDelete = useCallback(() => {
const path = findNodePath(editor, element);
path && removeNodes(editor, { at: path });
focusEditor(editor);
}, [editor, element]);
const receiveMessage = useCallback(
(event: MessageEvent) => {
switch (event.data.message) {
case `code_block_${id}_onChange`:
handleChange(event.data.value);
break;
case `code_block_${id}_delete`:
handleDelete();
break;
}
},
[handleChange, id],
[handleChange, handleDelete, id],
);
useWindowEvent('message', receiveMessage);

View File

@ -7,8 +7,9 @@ import React, { useCallback, useMemo } from 'react';
import { useFrame } from 'react-frame-component';
import languages from '@staticcms/code/data/languages';
import { isEmpty } from '@staticcms/core/lib/util/string.util';
import type { FC } from 'react';
import type { FC, KeyboardEvent } from 'react';
export interface CodeBlockFrameProps {
id: string;
@ -61,6 +62,15 @@ const CodeBlockFrame: FC<CodeBlockFrameProps> = ({ id, lang, code, theme }) => {
window?.parent.postMessage({ message: `code_block_${id}_onBlur` });
}, [id, window?.parent]);
const handleKeyDown = useCallback(
(event: KeyboardEvent) => {
if (event.key === 'Backspace' && isEmpty(code)) {
window?.parent.postMessage({ message: `code_block_${id}_delete` });
}
},
[code, id, window?.parent],
);
return (
<CodeMirror
value={code}
@ -68,6 +78,7 @@ const CodeBlockFrame: FC<CodeBlockFrameProps> = ({ id, lang, code, theme }) => {
onFocus={handleFocus}
onBlur={handleBlur}
onChange={handleChange}
onKeyDown={handleKeyDown}
extensions={extensions}
theme={theme}
/>

View File

@ -3,12 +3,12 @@ import { ELEMENT_CODE_BLOCK, createPluginFactory } from '@udecode/plate';
import deserializeHtmlCodeBlock from './deserializeHtmlCodeBlock';
import type { MdValue } from '@staticcms/markdown';
import type { HotkeyPlugin, PlateEditor } from '@udecode/plate';
import type { CodeBlockPlugin, PlateEditor } from '@udecode/plate';
/**
* Enables support for pre-formatted code blocks.
*/
const createCodeBlockPlugin = createPluginFactory<HotkeyPlugin, MdValue, PlateEditor<MdValue>>({
const createCodeBlockPlugin = createPluginFactory<CodeBlockPlugin, MdValue, PlateEditor<MdValue>>({
key: ELEMENT_CODE_BLOCK,
isElement: true,
deserializeHtml: deserializeHtmlCodeBlock,