PluginProbe
Code Block Pro – Beautiful Syntax Highlighting / 1.5.0
Code Block Pro – Beautiful Syntax Highlighting v1.5.0
1.27.1 1.27.2 1.27.3 1.27.4 1.27.5 1.27.6 1.27.7 1.28.0 1.3.0 1.4.0 1.5.0 1.5.1 1.5.2 1.6.0 1.7.0 1.8.0 1.9.0 1.9.1 1.9.2 1.9.3 trunk 1.1.0 1.10.0 1.11.0 1.11.1 All 63 releases
code-block-pro / src / editor / Edit.tsx

Edit.tsx in Code Block Pro – Beautiful Syntax Highlighting 1.5.0, at src/editor/Edit.tsx

94 lines 2.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { useEffect, useRef } from '@wordpress/element';
2 import { applyFilters } from '@wordpress/hooks';
3 import Editor from 'react-simple-code-editor';
4 import { useDefaults } from '../hooks/useDefaults';
5 import { useTheme } from '../hooks/useTheme';
6 import { useGlobalStore } from '../state/global';
7 import { useLanguageStore } from '../state/language';
8 import { useThemeStore } from '../state/theme';
9 import { AttributesPropsAndSetter } from '../types';
10
11 export const Edit = ({
12 attributes,
13 setAttributes,
14 }: AttributesPropsAndSetter) => {
15 const {
16 language,
17 theme,
18 code = '',
19 bgColor: backgroundColor,
20 textColor: color,
21 } = attributes;
22 const textAreaRef = useRef<HTMLDivElement>(null);
23 const handleChange = (code: string) => setAttributes({ code });
24 const { previousLanguage } = useLanguageStore();
25 const { highlighter, error, loading } = useTheme({
26 theme,
27 lang: language ?? previousLanguage,
28 });
29 useDefaults({ attributes, setAttributes });
30
31 useEffect(() => {
32 if (!highlighter) return;
33 setAttributes({
34 bgColor: highlighter.getBackgroundColor(),
35 textColor: highlighter.getForegroundColor(),
36 });
37 }, [theme, highlighter, setAttributes]);
38
39 useEffect(() => {
40 if (!highlighter) return;
41 // applyFilters()
42 setAttributes({
43 codeHTML: applyFilters(
44 'blocks.codeBlockPro.codeHTML',
45 highlighter.codeToHtml(code, {
46 lang: language ?? previousLanguage,
47 }),
48 attributes,
49 ) as string,
50 });
51 }, [
52 highlighter,
53 code,
54 language,
55 setAttributes,
56 previousLanguage,
57 attributes,
58 ]);
59
60 if ((loading && code) || error) {
61 return (
62 <div
63 className="p-8 px-4 text-left"
64 style={{ backgroundColor, color }}>
65 {error?.message ?? ''}
66 </div>
67 );
68 }
69
70 return (
71 <div ref={textAreaRef}>
72 <Editor
73 value={code}
74 onValueChange={handleChange}
75 padding={16}
76 style={{ backgroundColor, color }}
77 // eslint-disable-next-line
78 onKeyDown={(e: any) =>
79 e.key === 'Tab' &&
80 // Tab lock here. Pressing Escape will unlock.
81 textAreaRef.current?.querySelector('textarea')?.focus()
82 }
83 highlight={(code: string) =>
84 highlighter
85 ?.codeToHtml(code, {
86 lang: language ?? previousLanguage,
87 })
88 ?.replace(/<\/?[pre|code][^>]*>/g, '')
89 }
90 />
91 </div>
92 );
93 };
94