| 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 |
disablePadding, |
| 22 |
} = attributes; |
| 23 |
const textAreaRef = useRef<HTMLDivElement>(null); |
| 24 |
const handleChange = (code: string) => setAttributes({ code }); |
| 25 |
const { previousLanguage } = useLanguageStore(); |
| 26 |
const { highlighter, error, loading } = useTheme({ |
| 27 |
theme, |
| 28 |
lang: language ?? previousLanguage, |
| 29 |
}); |
| 30 |
useDefaults({ attributes, setAttributes }); |
| 31 |
|
| 32 |
useEffect(() => { |
| 33 |
if (!highlighter) return; |
| 34 |
setAttributes({ |
| 35 |
bgColor: highlighter.getBackgroundColor(), |
| 36 |
textColor: highlighter.getForegroundColor(), |
| 37 |
}); |
| 38 |
}, [theme, highlighter, setAttributes]); |
| 39 |
|
| 40 |
useEffect(() => { |
| 41 |
if (!highlighter) return; |
| 42 |
// applyFilters() |
| 43 |
setAttributes({ |
| 44 |
codeHTML: applyFilters( |
| 45 |
'blocks.codeBlockPro.codeHTML', |
| 46 |
highlighter.codeToHtml(code, { |
| 47 |
lang: language ?? previousLanguage, |
| 48 |
}), |
| 49 |
attributes, |
| 50 |
) as string, |
| 51 |
}); |
| 52 |
}, [ |
| 53 |
highlighter, |
| 54 |
code, |
| 55 |
language, |
| 56 |
setAttributes, |
| 57 |
previousLanguage, |
| 58 |
attributes, |
| 59 |
]); |
| 60 |
|
| 61 |
if ((loading && code) || error) { |
| 62 |
return ( |
| 63 |
<div |
| 64 |
className="p-8 px-4 text-left" |
| 65 |
style={{ backgroundColor, color }}> |
| 66 |
{error?.message ?? ''} |
| 67 |
</div> |
| 68 |
); |
| 69 |
} |
| 70 |
|
| 71 |
return ( |
| 72 |
<div ref={textAreaRef}> |
| 73 |
<Editor |
| 74 |
value={code} |
| 75 |
onValueChange={handleChange} |
| 76 |
padding={disablePadding ? 0 : 16} |
| 77 |
style={{ backgroundColor, color }} |
| 78 |
// eslint-disable-next-line |
| 79 |
onKeyDown={(e: any) => |
| 80 |
e.key === 'Tab' && |
| 81 |
// Tab lock here. Pressing Escape will unlock. |
| 82 |
textAreaRef.current?.querySelector('textarea')?.focus() |
| 83 |
} |
| 84 |
highlight={(code: string) => |
| 85 |
highlighter |
| 86 |
?.codeToHtml(code, { |
| 87 |
lang: language ?? previousLanguage, |
| 88 |
}) |
| 89 |
?.replace(/<\/?[pre|code][^>]*>/g, '') |
| 90 |
} |
| 91 |
/> |
| 92 |
</div> |
| 93 |
); |
| 94 |
}; |
| 95 |
|