Skip to content
Snippets Groups Projects

Issue # 3518977: Added parser function to process code samples sent by the AI Provider

Files
7
+ 36
3
@@ -25,6 +25,27 @@ import parseAIResponse from './parser';
const ALLOWED_BLOCKS = ['core/heading', 'core/paragraph', 'core/quote'];
const checkIfHTMLString = (string) => {
const regexForHTML = /<([A-Za-z][A-Za-z0-9]*)\b[^>]*>(.*?)<\/\1>/;
string = JSON.parse(string);
const isValid = regexForHTML.test(string);
if (isValid) {
return true;
}
};
const htmlEntities = (str) => {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/\n/g, '<br />');
};
function Edit({ attributes, setAttributes }) {
const { title, blockTitle, aiAnswer } = attributes;
const [token, setToken] = useState({ token: '' });
@@ -57,7 +78,7 @@ function Edit({ attributes, setAttributes }) {
setIsDisabled(true);
setProcessingMessage('Processing....');
/* TODO: these fetch chains look ugly as hell, consider using async/await instead. */
/* @TODO: these fetch chains look ugly as hell, consider using async/await instead. */
fetch('/session/token')
.then((response) => response.text())
.then((csrfToken) => {
@@ -71,8 +92,20 @@ function Edit({ attributes, setAttributes }) {
})
.then((response) => response.text())
.then((data) => {
console.log(data);
const parsedData = parseAIResponse(data);
let parsedData = '';
const regex = /\\u([\d\w]{4})/gi;
const found = data.match(regex);
if (found !== null && found.length > 0 && checkIfHTMLString(data)) {
/* eslint-disable-next-line prefer-template */
parsedData = `<code>${htmlEntities(
JSON.parse(data),
)}</code><br /><br />`;
} else {
parsedData = parseAIResponse(data);
}
setToken({ token: parsedData });
setAttributes({ aiAnswer: parsedData });
setIsDisabled(false);
Loading