From d288e537075c710f12d0919013bfb393ce79a799 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Pr=C3=A9nom=20Nom?= <adresse@mail.com>
Date: Sat, 15 Feb 2025 17:19:59 +0100
Subject: [PATCH] =?UTF-8?q?correction=20activation/d=C3=A9sactivation?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 src/background/background.js  | 120 +++++++++++++++++++++++++++++-----
 src/utils/stats.js            |  43 ++++--------
 src/workers/pyodide_worker.js |   2 +-
 3 files changed, 118 insertions(+), 47 deletions(-)

diff --git a/src/background/background.js b/src/background/background.js
index 338bfe0..178b3bf 100644
--- a/src/background/background.js
+++ b/src/background/background.js
@@ -322,13 +322,12 @@ function initWorker() {
     }}
   }
 
-//Initialisation
+//Initialisation du worker
 initWorker()
 
 // ─────────────────────────────────────────────────────────────────────────────
 // Écoute des messages de la popup et transmission au WebWorker
 // ─────────────────────────────────────────────────────────────────────────────
-
 browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
   console.log("[Background] Message reçu :", message);
 
@@ -338,10 +337,16 @@ browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
 
   if (message.command === "toggle-stats") {
       console.log(`[Background] Statistiques ${message.isActive ? "activées" : "désactivées"}`);
+      //Valeur du storage : actif
       const { isActive } = message;
       await browser.storage.local.set({ isTrackingActive: isActive });
-      // Transmettre l'activation des statistiques au WebWorker
-      worker.postMessage({ command: "toggle-stats", isActive: message.isActive });
+      //Si on désactive les stats, on met aussi la valeur autoAdd false
+      if (!isActive) {
+        await browser.storage.local.set({ autoAdd: false });
+        //console.log("[Background] autoAdd désactivé car les statistiques ont été désactivées.");
+      //Vérifier et activer le tracking
+      checkAndUpdateTracking();
+    }      
   }
   
   if (message.command === "pyodide-simplemma") {
@@ -349,25 +354,108 @@ browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
     worker.postMessage({ command: "pyodide-simplemma" });
   }
 
-  return true; // Permet une réponse asynchrone si nécessaire
+  if (message.command === "process-text") {
+    console.log("[Background] Envoi du texte au Worker pour traitement :", message.text);
+
+    // // Récupérer les préférences utilisateur depuis le stockage local
+    // const { accessToken, trackedLanguages, threshold, autoAdd } = await browser.storage.local.get([
+    //     "accessToken", "trackedLanguages", "threshold", "autoAdd"
+    // ]) || { trackedLanguages: [], threshold: 10, autoAdd: false };
+
+    // // Envoyer les données au Worker
+    // worker.postMessage({
+    //     type: "process-text",
+    //     text: message.text,
+    //     accessToken, 
+    //     trackedLanguages, 
+    //     threshold, 
+    //     autoAdd
+    // });
+  }
+  return true; 
 });
 
 // ─────────────────────────────────────────────────────────────────────────────
 // Écouter les réponses du WebWorker
 // ─────────────────────────────────────────────────────────────────────────────
-worker.onmessage = (event) => {
+worker.onmessage = async (event) => {
     console.log("[Background] Message du WebWorker :", event.data);
 
-    //Pyodide et Simplemma prêts
+    //Si Pyodide et Simplemma sont prêts : AJOUTER UNE INFO VISUELLE 
     if (event.data.type === "pyodide-simplemma" && event.data.status === "success") {
-      //Notifier tous les onglets
-        browser.tabs.query({}).then((tabs) => {
-            tabs.forEach((tab) => {
-                browser.tabs.sendMessage(tab.id, { command: "pyodide-simplemma-ready" })
-                    .catch((error) => console.warn(`[Background] Impossible d'envoyer un message à l'onglet ${tab.id} : ${error}`));
-            });
-        });
+      console.log("[Background] Pyodide et Simplemma prêts. Mise à jour de l'état.");
+
+      // Stocker l'information dans le localStorage
+      await browser.storage.local.set({ pyodideSimplemmaReady: true });
+
+      checkAndUpdateTracking();
     }
 };
-//Démarrer le tracking uniquement lorsque pyodide et simplemma sont prêts
-//Injecter le tracking partout (nouveaux onglets et actifs)
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Statistiques : Vérification et activation/désactivation du tracking
+// ─────────────────────────────────────────────────────────────────────────────
+async function checkAndUpdateTracking() {
+  const { isTrackingActive, pyodideSimplemmaReady } = await browser.storage.local.get(["isTrackingActive", "pyodideSimplemmaReady"]);
+
+  if (isTrackingActive && pyodideSimplemmaReady) {
+      console.log("[Background] Activation du tracking.");
+      notifyAllTabs({ command: "activate-stats" });
+  } else {
+      console.log("[Background] Désactivation du tracking.");
+      notifyAllTabs({ command: "deactivate-stats" });
+  }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Statistiques : Gestion des onglets
+// ─────────────────────────────────────────────────────────────────────────────
+// Fonction pour envoyer des messages à TOUS les onglets
+async function notifyAllTabs(message) {
+  browser.tabs.query({}).then((tabs) => {
+      tabs.forEach((tab) => {
+          browser.tabs.sendMessage(tab.id, message)
+              .catch((error) => console.warn(`[Background] Impossible d'envoyer un message à l'onglet ${tab.id} : ${error}`));
+      });
+  });
+}
+
+// Gestion des nouveaux onglets
+browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
+  if (changeInfo.status === "complete") {
+      browser.storage.local.get(["isTrackingActive", "pyodideSimplemmaReady"]).then(({ isTrackingActive, pyodideSimplemmaReady }) => {
+          if (isTrackingActive && pyodideSimplemmaReady) {
+              browser.tabs.executeScript(tabId, { file: "src/utils/stats.js" })
+                  .then(() => console.log(`[Background] stats.js injecté dans le nouvel onglet ${tabId}`))
+                  .catch((error) => console.warn(`[Background] Impossible d'injecter stats.js dans ${tabId} : ${error}`));
+
+              setTimeout(() => {
+                  browser.tabs.sendMessage(tabId, { command: "activate-stats" })
+                      .catch((error) => console.warn(`[Background] Impossible d'envoyer 'activate-stats' à ${tabId} : ${error}`));
+              }, 1000);
+          }
+      });
+  }
+});
+
+// Gestion du tracking pour les nouveaux onglets
+browser.tabs.onCreated.addListener((tab) => {
+  setTimeout(() => {
+      browser.storage.local.get(["isTrackingActive", "pyodideSimplemmaReady"]).then(({ isTrackingActive, pyodideSimplemmaReady }) => {
+          if (isTrackingActive && pyodideSimplemmaReady) {
+              console.log(`[Background] Nouveau onglet détecté (${tab.id}), activation du tracking.`);
+              browser.tabs.sendMessage(tab.id, { command: "activate-stats" })
+                  .catch((error) => console.warn(`[Background] Impossible d'activer le tracking sur ${tab.id} : ${error}`));
+          }
+      });
+  }, 1000);
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Écoute des modifications du stockage et mise à jour du tracking
+// ─────────────────────────────────────────────────────────────────────────────
+browser.storage.onChanged.addListener(async (changes, area) => {
+  if (area === "local" && (changes.isTrackingActive || changes.pyodideSimplemmaReady)) {
+    checkAndUpdateTracking();
+  }
+});
diff --git a/src/utils/stats.js b/src/utils/stats.js
index 49a6171..404ae6e 100644
--- a/src/utils/stats.js
+++ b/src/utils/stats.js
@@ -7,18 +7,11 @@
     let isTrackingActive = false;
     let scrollListenerAttached = false;
     const seenContent = new Set();
-    let simplemmaReady = false;
 
     /**
      * Fonction pour extraire le texte visible et l'envoyer au background script.
      */
     function trackVisibleContent() {
-        // pas de tracking tant que Pyodide n’est pas prêt
-        if (!simplemmaReady) {
-            console.log("[Stats] Pyodide n'est pas encore prêt, attente...");
-            return;
-        }
-
         let selectors = "p, h1, h2, h3, h4, h5, h6, ul, ol, li, table, tr, td, th, blockquote";
     
         // Sélecteurs spécifiques à exclure sur Wikipedia et d'autres sites
@@ -44,37 +37,27 @@
                 if (text.length > 10 && !seenContent.has(text)) {
                     seenContent.add(text);
                     console.log("[Stats] Envoi du texte filtré au background.js :", text);
-    
                     browser.runtime.sendMessage({ command: "process-text", text: text });
                 }
             }
         });
     }
+
     function cleanText(text) {
-        // Supprimer les puces et symboles inutiles
         text = text.replace(/[\u2022\u00b7•·■◆▪▸▹▶►▻⇨]/g, " ");  // Supprime puces et flèches
         text = text.replace(/[\t\n\r]+/g, " "); // Supprime les sauts de ligne inutiles
         text = text.replace(/\s{2,}/g, " "); // Remplace plusieurs espaces par un seul
-    
-        // Essayer d'extraire le contenu utile des tableaux (ex: "1 | Chat | Animal" → "1 Chat Animal")
         text = text.replace(/(\||\t)+/g, " "); // Remplace les séparateurs de tableau par un espace
         text = text.replace(/(\s*-+\s*)+/g, " "); // Supprime les lignes de séparation des tableaux
-        
-        // Supprimer les espaces en début et fin de texte
         text = text.trim();
-    
         return text;
     }
-    
-    
 
     // STATISTIQUES ------------------------------------------------------------------------------------------
     async function initializeTrackingState() {
         const { isTrackingActive: storedState } = await browser.storage.local.get("isTrackingActive");
         isTrackingActive = storedState ?? false;
-
         console.log("[Stats] État initial récupéré :", isTrackingActive);
-
         if (isTrackingActive) {
             startTracking();
         } else {
@@ -137,21 +120,21 @@
         }
     }
 
-    // GESTION DES MESSAGES ------------------------------------------------------------------------------------------
+    // GESTION DES MESSAGES envoyé depuis le background -----------------------------------------------------------------------------------------
     browser.runtime.onMessage.addListener((message) => {
-        if (message.command === "pyodide-simplemma-ready") {
-            console.log("[Stats] Pyodide et Simplemma prêt, démarrage du scraping : ");
-            simplemmaReady = true;
-            initializeTrackingState(); // démarre le tracking une fois Pyodide prêt
+        if (message.command === "activate-stats") {
+            console.log("[Stats] Activation demandée par le background script.");
+            startTracking();
         }
-
-        if (message.command === "update-stats") {
-            if (message.isActive && simplemmaReady) {
-                startTracking();
-            } else {
-                stopTracking();
-            }
+        if (message.command === "deactivate-stats") {
+            console.log("[Stats] Désactivation du tracking.");
+            stopTracking();
         }
     });
 
+    // Initialisation
+    // initializeTrackingState();
+
+    // Envoyer les données au WebWorker pour qu'il traite le texte scrappé
+
 })();
diff --git a/src/workers/pyodide_worker.js b/src/workers/pyodide_worker.js
index b76ab3a..aac6fc7 100644
--- a/src/workers/pyodide_worker.js
+++ b/src/workers/pyodide_worker.js
@@ -77,7 +77,7 @@ self.onmessage = async (event) => {
         }
     }
 
-    // Activer/désactiver les statistiques (stats.js)
+    // Traitement du texte (envoyé par stats.js)
     if (data.command === "toggle-stats") {
         console.log(`[WebWorker] Statistiques ${data.isActive ? "activées" : "désactivées"}`);
         return;
-- 
GitLab