import {
  appInit
} from "./chunk-N2SKTCDK.js";
import "./chunk-HKSNADSX.js";
import "./chunk-SKMFMGCD.js";
import {
  detectOne,
  sleep
} from "./chunk-DJQTUDJM.js";
import "./chunk-W55XSG6K.js";
import {
  require_tape
} from "./chunk-QWOE5YTB.js";
import "./chunk-4KY4XKJV.js";
import "./chunk-74ZU4BT6.js";
import "./chunk-IW57W7EQ.js";
import "./chunk-ZTYNN6G5.js";
import "./chunk-DKVUOBIE.js";
import "./chunk-PRZWSBMA.js";
import "./chunk-LTOBEUM2.js";
import "./chunk-MKAF2BHB.js";
import "./chunk-WKNI3HRQ.js";
import "./chunk-VGYTAYFK.js";
import "./chunk-67DBIM6H.js";
import {
  fillTermWrapper
} from "./chunk-SA7APTJR.js";
import "./chunk-HJ6L54YS.js";
import "./chunk-LSEFWW72.js";
import "./chunk-SKREEF3H.js";
import "./chunk-HYOEWQ5P.js";
import "./chunk-HBW42TDT.js";
import "./chunk-G6O3URDN.js";
import "./chunk-FN5XPUPH.js";
import "./chunk-IIT367QZ.js";
import "./chunk-RZGEKL77.js";
import "./chunk-UI7OCM2A.js";
import "./chunk-YZK37YCC.js";
import "./chunk-7EMWHCVW.js";
import "./chunk-7IYJZZQI.js";
import "./chunk-M3J4MINX.js";
import "./chunk-PF4DSFDR.js";
import "./chunk-QH6W3NVF.js";
import {
  NUMERIC_DICTIONARY_TERM,
  TermTypes
} from "./chunk-NOEAT6CX.js";
import "./chunk-4UWS5Y3N.js";
import "./chunk-DD4R5P6W.js";
import "./chunk-JNITUVXP.js";
import "./chunk-KSGA62R2.js";
import "./chunk-LOZEKOES.js";
import "./chunk-TOU7EVFQ.js";
import "./chunk-OAWQ6LOO.js";
import "./chunk-TLT4YIG3.js";
import "./chunk-KYBIQBXE.js";
import {
  select_default
} from "./chunk-I6Y4O3RR.js";
import "./chunk-OMR2DT66.js";
import "./chunk-DQC5FFGV.js";
import {
  __toESM
} from "./chunk-HFNDKYVF.js";

// plots/matrix/test/hierCluster.integration.spec.js
var import_tape = __toESM(require_tape(), 1);
(0, import_tape.default)("\n", function(test) {
  test.comment("-***- plots/hierCluster.js -***-");
  test.end();
});
(0, import_tape.default)("basic render", async (test) => {
  test.timeoutAfter(4e3);
  const { app, hc } = await getHierClusterApp({ terms: getGenes() });
  test.equal(hc.dom.termLabelG.selectAll(".sjpp-matrix-label").size(), 4, "should render 4 gene rows");
  test.equal(hc.dom.sampleLabelG.selectAll(".sjpp-matrix-label").size(), 60, "should render 60 sample columns");
  if (test._ok) app.destroy();
  test.end();
});
(0, import_tape.default)("filter", async (test) => {
  test.timeoutAfter(4e3);
  const { app, hc } = await getHierClusterApp({
    terms: getGenes(),
    filter: {
      type: "tvslst",
      join: "",
      in: true,
      lst: [{ type: "tvs", tvs: { term: { id: "diaggrp" }, values: [{ key: "Acute lymphoblastic leukemia" }] } }]
    }
  });
  test.equal(hc.dom.sampleLabelG.selectAll(".sjpp-matrix-label").size(), 36, "should render 36 sample columns");
  if (test._ok) app.destroy();
  test.end();
});
(0, import_tape.default)("avoid race condition - specified gene list", async (test) => {
  test.timeoutAfter(4e3);
  test.plan(4);
  const { app, hc } = await getHierClusterApp({ terms: getGenes() });
  const termgroups = structuredClone(hc.config.termgroups);
  const lst = await Promise.all([
    fillTermWrapper({ term: { gene: "KRAS", name: "KRAS", type: "geneExpression" } }, app.vocabApi),
    fillTermWrapper({ term: { gene: "AKT1", name: "AKT1", type: "geneExpression" } }, app.vocabApi),
    fillTermWrapper({ term: { gene: "TP53", name: "TP53", type: "geneExpression" } }, app.vocabApi),
    fillTermWrapper({ term: { gene: "BCR", name: "BCR", type: "geneExpression" } }, app.vocabApi)
  ]);
  termgroups[0].lst = lst;
  const responseDelay = 250;
  hc.origRequestData = hc.requestData;
  hc.requestData = async () => {
    const lst2 = hc.config.termgroups[0].lst;
    const data = await hc.origRequestData({});
    if (lst2.length === 3) return data;
    await sleep(250);
    return data;
  };
  const prom = {};
  const postRenderTest = new Promise((resolve) => {
    prom.resolve = resolve;
  });
  app.on("postRender.test1", () => {
    app.on("postRender.test1", null);
    prom.resolve();
  });
  await Promise.all([
    app.dispatch({
      type: "plot_edit",
      id: hc.id,
      config: { termgroups }
    }),
    (async () => {
      await sleep(0);
      const termgroups2 = structuredClone(hc.config.termgroups);
      termgroups2[0].lst = lst.slice(0, 3);
      await app.dispatch({
        type: "plot_edit",
        id: hc.id,
        config: { termgroups: termgroups2 }
      });
    })()
  ]);
  await postRenderTest;
  await sleep(responseDelay + 500);
  test.equal(hc.dom.termLabelG.selectAll(".sjpp-matrix-label").size(), 3, "should render 3 gene rows");
  const rects = hc.dom.seriesesG.selectAll(".sjpp-mass-series-g rect");
  const hits = rects.filter((d) => d.key !== "BCR" && d.value.class != "WT" && d.value.class != "Blank");
  test.equal(
    rects.size(),
    180,
    "should have the expected total number of matrix cell rects, inlcuding WT and not tested"
  );
  test.equal(hits.size(), 180, "should have the expected number of matrix cell rects with hits");
  test.equal(
    app.Inner.dom.holder.selectAll(".sja_errorbar").filter(function() {
      return this.style.display != "none";
    }).size(),
    0,
    "should not display errors"
  );
  if (test._ok) app.destroy();
});
(0, import_tape.default)("avoid race condition - reused fetch response cache", async (test) => {
  test.timeoutAfter(4e3);
  test.plan(4);
  const { app, hc } = await getHierClusterApp({ terms: getGenes() });
  const termgroups = structuredClone(hc.config.termgroups);
  const responseDelay = 250;
  hc.origRequestData = hc.requestData;
  hc.requestData = async () => {
    const lst = hc.config.termgroups[0].lst;
    const data = await hc.origRequestData({});
    if (lst.length === 3) return data;
    return data;
    await sleep(responseDelay);
    return data;
  };
  const prom = {};
  const postRenderTest = new Promise((resolve) => {
    prom.resolve = resolve;
  });
  app.on("postRender.test1", () => {
    app.on("postRender.test1", null);
    prom.resolve();
  });
  await Promise.all([
    app.dispatch({
      type: "plot_edit",
      id: hc.id,
      config: { termgroups }
    }),
    (async () => {
      await sleep(0);
      const _termgroups = structuredClone(termgroups);
      _termgroups[0].lst = _termgroups[0].lst.slice(0, 3);
      await app.dispatch({
        type: "plot_edit",
        id: hc.id,
        config: { termgroups: _termgroups }
      });
    })()
  ]);
  await postRenderTest;
  await sleep(responseDelay + 500);
  test.equal(hc.dom.termLabelG.selectAll(".sjpp-matrix-label").size(), 3, "should render 3 gene rows");
  const rects = hc.dom.seriesesG.selectAll(".sjpp-mass-series-g rect");
  const hits = rects.filter((d) => d.key !== "BCR" && d.value.class != "WT" && d.value.class != "Blank");
  test.equal(
    rects.size(),
    180,
    "should have the expected total number of matrix cell rects, inlcuding WT and not tested"
  );
  test.equal(hits.size(), 180, "should have the expected number of matrix cell rects with hits");
  test.equal(
    app.Inner.dom.holder.selectAll(".sja_errorbar").filter(function() {
      return this.style.display != "none";
    }).size(),
    0,
    "should not display errors"
  );
  if (test._ok) app.destroy();
});
(0, import_tape.default)("dendrogram click", async function(test) {
  test.timeoutAfter(5e3);
  test.plan(3);
  let numRenders = 0;
  const { app, hc } = await getHierClusterApp({ terms: getGenes() });
  const img = await detectOne({ elem: hc.dom.topDendrogram.node(), selector: "image" });
  const svgBox = hc.dom.svg.node().getBoundingClientRect();
  const imgBox = img.getBBox();
  img.dispatchEvent(
    new MouseEvent("click", {
      //'view': window,
      bubbles: true,
      cancelable: true,
      clientX: svgBox.x + hc.dimensions.xOffset + imgBox.x + imgBox.width / 2,
      clientY: svgBox.y + imgBox.y + imgBox.height / 2
    })
  );
  test.deepEqual(
    hc.clickedClusterIds,
    [
      46,
      54,
      37,
      28,
      27,
      51,
      53,
      44,
      49,
      25,
      34,
      11,
      20,
      41,
      45,
      29,
      33,
      17,
      15,
      2,
      38,
      42,
      30,
      36,
      22,
      9,
      14,
      3,
      4,
      31,
      13,
      26,
      1,
      16,
      8,
      10,
      5,
      6,
      7,
      23,
      47,
      48,
      35,
      43,
      21,
      32,
      18,
      24,
      56
    ],
    `should give the expected clickedClusterIds`
  );
  test.deepEqual(
    ["Zoom in", "List 50 samples"],
    [...hc.dom.dendroClickMenu.d.node().querySelectorAll(".sja_menuoption")].map((elem) => elem.__data__.label),
    "should show the expected menu options on dendrogram click"
  );
  hc.dom.dendroClickMenu.d.node().querySelector(".sja_menuoption").parentNode.lastChild.click();
  await sleep(5);
  test.equal(
    hc.dom.dendroClickMenu.d.node().querySelectorAll(".sjpp_row_wrapper").length,
    50,
    "should list the expected number of samples"
  );
  if (test._ok) {
    hc.dom.dendroClickMenu.clear().hide();
    app.destroy();
  }
});
(0, import_tape.default)("numericDictTerm", async function(test) {
  const terms = [
    {
      id: "aaclassic_5",
      // tw.id must be provided
      term: { id: "aaclassic_5", name: "a1", type: "float" },
      // requires {id,name,type}; term.name doesn't need to be real, unique name works
      q: { mode: "continuous" }
      // set to continuous to avoid validating tw.term.bins
    },
    { id: "hrtavg", term: { id: "hrtavg", name: "a2", type: "float" }, q: { mode: "continuous" } },
    { id: "agedx", term: { id: "agedx", name: "a3", type: "float" }, q: { mode: "continuous" } }
  ];
  const { app, hc } = await getHierClusterApp({ terms, dataType: NUMERIC_DICTIONARY_TERM });
  test.equal(hc.dom.termLabelG.selectAll(".sjpp-matrix-label").size(), 3, "should render 3 rows");
  if (test._ok) app.destroy();
  test.end();
});
async function getHierClusterApp(_opts = {}) {
  const holder = select_default("body").append("div");
  const defaults = {
    debug: true,
    holder,
    genome: "hg38-test",
    state: {
      genome: "hg38-test",
      dslabel: "TermdbTest",
      termfilter: { filter0: _opts.filter0 },
      plots: [
        {
          chartType: "hierCluster",
          dataType: _opts.dataType || TermTypes.GENE_EXPRESSION,
          settings: {
            hierCluster: {
              termGroupName: "Gene Expression (CGC genes only)"
            },
            matrix: {
              // the matrix autocomputes the colw based on available screen width,
              // need to set an exact screen width for consistent tests using getBBox()
              availContentWidth: 1200
            }
          },
          // force empty termgroups, genes since the instance requestData() will not have expression data,
          // and will cause a non-trival error if using the actual requestData(), which will be mocked below
          termgroups: [],
          // _opts.termgroups || [],
          // !!! there will be an initial load error since this is an empty geneset,
          // !!! but will be ignored since it's not relevant to this test
          terms: _opts.terms || [],
          filter: _opts.filter
        }
      ]
    },
    app: {
      features: ["recover"],
      callbacks: _opts?.app?.callbacks || {}
    },
    recover: {
      undoHtml: "Undo",
      redoHtml: "Redo",
      resetHtml: "Restore",
      adjustTrackedState(state) {
        const s = structuredClone(state);
        delete s.termfilter.filter0;
        return s;
      }
    },
    hierCluster: _opts?.hierCluster || {}
  };
  const opts = Object.assign(defaults, _opts);
  const app = await appInit(opts);
  holder.select(".sja_errorbar").node()?.lastChild?.click();
  const hc = Object.values(app.Inner.components.plots).find(
    (p) => p.type == "hierCluster" || p.chartType == "hierCluster"
  ).Inner;
  return { app, hc };
}
function getGenes() {
  return [
    { gene: "AKT1", type: "geneExpression" },
    { gene: "TP53", type: "geneExpression" },
    { gene: "BCR", type: "geneExpression" },
    { gene: "KRAS", type: "geneExpression" }
  ];
}
//# sourceMappingURL=hierCluster.integration.spec-SSDN7LSH.js.map
