Desktop: Fixed copying and pasting an image from Chrome in RTE

This commit is contained in:
Laurent Cozic
2023-11-17 18:11:17 +00:00
parent 60c2964acd
commit 2c9bf9f03a
7 changed files with 168 additions and 9 deletions
+36 -1
View File
@@ -1,4 +1,4 @@
import htmlUtils, { extractHtmlBody } from './htmlUtils';
import htmlUtils, { extractHtmlBody, htmlDocIsImageOnly } from './htmlUtils';
describe('htmlUtils', () => {
@@ -51,4 +51,39 @@ describe('htmlUtils', () => {
}
});
test('should tell if an HTML document is an image only', () => {
const testCases: [string, boolean][] = [
[
// This is the kind of HTML that's pasted when copying an image from Chrome
'<meta charset=\'utf-8\'>\n<img src="https://example.com/img.png"/>',
true,
],
[
'',
false,
],
[
'<img src="https://example.com/img.png"/>',
true,
],
[
'<img src="https://example.com/img.png"/><img src="https://example.com/img.png"/>',
false,
],
[
'<img src="https://example.com/img.png"/><p>Some text</p>',
false,
],
[
'<img src="https://example.com/img.png"/> Some text',
false,
],
];
for (const [input, expected] of testCases) {
const actual = htmlDocIsImageOnly(input);
expect(actual).toBe(expected);
}
});
});
+29
View File
@@ -404,4 +404,33 @@ export const extractHtmlBody = (html: string) => {
return bodyFound ? output.join('') : html;
};
export const htmlDocIsImageOnly = (html: string) => {
let imageCount = 0;
let nonImageFound = false;
let textFound = false;
const parser = new htmlparser2.Parser({
onopentag: (name: string) => {
if (name === 'img') {
imageCount++;
} else if (['meta'].includes(name)) {
// We allow these tags since they don't print anything
} else {
nonImageFound = true;
}
},
ontext: (text: string) => {
if (text.trim()) textFound = true;
},
});
parser.write(html);
parser.end();
return imageCount === 1 && !nonImageFound && !textFound;
};
export default new HtmlUtils();