From 1669426ef1c15b9c432651eb90d3ec87ac05f6c1 Mon Sep 17 00:00:00 2001
From: Volker Schukai <volker.schukai@schukai.com>
Date: Thu, 3 Jul 2025 13:07:50 +0200
Subject: [PATCH] fix: Refactor image handling in MessageContent for better
 readability #328

Summary of changes
- Introduced new imports for HTML and tab layout modules to streamline processing.
- Simplified regex handling for embedded images by eliminating unnecessary complexity.
- Cleaned up the code to improve readability and maintainability.

- Added imports for "./html.mjs" and "../../layout/tabs.mjs" to enhance modularity in the component. This prepares the ground for potential future features related to layout and content processing.
- Replaced the cumbersome CID regex handling with a more straightforward imgRegex that captures image tags. This change makes it easier to identify and replace source URLs in the HTML content, thereby improving clarity and facilitating debugging in the long run.
---
 source/components/content/viewer/message.mjs | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/source/components/content/viewer/message.mjs b/source/components/content/viewer/message.mjs
index 59dc4fe46..3891d1183 100644
--- a/source/components/content/viewer/message.mjs
+++ b/source/components/content/viewer/message.mjs
@@ -26,6 +26,9 @@ import { isArray, isObject } from "../../../types/is.mjs";
 import { findTargetElementFromEvent } from "../../../dom/events.mjs";
 import { getLocaleOfDocument } from "../../../dom/locale.mjs";
 
+import "./html.mjs";
+import "../../layout/tabs.mjs";
+
 export { MessageContent };
 
 /**
@@ -258,6 +261,7 @@ class MessageContent extends CustomElement {
 							(part.filename
 								? part.filename.split(".").slice(0, -1).join(".")
 								: null);
+
 						if (cid) {
 							embeddedImages[cid] = part;
 						} else {
@@ -282,6 +286,7 @@ class MessageContent extends CustomElement {
 		}
 
 		for (const cid in embeddedImages) {
+
 			const imagePart = embeddedImages[cid];
 			if (imagePart.content && imagePart.contentType) {
 				try {
@@ -314,14 +319,11 @@ class MessageContent extends CustomElement {
 					const objectUrl = URL.createObjectURL(blob);
 					this[embeddedImageUrlsSymbol].push(objectUrl); // Speichern zur späteren Widerrufung
 
-					// Den CID für die RegExp escapen, um Sonderzeichen zu behandeln
-					const escapedCid = cleanCid.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-					const cidRegex = new RegExp(
-						`src=["']cid:[^"']*?${escapedCid}[^"']*?["']`,
-						"gi",
+     				const imgRegex = /(<img\b(?:(?!src\s*=)[^>])*?)(?:\s+src\s*=\s*(["'])(?:\s*cid:[^'"]*|\s*)\2)?([^>]*>)/gi;
+					htmlContent = htmlContent.replace(
+						imgRegex,
+						`$1 src="${objectUrl}"$3`
 					);
-
-					htmlContent = htmlContent.replace(cidRegex, `src="${objectUrl}"`);
 				} catch (e) {
 					console.error(
 						`Error processing embedded image with CID '${cid}':`,
-- 
GitLab