bindCacheEvents function domain

Last updated: 2026-03-01T23:25:47.136Z

Metrics

LOC: 144 Complexity: 17 Params: 0

Signature

bindCacheEvents(): : void

Architecture violations

View all

  • [warning] max-cyclomatic-complexity: 'bindCacheEvents' has cyclomatic complexity 17 (max 10)
  • [warning] max-lines: 'bindCacheEvents' has 144 lines (max 80)

Source Code

function bindCacheEvents(): void {
  document
    .getElementById("btn-refresh-cache")
    ?.addEventListener("click", async () => {
      await loadFieldCache();
      await loadLearnedEntries();
      showToast(t("toastCacheRefreshed"));
    });

  document
    .getElementById("btn-clear-cache")
    ?.addEventListener("click", async () => {
      await chrome.runtime.sendMessage({ type: "CLEAR_FIELD_CACHE" });
      await loadFieldCache();
      showToast(t("toastCacheCleared"));
    });

  document
    .getElementById("btn-clear-learning")
    ?.addEventListener("click", async () => {
      await chrome.runtime.sendMessage({ type: "CLEAR_LEARNED_ENTRIES" });
      await loadLearnedEntries();
      showToast(t("toastLearningCleared"));
    });

  document
    .getElementById("btn-export-rules-dataset")
    ?.addEventListener("click", async () => {
      const rules = (await chrome.runtime.sendMessage({
        type: "GET_RULES",
      })) as FieldRule[];

      if (!Array.isArray(rules) || rules.length === 0) {
        showToast(t("noRulesToExport"), "error");
        return;
      }

      const json = JSON.stringify(rules, null, 2);
      const blob = new Blob([json], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "fill-all-rules.json";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      showToast(t("rulesExportedMsg", [String(rules.length)]));
    });

  document
    .getElementById("btn-retrain-learning")
    ?.addEventListener("click", async () => {
      const btn = document.getElementById(
        "btn-retrain-learning",
      ) as HTMLButtonElement;
      const logBox = document.getElementById(
        "retrain-log-box",
      ) as HTMLElement | null;
      const logPre = document.getElementById(
        "retrain-log",
      ) as HTMLPreElement | null;

      btn.disabled = true;
      btn.textContent = t("retraining");

      if (logBox) logBox.style.display = "none";
      if (logPre) logPre.textContent = "";

      const t0 = performance.now();

      try {
        const result = (await chrome.runtime.sendMessage({
          type: "RETRAIN_LEARNING_DATABASE",
        })) as (RetrainResult & { success?: boolean }) | null;

        const elapsed = Math.round(performance.now() - t0);

        await loadLearnedEntries();

        if (result && logPre && logBox) {
          const lines: string[] = [];
          lines.push("═══════════════════════════════════════════");
          lines.push("  RETREINO DE VETORES — RESULTADO DETALHADO");
          lines.push("═══════════════════════════════════════════");
          lines.push("");
          lines.push(`  Total de regras encontradas : ${result.totalRules}`);
          lines.push(`  Importadas com sucesso      : ${result.imported}`);
          lines.push(`  Ignoradas (sem signals)     : ${result.skipped}`);
          lines.push(
            `  Duração total               : ${result.durationMs ?? elapsed}ms`,
          );
          lines.push("");
          lines.push("─── O QUE FOI FEITO ───────────────────────");
          lines.push(
            "  ✔ Entradas anteriores de regras foram removidas (entradas orgânicas preservadas).",
          );
          lines.push(
            "  ✔ Regras convertidas em sinais e salvas como LearnedEntry.",
          );
          lines.push("  ✔ Abas abertas notificadas (INVALIDATE_CLASSIFIER).");
          lines.push("  ✔ Próxima classificação usará os novos vetores.");
          lines.push("");
          lines.push("─── O QUE NÃO FOI FEITO ───────────────────");
          lines.push("  ✗ Os pesos da rede neural TF.js NÃO foram alterados.");
          lines.push(
            "  ✗ Os arquivos model.json / *.bin NÃO foram substituídos.",
          );
          lines.push("  → Para retreinar o modelo neural: npm run train:model");
          lines.push("");

          if (result.details && result.details.length > 0) {
            lines.push("─── DETALHES POR REGRA ────────────────────");
            for (const d of result.details) {
              const icon = d.status === "imported" ? "✔" : "✗";
              const sig = d.signals ? `"${d.signals.slice(0, 60)}"` : "(vazio)";
              lines.push(
                `  ${icon} [${d.type.padEnd(14)}] ${d.selector.slice(0, 40)}`,
              );
              lines.push(`       signals: ${sig}`);
            }
            lines.push("");
          }

          lines.push("═══════════════════════════════════════════");

          logPre.textContent = lines.join("\n");
          logBox.style.display = "block";
        }

        showToast(
          t("toastRetrainResult", [
            String(result?.imported ?? 0),
            String(result?.totalRules ?? 0),
            String(result?.durationMs ?? elapsed),
          ]),
        );
      } finally {
        btn.disabled = false;
        btn.textContent = t("btnRetrainVectors");
      }
    });
}

Dependencies (Outgoing)

graph LR bindCacheEvents["bindCacheEvents"] loadFieldCache["loadFieldCache"] loadLearnedEntries["loadLearnedEntries"] bindCacheEvents -->|calls| loadFieldCache bindCacheEvents -->|calls| loadLearnedEntries style bindCacheEvents fill:#dbeafe,stroke:#2563eb,stroke-width:2px click bindCacheEvents "ae693123fa601947.html" click loadFieldCache "46dd37f53cffbad9.html" click loadLearnedEntries "395376aee20c6cb3.html"
TargetType
loadFieldCache calls
loadLearnedEntries calls
click dynamic_call

Impact (Incoming)

graph LR bindCacheEvents["bindCacheEvents"] initCacheTab["initCacheTab"] initCacheTab -->|calls| bindCacheEvents style bindCacheEvents fill:#dbeafe,stroke:#2563eb,stroke-width:2px click bindCacheEvents "ae693123fa601947.html" click initCacheTab "c522a08a715e2b3a.html"
SourceType
initCacheTab calls