67 lines
2.0 KiB
JavaScript
67 lines
2.0 KiB
JavaScript
import { useState, useEffect } from '@wordpress/element';
|
|
import { TextareaControl } from '@wordpress/components';
|
|
import { __ } from '@wordpress/i18n';
|
|
|
|
/**
|
|
* Simple validator functions for languages.
|
|
* You can expand these for more robust validation.
|
|
*/
|
|
const validators = {
|
|
css: (code) => {
|
|
// Very basic CSS validation: checks for opening/closing braces
|
|
const openBraces = (code.match(/{/g) || []).length;
|
|
const closeBraces = (code.match(/}/g) || []).length;
|
|
return openBraces === closeBraces;
|
|
},
|
|
js: (code) => {
|
|
try {
|
|
// Attempt to parse as JavaScript
|
|
new Function(code);
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
},
|
|
html: (code) => {
|
|
// Very basic HTML check: matching opening/closing tags
|
|
const openTags = (code.match(/<[^/!][^>]*>/g) || []).length;
|
|
const closeTags = (code.match(/<\/[^>]+>/g) || []).length;
|
|
return openTags === closeTags;
|
|
},
|
|
};
|
|
|
|
export default function CodeControl({
|
|
value,
|
|
onChange,
|
|
language = 'css',
|
|
label = __('Code', 'your-text-domain'),
|
|
rows = 10,
|
|
}) {
|
|
const [error, setError] = useState(false);
|
|
|
|
useEffect(() => {
|
|
// Validate code whenever value or language changes
|
|
const isValid = validators[language]
|
|
? validators[language](value)
|
|
: true; // fallback: no validation
|
|
setError(!isValid);
|
|
}, [value, language]);
|
|
|
|
return (
|
|
<div style={{ fontFamily: 'monospace', whiteSpace: 'pre' }}>
|
|
<TextareaControl
|
|
label={label + (error ? ' ⚠️ Invalid ' + language : '')}
|
|
value={value}
|
|
onChange={onChange}
|
|
placeholder={`Enter ${language} code here...`}
|
|
rows={rows}
|
|
style={{
|
|
borderColor: error ? 'red' : undefined,
|
|
background: '#f5f5f5',
|
|
fontFamily: 'monospace',
|
|
}}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|