Merge pull request #264 from answerdev/feat/1.0.7/ui

fix: diff text optimization
This commit is contained in:
dashuai 2023-03-16 17:21:12 +08:00 committed by GitHub
commit a141550220
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 15 additions and 13 deletions

View File

@ -188,20 +188,27 @@ function handleFormError(
return data;
}
function escapeHtml(str: string) {
const tagsToReplace = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
'`': '&#96;',
};
return str.replace(/[&<>"'`]/g, (tag) => tagsToReplace[tag] || tag);
}
function diffText(newText: string, oldText?: string): string {
if (!newText) {
return '';
}
if (typeof oldText !== 'string') {
return newText
?.replace(/\n/gi, '<br>')
?.replace(/<kbd/gi, '&lt;kbd')
?.replace(/<\/kbd>/gi, '&lt;/kbd&gt;')
?.replace(/<iframe/gi, '&lt;iframe')
?.replace(/<input/gi, '&lt;input');
return escapeHtml(newText?.replace(/\n/gi, '<br>'));
}
const diff = Diff.diffChars(oldText, newText);
const diff = Diff.diffChars(escapeHtml(oldText), escapeHtml(newText));
const result = diff.map((part) => {
if (part.added) {
if (part.value.replace(/\n/g, '').length <= 0) {
@ -225,12 +232,7 @@ function diffText(newText: string, oldText?: string): string {
return part.value;
});
return result
.join('')
?.replace(/<iframe/gi, '&lt;iframe')
?.replace(/<kbd/gi, '&lt;kbd')
?.replace(/<\/kbd>/gi, '&lt;/kbd&gt;')
?.replace(/<input/gi, '&lt;input');
return result.join('');
}
function htmlToReact(html: string) {