import {
  matrix_layout_exports
} from "./chunk-36EHIPV4.js";
import {
  matrix_serieses_exports
} from "./chunk-EH4NQ7C4.js";
import {
  matrix_legend_exports
} from "./chunk-VGJSASRT.js";
import {
  matrix_groups_exports
} from "./chunk-ODG6RD7P.js";
import {
  setComputedConfig
} from "./chunk-BWGU5NJS.js";
import {
  setMatrixDom
} from "./chunk-HUBO743S.js";
import {
  setInteractivity
} from "./chunk-6GN7X6LU.js";
import {
  setRenderers
} from "./chunk-3ZLJDFJU.js";
import {
  MatrixCluster
} from "./chunk-DDKS3MV3.js";
import {
  getSorterUi
} from "./chunk-VV36JRUF.js";
import {
  matrix_data_exports
} from "./chunk-XMLURPEP.js";
import {
  GeneSetEditUI,
  GeneSetEditUIwithTabs,
  PlotBase,
  TwRouter,
  fillTermWrapper,
  get$id,
  getCombinedTermFilter,
  getGEunit,
  initByInput,
  make_one_checkbox,
  make_radios,
  rebaseGroupFilter,
  routedTermTypes,
  sayerror,
  svgLegend,
  svgScroll,
  to_svg,
  zoom
} from "./chunk-SA7APTJR.js";
import {
  Menu
} from "./chunk-HYOEWQ5P.js";
import {
  icons
} from "./chunk-IIT367QZ.js";
import {
  copyMerge,
  deepEqual,
  getCompInit
} from "./chunk-M3J4MINX.js";
import {
  TermTypes,
  isNumericTerm
} from "./chunk-NOEAT6CX.js";
import {
  dt2label,
  dtcnv,
  dtfusionrna,
  dtsnvindel,
  dtsv,
  mclass,
  morigin
} from "./chunk-4UWS5Y3N.js";
import {
  convertUnits
} from "./chunk-JNITUVXP.js";
import {
  select_default
} from "./chunk-I6Y4O3RR.js";

// plots/matrix/matrix.controls.samples.ts
function setSamplesBtn(self2, s) {
  const l = s.controlLabels;
  const controls = self2;
  const parent = self2.parent;
  const rows = [
    {
      label: `Maximum # ${l.Samples}`,
      title: `Limit the number of displayed ${l.samples}`,
      type: "number",
      chartType: "matrix",
      settingsKey: "maxSample",
      getDisplayStyle(plot) {
        return plot.chartType == "hierCluster" ? "none" : "table-row";
      }
    },
    {
      label: `Sort ${l.Sample} Groups`,
      title: `Set how to sort ${l.sample} groups`,
      type: "radio",
      chartType: "matrix",
      settingsKey: "sortSampleGrpsBy",
      options: [
        {
          label: "Predefined or Group Name",
          value: "name",
          title: `Sort by group name`
        },
        {
          label: `${l.Sample} Count`,
          value: "sampleCount",
          title: `Sort by the number of samples in the group`
        },
        {
          label: `Hits`,
          value: "hits",
          title: `Sort by the total number of variants for every ${l.sample} in the group`
        }
      ],
      getDisplayStyle(plot) {
        return plot.divideBy && !plot.hierCluster ? "table-row" : "none";
      }
    },
    {
      label: `${l.Sample} Group Label Character Limit`,
      title: `Truncate the ${l.sample} group label if it exceeds this maximum number of characters`,
      type: "number",
      chartType: "matrix",
      settingsKey: "sampleGrpLabelMaxChars",
      getDisplayStyle(plot) {
        return plot.divideBy && !plot.hierCluster ? "table-row" : "none";
      }
    },
    {
      label: `${l.Sample} Label Character Limit`,
      title: `Truncate the ${l.sample} label if it exceeds this maximum number of characters`,
      type: "number",
      chartType: "matrix",
      settingsKey: "collabelmaxchars"
    },
    {
      label: `Toggle sample labels`,
      title: `Do not automatically show sample labels based on column width`,
      type: "radio",
      chartType: "matrix",
      settingsKey: "sampleLabelsToggle",
      styles: { display: "inline-block" },
      options: [
        { label: `Based on column width`, value: "auto" },
        { label: "Always hide", value: "hide" }
      ]
    },
    {
      label: `Group ${l.Samples} By`,
      title: `Select a variable with discrete values to group ${l.samples}`,
      type: "term",
      chartType: "matrix",
      configKey: "divideBy",
      vocabApi: self2.opts.app.vocabApi,
      state: {
        vocab: self2.opts.vocab
        //activeCohort: appState.activeCohort
      },
      processInput: async (tw) => {
        if (tw?.term && isNumericTerm(tw.term)) {
          tw.q = { ...tw.q, mode: "discrete" };
        }
        if (tw) await fillTermWrapper(tw, self2.opts.app.vocabApi);
        return tw;
      },
      processConfig: (config) => {
        if (self2.parent.chartType == "hierCluster" && config["divideBy"]) {
          config.settings = {
            hierCluster: {
              yDendrogramHeight: 0,
              clusterSamples: false
            }
          };
        }
        if (self2.parent.config.divideBy)
          config.legendValueFilter = self2.parent.mayRemoveTvsEntry(self2.parent.config.divideBy);
      },
      getBodyParams: () => {
        const currentGeneNames = self2.parent.termOrder.filter((t) => t.tw.term.type === "geneVariant").map(
          (t) => t.tw.term.chr ? `${t.tw.term.chr}:${t.tw.term.start}-${t.tw.term.stop}` : t.tw.term.gene || t.tw.term.name
        );
        if (currentGeneNames.length) return { currentGeneNames };
        return {};
      }
    }
  ];
  rows.push({
    label: `Sort ${l.Sample} Priority`,
    title: `Set how to sort ${l.samples}`,
    type: "custom",
    // the "input" argument is created by controls
    init(input) {
      const m = parent.config.settings.matrix;
      if (!controls.activeTab) controls.activeTab = "basic";
      input.dom.inputTd.style("padding", "5px");
      const btnsDiv = input.dom.inputTd.append("div").style("margin-bottom", "5px");
      const basicBtn = btnsDiv.append("div").style("display", "inline-block").style("padding-right", "5px").style("border-right", "2px solid black").style("text-decoration", controls.activeTab == "basic" ? "underline" : "").style("cursor", "pointer").html("Basic").on("click", () => {
        controls.activeTab = "basic";
        basicBtn.style("text-decoration", "underline");
        advancedBtn.style("text-decoration", "");
        basicDiv.style("display", "");
        advancedDiv.style("display", "none");
      });
      const advancedBtn = btnsDiv.append("div").style("display", "inline-block").style("margin-left", "5px").style("text-decoration", controls.activeTab == "advanced" ? "underline" : "").style("cursor", "pointer").html("Advanced").on("click", () => {
        controls.activeTab = "advanced";
        basicBtn.style("text-decoration", "");
        advancedBtn.style("text-decoration", "underline");
        basicDiv.style("display", "none");
        advancedDiv.style("display", "");
      });
      const basicDiv = input.dom.inputTd.append("div").style("display", controls.activeTab == "basic" ? "" : "none");
      const ssmDiv = basicDiv.append("div");
      ssmDiv.append("span").html("SSM");
      const { inputs } = make_radios({
        // holder, options, callback, styles
        holder: ssmDiv.append("span"),
        options: [
          { label: "by consequence", value: "consequence", checked: m.sortByMutation === "consequence" },
          { label: "by presence", value: "presence", checked: m.sortByMutation === "presence" }
        ],
        styles: {
          display: "inline-block"
        },
        callback: (sortByMutation) => {
          const sortOptions = parent.config.settings.matrix.sortOptions;
          const activeOption = sortOptions.a;
          const mutTb = activeOption.sortPriority[0].tiebreakers[1];
          mutTb.disabled = !sortByMutation;
          mutTb.isOrdered = sortByMutation === "consequence";
          parent.app.dispatch({
            type: "plot_edit",
            id: parent.id,
            config: {
              settings: {
                matrix: {
                  sortByMutation,
                  // needed to show the correct status for checkbox, but actual sorting behavior
                  sortOptions
                  // is based on sortOptions.a[*].tiebreaker[*][disabled, isOrdered]
                }
              }
            }
          });
        }
      });
      inputs.style("margin", "2px 0 0 2px").style("vertical-align", "top");
      const cnvDiv = basicDiv.append("div").style("display", m.showMatrixCNV != "none" && !m.allMatrixCNVHidden ? "block" : "none");
      cnvDiv.append("span").html("CNV");
      const checkbox = make_one_checkbox({
        holder: cnvDiv.append("span"),
        divstyle: { display: "inline-block" },
        checked: m.sortByCNV,
        labeltext: "sort by CNV",
        callback: () => {
          const sortByCNV = checkbox.property("checked");
          const sortOptions = parent.config.settings.matrix.sortOptions;
          const activeOption = sortOptions.a;
          const cnvTb = activeOption.sortPriority[0].tiebreakers[2];
          cnvTb.disabled = !sortByCNV;
          cnvTb.isOrdered = sortByCNV;
          parent.app.dispatch({
            type: "plot_edit",
            id: parent.id,
            config: {
              settings: {
                matrix: {
                  sortByCNV,
                  // needed to show the correct status for checkbox, but actual sorting behavior
                  sortOptions
                  // is based on sortOptions.a[*].tiebreaker[*][disabled, isOrdered]
                }
              }
            }
          });
        }
      });
      const advancedDiv = input.dom.inputTd.append("div").style("display", controls.activeTab == "advanced" ? "" : "none");
      input.dom.row.on("mouseover", function() {
        this.style.backgroundColor = "#fff";
        this.style.textShadow = "none";
      });
      if (!controls.sorterUi) {
        controls.sorterUi = getSorterUi({
          controls,
          holder: advancedDiv,
          tip: controls.parent.app.tip
        });
      } else {
        controls.sorterUi.main(controls.parent.config.settings.matrix, { holder: advancedDiv });
      }
      return {
        main: (plot) => {
          const s2 = plot.settings.matrix;
          inputs.property("checked", (d) => d.value == s2.sortByMutation);
          checkbox.property("checked", s2.sortByCNV);
          cnvDiv.style("display", s2.showMatrixCNV != "none" && !s2.allMatrixCNVHidden ? "block" : "none");
        }
      };
    }
  });
  self2.opts.holder.append("button").datum({
    label: l.Samples || `Samples`,
    getCount: () => "sampleCount" in self2.overrides ? self2.overrides.sampleCount : self2.parent.sampleOrder?.length || 0,
    rows,
    customInputs: updateSamplesControls
  }).html((d) => d.label).style("margin", "2px 0").on("click", (event, d) => self2.callback(event, d));
}
function updateSamplesControls(self2, app, parent, table) {
  if (parent.chartType == "hierCluster" && parent.config.settings.hierCluster.clusterSamples) {
    const l = parent.config.settings.matrix.controlLabels;
    const sortingControl = select_default(
      table.selectAll("td").filter(function() {
        return select_default(this).text() == `Sort ${l.Sample} Priority`;
      }).node().closest("tr")
    );
    sortingControl.style("display", "none");
  }
}

// plots/matrix/matrix.controls.genes.ts
var tip = new Menu({ padding: "" });
function setGenesBtn(self2, s) {
  const l = s.controlLabels;
  const renderStyleOptions = [
    {
      label: `&nbsp;Stacked <span style="font-size:.7em;color:#555;">Show stacked rectangles in the same matrix cell to render variants for the same ${l.sample} and gene</span>`,
      value: "",
      title: `Show stacked rectangles in the same matrix cell to render variants for the same ${l.sample} and gene`
    },
    {
      label: `&nbsp;OncoPrint <span style="font-size:.7em;color:#555;">Show overlapping rectangles in the same matrix cell to render variants for the same ${l.sample} and gene</span>`,
      value: "oncoprint",
      title: `Show overlapping rectangles in the same matrix cell to render variants for the same ${l.sample} and gene`
    }
  ];
  if (s.addMutationCNVButtons && self2.parent.chartType !== "hierCluster")
    renderStyleOptions.unshift({
      label: `&nbsp;Single <span style="font-size:.7em;color:#555;">Show a single rectangle in a matrix cell to render the most severe variant (truncating > indels > missense > synonymous) for the same ${l.sample} and gene</span>`,
      value: "single",
      title: `Show a single rectangle in a matrix cell to render the most severe variant (truncating > indels > missense > synonymous) for the same ${l.sample} and gene`
    });
  self2.opts.holder.append("button").datum({
    label: "Genes",
    getCount: () => self2.parent.termOrder?.filter(
      (t) => t.tw.term.type == TermTypes.GENE_VARIANT || t.tw.term.type == TermTypes.GENE_EXPRESSION
    ).length || 0,
    customInputs: addGeneInputs,
    rows: [
      {
        label: `Display ${l.Sample} Counts for Gene`,
        title: `Include the ${l.sample} count in the gene label`,
        type: "radio",
        chartType: "matrix",
        settingsKey: "samplecount4gene",
        styles: { display: "inline-block" },
        options: [
          { label: "Absolute", value: "abs" },
          { label: `Percent`, value: "pct" },
          { label: `None`, value: "" }
        ],
        getDisplayStyle() {
          return self2.parent.termOrder?.filter((t) => t.tw.term.type == "geneVariant").length ? "table-row" : "none";
        }
      },
      // TODO: implement this contol option
      // {
      // 	label: `Exclude From ${l.Sample} Displayed Counts`,
      // 	title: `Do not include these variations/mutations when counting samples for a gene.`,
      // 	type: 'text',
      // 	chartType: 'matrix',
      // 	settingsKey: 'geneVariantCountSamplesSkipMclass',
      // 	processInput: tw => {},
      // },
      {
        label: "Genomic Alterations Rendering",
        title: `Set how to indicate a ${l.sample}'s applicable variant types in the same matrix cell`,
        type: "radio",
        chartType: "matrix",
        settingsKey: "cellEncoding",
        options: renderStyleOptions,
        styles: { padding: "5px 0px", margin: 0 },
        labelDisplay: "block",
        getDisplayStyle() {
          return self2.parent.termOrder?.filter((t) => t.tw.term.type == "geneVariant").length ? "table-row" : "none";
        },
        callback: self2.parent.geneStyleControlCallback
      },
      {
        label: "Sort Genes",
        title: "Set how to order the genes as rows",
        type: "radio",
        chartType: "matrix",
        settingsKey: "sortTermsBy",
        options: [
          { label: "By Input Data Order", value: "asListed" },
          { label: `By ${l.sample} Count`, value: "sampleCount" }
        ],
        styles: { padding: 0, "padding-right": "10px", margin: 0, display: "inline-block" },
        getDisplayStyle() {
          return self2.parent.termOrder?.filter((t) => t.tw.term.type == "geneVariant").length ? "table-row" : "none";
        }
      }
    ]
  }).html((d) => d.label).style("margin", "2px 0").on("click", (event, d) => self2.callback(event, d));
}
async function addGeneInputs(self2, app, parent, table) {
  if (parent.chartType == "hierCluster" && parent.config.dataType == TermTypes.GENE_EXPRESSION) {
    appendGeneInputs(self2, app, parent, table, "hierCluster");
  }
  if (parent.state?.termdbConfig?.allowedTermTypes?.includes(TermTypes.GENE_VARIANT) || parent.state.termdbConfig.queries.snvindel)
    appendGeneInputs(self2, app, parent, table);
}
async function appendGeneInputs(self2, app, parent, table, geneInputType) {
  tip.clear();
  if (!parent.selectedGroup) parent.selectedGroup = 0;
  if (parent.opts.customInputs?.genes) {
    for (const inputConfig of parent.opts.customInputs.genes) {
      inputConfig.chartType = "matrix";
      const holder = table.append("tr");
      if (inputConfig.title) holder.attr("aria-label", inputConfig.title);
      const input = await initByInput[inputConfig.type](
        Object.assign(
          {},
          {
            holder,
            app,
            id: parent.id,
            debug: self2.opts.debug,
            parent
          },
          inputConfig
        )
      );
      input.main(parent.config);
    }
  }
  let geneInputTr;
  if (geneInputType == "hierCluster" || parent.chartType !== "hierCluster") {
    geneInputTr = table.insert("tr", () => table.select("tr").node());
  } else {
    const secondTr = table.selectAll("tr").nodes()[1] || null;
    const hrTr = table.insert("tr", () => secondTr);
    hrTr.append("td").attr("colspan", 2).append("hr").style("border", "1px solid #ccc");
    geneInputTr = table.insert("tr", () => secondTr);
  }
  addGenesetInput(self2, app, parent, geneInputTr, geneInputType);
}
function addGenesetInput(self2, app, parent, tr, geneInputType) {
  const controlPanelBtn = self2.btns.filter((d) => d.label.endsWith("Genes"))?.node();
  const tip3 = app.tip;
  const tg = parent.config.termgroups;
  const { maxGenes, genesetEditUiVersion } = parent.settings?.matrix || parent.config?.settings?.matrix || {};
  let selectedGroup;
  const triggerGenesetEdit = (holder) => {
    holder.selectAll("*").remove();
    const geneList = selectedGroup.lst.map((item) => {
      return { gene: item.name };
    });
    const genesetUi = genesetEditUiVersion === "withTabs" ? GeneSetEditUIwithTabs : GeneSetEditUI;
    new genesetUi({
      holder,
      genome: app.opts.genome,
      geneList,
      // Remove the GFF Loads Gene Sets option from unclustered genes panel.
      customInputs: parent.chartType !== "hierCluster" || geneInputType == "hierCluster" ? self2.parent.opts.customInputs?.geneset : void 0,
      /* running hier clustering and the editing group is the group used for clustering
      pass this mode value to inform ui to support the optional button "top variably exp gene"
      this is hardcoded for the purpose of gene expression and should be improved
      */
      mode: selectedGroup.mode,
      minNumGenes: selectedGroup.mode == "geneExpression" ? 3 : 1,
      maxNumGenes: maxGenes,
      vocabApi: self2.opts.app.vocabApi,
      callback: async ({ geneList: geneList2, groupName }) => {
        if (!selectedGroup) throw `missing selectedGroup`;
        tip3.hide();
        const group = selectedGroup.status == "new" ? { name: groupName, lst: [] } : tg[selectedGroup.index];
        if (selectedGroup.status == "new") tg.push(group);
        const targetTermType = selectedGroup.mode == "geneExpression" ? "geneExpression" : "geneVariant";
        const lst = group.lst.filter((tw) => tw.term.type != targetTermType);
        const tws = await Promise.all(
          geneList2.map(async (d) => {
            let term;
            if (targetTermType == "geneExpression") {
              const gene = d.symbol || d.gene;
              const unit = getGEunit(app.vocabApi);
              const name = `${gene} ${unit}`;
              term = { gene, name, type: "geneExpression" };
            } else {
              term = {
                gene: d.symbol || d.gene,
                name: d.symbol || d.gene,
                type: "geneVariant"
              };
            }
            let tw = group.lst.find((t) => {
              const geneName = t.term.gene || t.term.name;
              const match = d.symbol ? geneName === d.symbol : d.gene ? geneName === d.gene : false;
              return match && t.term.type == targetTermType;
            });
            if (!tw) {
              tw = { term };
              await fillTermWrapper(tw, self2.opts.app.vocabApi);
            } else if (!tw.$id) {
              tw.$id = await get$id(self2.opts.app.vocabApi.getTwMinCopy({ term }));
            }
            return tw;
          })
        );
        group.lst = [...lst, ...tws];
        if (!group.lst.length) tg.splice(selectedGroup.index, 1);
        app.dispatch({
          type: "plot_edit",
          id: self2.parent.id,
          config: {
            termgroups: tg
          }
        });
      },
      backBtn: {
        target: "Genes Menu",
        callback: () => {
          controlPanelBtn.click();
        }
      },
      termsAsListed: geneInputType == "hierCluster" && !self2.parent.config.settings.hierCluster.clusterRows || geneInputType != "hierCluster" && self2.parent.config.settings.matrix.sortTermsBy == "asListed"
    });
  };
  const numOfEditableGrps = tg.filter((g) => g.type != "hierCluster").length;
  tr.append("td").attr("class", "sja-termdb-config-row-label").html(geneInputType == "hierCluster" ? "Hierarchical Clustering Gene Set" : "Genomic Alteration Gene Set");
  if (numOfEditableGrps > 0 || geneInputType == "hierCluster") {
    const td1 = tr.append("td").style("display", "block").style("padding", "5px 0px");
    const editGrpDiv = td1.append("div").append("label");
    editGrpDiv.append("button").html(
      numOfEditableGrps > 1 && geneInputType !== "hierCluster" ? "Edit Selected Group" : geneInputType == "hierCluster" ? "Edit Gene Set" : "Edit Current Group"
    ).on("click", () => {
      tip3.clear();
      setMenuBackBtn(tip3.d.append("div").style("padding", "5px"), () => controlPanelBtn.click(), `Back`);
      const genesetEdiUiHolder = tip3.d.append("div");
      triggerGenesetEdit(genesetEdiUiHolder);
    });
    if (numOfEditableGrps > 1 && geneInputType !== "hierCluster") {
      const { nonHierClusterGroups, groupSelect } = setTermGroupSelector(self2, editGrpDiv, tg);
      selectedGroup = nonHierClusterGroups.find((g) => g.selected);
      groupSelect.on("change", () => {
        selectedGroup = nonHierClusterGroups[groupSelect.property("value")];
      });
    } else {
      const s = parent.config.settings.hierCluster;
      const g = geneInputType == "hierCluster" ? tg.find((g2) => g2.type == "hierCluster") : tg.find((g2) => g2.type != "hierCluster");
      selectedGroup = {
        index: geneInputType == "hierCluster" ? tg.findIndex((g2) => g2.type == "hierCluster") : tg[0].type == g.type ? 0 : 1,
        name: g.name,
        type: g.type,
        lst: g.type == "hierCluster" ? g.lst.map((tw) => ({ name: tw.term.gene || tw.term.name })) : g.lst.filter((tw) => tw.term.type == TermTypes.GENE_VARIANT).map((tw) => ({ name: tw.term.name })),
        mode: g.type == "hierCluster" ? s.dataType : (
          // !!subject to change!! when group is not clustering, and ds has mutation, defaults to MUTATION_CNV_FUSION
          self2.parent.state.termdbConfig.queries?.snvindel ? TermTypes.GENE_VARIANT : ""
        ),
        selected: true
      };
    }
  }
  if (geneInputType == "hierCluster") {
    return;
  }
  const td2 = tr.append("td").style("display", "block").style("padding", "5px 0px");
  const createNewGrpDiv = td2.append("div").append("label");
  const createBtn = createNewGrpDiv.append("button").html("Create New Group").property("disabled", true).on("click", () => {
    tip3.clear();
    setMenuBackBtn(tip3.d.append("div"), () => controlPanelBtn.click(), "Back");
    const name = nameInput.property("value");
    selectedGroup = {
      index: tg.length,
      name,
      label: name,
      lst: [],
      status: "new",
      mode: parent.state.termdbConfig.queries?.snvindel ? TermTypes.GENE_VARIANT : ""
    };
    triggerGenesetEdit(tip3.d.append("div"));
  });
  const nameInput = createNewGrpDiv.append("input").style("margin", "2px 5px").style("width", "210px").attr("placeholder", "Group Name").on("input", () => {
    createBtn.property("disabled", !nameInput.property("value"));
  }).on("keyup", (event) => {
    if (event.key == "Enter" && !createBtn.property("disabled")) {
      createBtn.node().click();
    }
  });
}
function setMenuBackBtn(holder, callback, label) {
  holder.attr("tabindex", 0).style("padding", "5px").style("text-decoration", "underline").style("cursor", "pointer").style("margin-bottom", "12px").html(`&#171; ${label}`).on("click", callback).on("keyup", (event) => {
    if (event.key == "Enter") event.target.click();
  });
}
function setTermGroupSelector(self2, holder, tg) {
  const firstGrpWithGeneTw = tg.find(
    (g) => g.lst.find((tw) => tw.term.type == TermTypes.GENE_VARIANT && g.type !== "hierCluster")
  );
  const groups = tg.map((g, index) => {
    return {
      index,
      name: g.name,
      type: g.type,
      lst: g.lst.filter((tw) => tw.term.type == TermTypes.GENE_VARIANT).map((tw) => ({ name: tw.term.name })),
      mode: self2.parent.state.termdbConfig.queries?.snvindel ? TermTypes.GENE_VARIANT : "",
      selected: g === firstGrpWithGeneTw
    };
  });
  const nonHierClusterGroups = groups.filter((g) => g.type != "hierCluster");
  const groupSelect = holder.append("select").style("width", "218px").style("margin", "2px 5px");
  for (const [i, group] of nonHierClusterGroups.entries()) {
    if (group.label) continue;
    if (group.name) group.label = group.name;
    else group.label = `Unlabeled group #${i + 1}`;
  }
  groupSelect.selectAll("option").data(nonHierClusterGroups).enter().append("option").property("selected", (grp) => grp.selected).attr("value", (d, i) => i).html((grp) => grp.label);
  return { nonHierClusterGroups, groupSelect };
}

// plots/matrix/matrix.controls.variables.ts
var tip2 = new Menu({ padding: "" });
function setVariablesBtn(self2, s) {
  self2.opts.holder.append("button").datum({
    label: s.controlLabels.Terms || `Variables`,
    //getCount: () => self.parent.termOrder.filter(t => t.tw.term.type != 'geneVariant').length.length,
    rows: [
      {
        label: `Row Group Label Max Length`,
        title: `Truncate the row group label if it exceeds this maximum number of characters`,
        type: "number",
        chartType: "matrix",
        settingsKey: "termGrpLabelMaxChars"
      },
      {
        label: `Row Label Max Length`,
        title: `Truncate the row label if it exceeds this maximum number of characters`,
        type: "number",
        chartType: "matrix",
        settingsKey: "rowlabelmaxchars"
      }
    ],
    customInputs: appendDictInputs
  }).html((d) => d.label).style("margin", "2px 0").on("click", (event, d) => self2.callback(event, d));
}
function appendDictInputs(self2, app, parent) {
  tip2.clear();
  if (!parent.selectedGroup) parent.selectedGroup = parent.chartType == "hierCluster" ? 1 : 0;
  app.tip.d.append("hr");
  addDictMenu(self2, app, parent, app.tip.d.append("div"));
}
async function addDictMenu(self2, app, parent, holder = void 0) {
  const termdb = await import("./app-AIIN4WDE.js");
  termdb.appInit({
    holder: holder || app.tip.d,
    vocabApi: self2.parent.app.vocabApi,
    focus: "off",
    state: {
      vocab: self2.parent.state.vocab,
      activeCohort: self2.parent.activeCohort,
      nav: {
        header_mode: "search_only"
      },
      tree: {
        usecase: { target: "matrix", detail: "termgroups" }
      }
    },
    tree: {
      submit_lst: (termlst) => {
        submitLst(self2, termlst);
        app.tip.hide();
      }
    },
    search: {
      focus: "off"
    }
  });
}
async function submitLst(self2, termlst) {
  const newterms = await Promise.all(
    termlst.map(async (_term) => {
      const term = structuredClone(_term);
      const tw = "id" in term ? { id: term.id, term } : { term };
      await fillTermWrapper(tw, self2.opts.app.vocabApi);
      return tw;
    })
  );
  const termgroups = structuredClone(self2.parent.config.termgroups);
  const i = termgroups.findIndex((g) => g.name == "Variables");
  if (i !== -1) {
    const grp = termgroups[i];
    grp.lst.push(...newterms);
    self2.parent.app.dispatch({
      type: "plot_nestedEdits",
      id: self2.parent.id,
      edits: [
        {
          nestedKeys: ["termgroups", i, "lst"],
          value: grp.lst
        }
      ]
    });
  } else {
    const grp = { name: "Variables", lst: newterms };
    termgroups.push(grp);
    self2.parent.app.dispatch({
      type: "plot_edit",
      id: self2.parent.id,
      config: { termgroups }
    });
  }
}

// plots/matrix/matrix.controls.dimensions.ts
function setDimensionsBtn(self2, s) {
  const l = s.controlLabels;
  self2.opts.holder.append("button").datum({
    label: "Cell Layout",
    tables: [
      {
        rows: [
          {
            label: "Grid",
            title: "Show grid lines, which creates borders around each matrix cells.  Note that grid lines are hidden when the auto-computed width <= 2, or when either the column and row spacing is set to 0.",
            type: "checkbox",
            boxLabel: "show",
            // v===true means property('checked') and convert to recognized 'rect' value for dispatch
            // otherwise, compared value to 'rect' to set the current value of the checkbox
            // note: the non-boolean showGrid values allow keeping the hidden value='pattern' option for benchmark tests
            processInput: (v) => v === true ? "rect" : v === "rect",
            chartType: "matrix",
            settingsKey: "showGrid",
            colspan: 2,
            align: "center"
            // for testing/benchmarking
            // type: 'radio',
            // options: [
            // 	{
            // 		label: 'hide',
            // 		value: ''
            // 	},
            // 	{
            // 		label: 'lines',
            // 		value: 'pattern' // needs debugging for when s.rowh or d.colw does not apply to all rows
            // 	},
            // 	{
            // 		label: 'rect',
            // 		value: 'rect'
            // 	}
            // ]
          },
          {
            label: "Outline Color",
            title: "Set a border color for the whole matrix",
            type: "color",
            chartType: "matrix",
            settingsKey: "outlineStroke",
            colspan: 2,
            align: "center"
            //getDisplayStyle: plot => self.parent.settings.matrix.showGrid ? '' : 'none'
          },
          {
            label: "Beam Color",
            title: "Set a color for the beam highlighter",
            type: "color",
            chartType: "matrix",
            settingsKey: "beamStroke",
            colspan: 2,
            align: "center"
            //getDisplayStyle: plot => self.parent.settings.matrix.showGrid ? '' : 'none'
          },
          {
            label: "Grid Line Color",
            title: "Set the grid color, equivalent to applying the same border color for each matrix cell",
            type: "color",
            chartType: "matrix",
            settingsKey: "gridStroke",
            colspan: 2,
            align: "center"
            //getDisplayStyle: plot => self.parent.settings.matrix.showGrid ? '' : 'none'
          },
          {
            label: "Background Color",
            title: `Set the background color when there are no alterations or annotation data for a ${l.sample}`,
            type: "color",
            chartType: "matrix",
            settingsKey: "cellbg",
            colspan: 2,
            align: "center"
          },
          {
            label: `Use Canvas If # ${l.sample} Exceeds`,
            title: `Switch from SVG to canvas rendering when the number of ${l.samples} exceeds this number`,
            type: "number",
            chartType: "matrix",
            settingsKey: "svgCanvasSwitch",
            colspan: 2,
            align: "center",
            width: 60,
            min: 0,
            max: 1e4,
            step: 1
          },
          {
            label: "Canvas Min. Pixel Width",
            title: "Set a minimum pixel width for a matrix cell when using canvas, may affect the perceived sharpness of the canvas image",
            type: "checkbox",
            boxLabel: "apply",
            chartType: "matrix",
            settingsKey: "useMinPixelWidth",
            colspan: 2,
            align: "center",
            getDisplayStyle: () => self2.parent.settings.matrix.useCanvas ? "" : "none"
          }
        ]
      },
      {
        header: ["Cells", "Columns", "Rows"],
        rows: [
          {
            label: "Row Height",
            title: "Set the height of a matrix row",
            type: "number",
            width: 50,
            align: "center",
            chartType: "matrix",
            inputs: [{ label: "N/A" }, { settingsKey: "rowh", min: 8, max: 30, step: 1 }],
            getDisplayStyle(plot) {
              return plot.chartType == "hierCluster" ? "none" : "table-row";
            }
          },
          {
            label: "Min Col. Width",
            title: "Set the minimum width of the auto-computed matrix column width",
            type: "number",
            width: 50,
            align: "center",
            chartType: "matrix",
            inputs: [{ settingsKey: "colwMin", min: 0.1, max: 16, step: 0.2 }, { label: "N/A" }]
          },
          {
            label: "Max Col. Width",
            title: "Set the maximum width of the auto-computed matrix column width",
            type: "number",
            width: 50,
            align: "center",
            chartType: "matrix",
            inputs: [{ settingsKey: "colwMax", min: 1, max: 24, step: 0.2 }, { label: "N/A" }]
          },
          {
            label: "Spacing",
            title: "Set the column spacing. Note that this will be set to 0 when the auto-computed width < 2.",
            type: "number",
            width: 50,
            align: "center",
            chartType: "matrix",
            inputs: [
              { settingsKey: "colspace", min: 0, max: 20, step: 1 },
              { settingsKey: "rowspace", min: 0, max: 20, step: 1 }
            ],
            getDisplayStyle(plot) {
              return plot.chartType == "hierCluster" ? "none" : "table-row";
            }
          },
          {
            label: "Group spacing",
            title: "Set the spacing between column and row groups.",
            type: "number",
            width: 50,
            align: "center",
            chartType: "matrix",
            inputs: [
              self2.parent.chartType == "hierCluster" ? { label: "N/A" } : { settingsKey: "colgspace", min: 0, max: 20, step: 1 },
              { settingsKey: "rowgspace", min: 0, max: 20, step: 1 }
            ]
          }
        ]
      },
      {
        header: ["Labels", "Columns", "Rows"],
        rows: [
          {
            label: "Offset",
            title: "Set the gap between the label text and matrix edge",
            type: "number",
            width: 50,
            align: "center",
            chartType: "matrix",
            inputs: [
              { settingsKey: "collabelgap", min: 0, max: 20, step: 1 },
              { settingsKey: "rowlabelgap", min: 0, max: 20, step: 1 }
            ]
          },
          {
            label: "Spacing",
            title: "Set the gap between labels",
            type: "number",
            width: 50,
            align: "center",
            chartType: "matrix",
            inputs: [
              { settingsKey: "collabelpad", min: 0, max: 20, step: 1 },
              { settingsKey: "rowlabelpad", min: 0, max: 20, step: 1 }
            ]
          },
          {
            label: "Min font size",
            title: "Set the minimum auto-computed font size for labels. Note that labels will be hidden if the auto-computed values falls below this minimum.",
            type: "number",
            width: 50,
            align: "center",
            colspan: 2,
            chartType: "matrix",
            settingsKey: "minLabelFontSize",
            min: 0,
            max: 24,
            step: 0.1
          },
          {
            label: "Max font size",
            title: "Set the maximum auto-computed font size for labels",
            type: "number",
            width: 50,
            align: "center",
            colspan: 2,
            chartType: "matrix",
            settingsKey: "maxLabelFontSize",
            min: 0,
            max: 24,
            step: 0.1
          },
          {
            label: "Group label<br/>position",
            title: "Set which side of the matrix to display group labels",
            type: "radio",
            width: 50,
            chartType: "matrix",
            labelDisplay: "block",
            getDisplayStyle(plot) {
              return plot.chartType == "hierCluster" ? "none" : "table-row";
            },
            inputs: [
              {
                settingsKey: "collabelpos",
                // switched since settings.collabelpos refers to the individual column label, not group
                options: [
                  { label: "Top", value: "bottom", title: `Display ${l.sample} group labels at the bottom` },
                  { label: "Bottom", value: "top", title: `Display ${l.sample} group labels on top` }
                ]
              },
              {
                settingsKey: "rowlabelpos",
                // switched since settings.rowlabelpos refers to the individual column label, not group
                options: [
                  {
                    label: "Left",
                    value: "right",
                    title: `Display gene or variable group labels on the left side`
                  },
                  {
                    label: "Right",
                    value: "left",
                    title: `Display gene or variable group labels on the right side`
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }).html((d) => d.label).style("margin", "2px 0").on("click", (event, d) => self2.callback(event, d));
}

// plots/matrix/matrix.controls.legend.ts
function setLegendBtn(self2) {
  self2.opts.holder.append("button").style("margin", "2px 0").datum({
    label: "Legend Layout",
    rows: [
      //ontop: false,
      {
        label: "Font Size",
        title: "Set the font size for the legend text",
        type: "number",
        chartType: "legend",
        settingsKey: "fontsize"
      },
      {
        label: "Line Height",
        title: "Set the line height for a legend group",
        type: "number",
        chartType: "legend",
        settingsKey: "lineh"
      },
      {
        label: "Icon Height",
        title: "Set the icon height for a legend item",
        type: "number",
        chartType: "legend",
        settingsKey: "iconh"
      },
      {
        label: "Icon Width",
        title: "Set the icon width for a legend item",
        type: "number",
        chartType: "legend",
        settingsKey: "iconw"
      },
      /*{
      	label: 'Bottom margin',
      	type: 'number',
      	chartType: 'legend',
      	settingsKey: 'padbtm'
      },*/
      {
        label: "Item Left Pad",
        title: "Set a left margin for each legend item",
        type: "number",
        chartType: "legend",
        settingsKey: "padx"
      },
      {
        label: "Left Margin",
        title: "Set a left margin for the whole legend",
        type: "number",
        chartType: "legend",
        settingsKey: "padleft"
      },
      {
        label: "Left Indent",
        title: `Set a left margin for the first legend item in each group, and should be set to the length of the longest group label. The left indent will align the legend group label text to the right.`,
        type: "number",
        chartType: "legend",
        settingsKey: "hangleft"
      },
      {
        label: "Item Layout",
        title: "Option to separate each legend item into a new line, instead of a horizontal layout in the same line.",
        type: "checkbox",
        chartType: "legend",
        settingsKey: "linesep",
        boxLabel: "Line separated"
      }
    ]
  }).html((d) => d.label).style("margin", "2px 0").on("click", (event, d) => self2.callback(event, d));
}

// plots/matrix/matrix.controls.mutations.ts
function setMutationBtn(self2) {
  self2.opts.holder.append("button").style("margin", "2px 0").datum({
    label: "Mutation",
    updateBtn: (btn) => {
      const s = self2.parent.config.settings.matrix;
      btn.style("text-decoration", s.allMatrixMutationHidden ? "line-through" : "").style("text-decoration-thickness", s.allMatrixMutationHidden ? "2px" : "");
    },
    rows: [
      {
        title: `Show mutation options`,
        type: "radio",
        chartType: "matrix",
        settingsKey: "showMatrixMutation",
        options: [
          { label: "Show all mutations", value: "all" },
          { label: `Show only truncating mutations`, value: "onlyTruncating" },
          { label: `Show only protein-changing mutations`, value: "onlyPC" },
          { label: `Do not show mutations`, value: "none" },
          { label: `Show selected mutation`, value: "bySelection" }
        ],
        labelDisplay: "block",
        getDisplayStyle(plot) {
          return plot.chartType == "hierCluster" ? "none" : "table-row";
        },
        callback: self2.parent.mutationControlCallback
      }
    ],
    customInputs: generateMutationItems
  }).html((d) => d.label).style("margin", "2px 0").on("click", (event, d) => self2.callback(event, d));
}
function generateMutationItems(self2, app, parent, table) {
  table.attr("class", null);
  const m = parent.config.settings.matrix;
  const cnvLegendGrp = parent.legendData.find((l) => l.dt?.includes(dtcnv));
  if (m.showMatrixMutation !== "none" && (m.allMatrixCNVHidden || !cnvLegendGrp || cnvLegendGrp.crossedOut || !cnvLegendGrp.items.find((i) => !i.greyedOut && !i.crossedOut))) {
    table.select("input[type='radio'][value='none']").property("disabled", true);
    table.select("input[type='radio'][value='none'] + span").style("opacity", "0.5").on("mouseup", null);
  }
  if (m.addMutationCNVButtons && parent.chartType !== "hierCluster" && m.showMatrixMutation == "bySelection")
    parent.mutationControlCallback("bySelection");
}

// plots/matrix/matrix.controls.cnv.ts
function setCNVBtn(self2) {
  self2.opts.holder.append("button").style("margin", "2px 0").datum({
    label: "CNV",
    updateBtn: (btn) => {
      const s = self2.parent.config.settings.matrix;
      const notRendered = s.allMatrixCNVHidden;
      btn.style("text-decoration", notRendered ? "line-through" : "").style("text-decoration-thickness", notRendered ? "2px" : "");
    },
    rows: [
      {
        title: `Show CNV options`,
        type: "radio",
        chartType: "matrix",
        settingsKey: "showMatrixCNV",
        options: [
          { label: "Show all CNV", value: "all" },
          { label: `Do not show CNV`, value: "none" },
          { label: `Show selected CNV`, value: "bySelection" }
        ],
        labelDisplay: "block",
        getDisplayStyle(plot) {
          return plot.chartType == "hierCluster" ? "none" : "table-row";
        },
        callback: self2.parent.CNVControlCallback
      }
    ],
    customInputs: generateCNVItems
  }).html((d) => d.label).style("margin", "2px 0").on("click", (event, d) => self2.callback(event, d));
}
function generateCNVItems(self2, app, parent, table) {
  table.attr("class", null);
  const m = parent.config.settings.matrix;
  const mutationLegendGrp = parent.legendData.find((l) => l.dt?.includes(dtsnvindel));
  if (m.showMatrixCNV !== "none" && (m.allMatrixMutationHidden || !mutationLegendGrp || mutationLegendGrp.crossedOut || !mutationLegendGrp.items.find((i) => !i.greyedOut && !i.crossedOut))) {
    table.select("input[type='radio'][value='none']").property("disabled", true);
    table.select("input[type='radio'][value='none'] + span").style("opacity", "0.5").on("mouseup", null);
  }
  if (m.addMutationCNVButtons && parent.chartType !== "hierCluster" && m.showMatrixCNV == "bySelection")
    parent.CNVControlCallback("bySelection");
}

// plots/matrix/matrix.controls.download.ts
function setDownloadBtn(self2) {
  self2.opts.holder.append("button").style("margin", "2px 0").text("Download").on("focus", () => self2.parent.app.tip.hide()).on("click.sjpp-matrix-download", (event) => {
    const p = self2.parent;
    if (!p.dom.downloadMenu) p.dom.downloadMenu = new Menu({ padding: "" });
    const downloadMenu = p.dom.downloadMenu.clear();
    const div = downloadMenu.d.append("div");
    div.append("div").attr("class", "sja_menuoption sja_sharp_border").text(`SVG image`).on("click.sjpp-matrix-download", () => {
      to_svg(self2.opts.getSvg(), "matrix", { apply_dom_styles: true });
      p.dom.downloadMenu.destroy();
    });
    div.append("div").attr("class", "sja_menuoption sja_sharp_border").text(`TSV data`).on("click.sjpp-matrix-download", () => {
      const lst = p.data.lst;
      const allTerms = p.termOrder.map((t) => t.tw);
      const assayAvailability = p.state.termdbConfig.assayAvailability;
      const controlLabels = p.settings.matrix.controlLabels;
      if (p.config.divideBy?.id && !allTerms.find((a2) => a2.id == p.config.divideBy.id)) {
        allTerms.push(p.config.divideBy);
      }
      const activeSamples = [];
      for (const d of lst) {
        for (const tw of allTerms) {
          if (tw.$id in d) {
            activeSamples.push(d);
            break;
          }
        }
      }
      const header = [controlLabels.Sample];
      for (const tw of allTerms) header.push(tw.term.name);
      const rows = [header];
      for (const sample of activeSamples) {
        const row = [sample._ref_.label];
        for (const tw of allTerms) {
          if (!sample[tw.$id]) {
            row.push("");
          } else {
            if (tw.term.type == "geneVariant") {
              const allVariant = [];
              for (const v of sample[tw.$id].renderedValues) {
                const hasAssayAvailability = assayAvailability?.byDt?.[parseInt(v.dt)];
                if (v.dt == dtsnvindel) {
                  allVariant.push(
                    (v.origin ? `${v.origin} ` : "") + (hasAssayAvailability ? `${dt2label[v.dt]}:` : "") + `${mclass[v.class]?.label}` + (v.mname ? `,${v.mname}` : "")
                  );
                } else if (v.dt == dtcnv) {
                  const cnvValue = v.value ? `${hasAssayAvailability ? "" : "CNV:"}${v.value}` : v.class == "CNV_amp" ? "CNV gain" : v.class == "CNV_loss" ? "CNV loss" : v.class == "CNV_homozygous_deletion" ? "CNV homozygous deletion" : v.class == "CNV_amplification" ? "CNV amplification" : v.class == "CNV_loh" ? "CNV loss of heterozygosity" : mclass[v.class]?.label;
                  allVariant.push(
                    (v.origin ? `${v.origin} ` : "") + (hasAssayAvailability ? `${dt2label[v.dt]}:` : "") + cnvValue
                  );
                } else if (v.dt == dtfusionrna || v.dt == dtsv) {
                  allVariant.push(
                    (v.origin ? `${v.origin} ` : "") + (hasAssayAvailability ? `${dt2label[v.dt]}:` : "") + `${mclass[v.class]?.label}` + (v.gene && v.mname ? `(${v.gene}::${v.mname})` : "")
                  );
                } else {
                  allVariant.push(`DO NOT SUPPORT dt='${v.dt}'`);
                }
              }
              row.push(allVariant.join("|"));
            } else if (tw.term.type == TermTypes.GENE_EXPRESSION || tw.term.type == TermTypes.METABOLITE_INTENSITY || tw.term.type == TermTypes.PROTEOME_ABUNDANCE) {
              row.push(sample[tw.$id]?.renderedValues?.[0]?.value || "");
            } else {
              row.push(sample[tw.$id]?.renderedValues?.[0] || sample[tw.$id]?.value || "");
            }
          }
        }
        rows.push(row);
      }
      const matrix = rows.map((row) => row.join("	")).join("\n");
      const a = document.createElement("a");
      document.body.appendChild(a);
      a.addEventListener(
        "click",
        function() {
          const currentDate = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
          a.download = p.config.settings?.hierCluster?.termGroupName?.startsWith("Gene Expression") ? `GeneExpression.${currentDate}.tsv` : p.chartType == "hierCluster" ? `HierCluster.${currentDate}.tsv` : `${p.app.vocabApi.termdbConfig.matrix?.appName || "Matrix"}.${currentDate}.tsv`;
          a.href = URL.createObjectURL(new Blob([matrix], { type: "text/tab-separated-values" }));
          document.body.removeChild(a);
        },
        false
      );
      a.click();
      p.dom.downloadMenu.destroy();
    });
    downloadMenu.showunder(event.target);
  });
}

// plots/matrix/matrix.zoomPanScroll.ts
function setZoomInput(self2) {
  const holder = self2.opts.holder.append("div").style("display", "inline-block").style("margin-left", "50px");
  const s = self2.parent.settings.matrix || self2.parent.config.settings.matrix;
  self2.zoomApi = zoom({
    holder,
    title: "Zoom factor relative to the ideal column width, as computed for the number of columns versus available screen width",
    unit: "",
    width: "80px",
    settings: {
      min: 0.1,
      // will be determined once the auto-computed width is determined
      max: 1,
      // will be determined once the auto-computed width is determined
      value: 1,
      increment: s.zoomIncrement,
      step: s.zoomStep || 5
    },
    callback: (zoomLevel) => {
      const p = self2.parent;
      const c = p.getVisibleCenterCell(0);
      p.app.dispatch({
        type: "plot_edit",
        id: p.id,
        config: {
          settings: {
            matrix: {
              zoomLevel,
              zoomCenterPct: 0.5,
              zoomIndex: c.totalIndex,
              zoomGrpIndex: c.grpIndex
            }
          }
        }
      });
    },
    reset: () => {
      self2.parent.app.dispatch({
        type: "plot_edit",
        id: self2.parent.id,
        config: {
          settings: {
            matrix: {
              zoomLevel: 1,
              zoomCenterPct: 0
            }
          }
        }
      });
    }
  });
}
function setDragToggle(self2, opts = {}) {
  const defaults = {
    mouseMode: "select",
    activeBgColor: "rgb(255, 255, 255)"
  };
  opts.target.style("cursor", "default");
  const instance = {
    opts: Object.assign({}, defaults, opts),
    dom: {
      selectBtn: opts.holder.append("button").attr("aria-label", "Click the matrix to select data").style("display", "inline-block").style("width", "25px").style("height", "24.5px").style("background-color", defaults.activeBgColor).on("click", () => setMode("select")),
      grabBtn: opts.holder.append("button").attr("aria-label", "Click the matrix to drag and move").style("display", "inline-block").style("width", "25px").style("height", "24.5px").on("click", () => setMode("pan"))
    }
  };
  icons.arrowPointer(instance.dom.selectBtn, { width: 14, height: 14, transform: "translate(50,50)" });
  icons.grab(instance.dom.grabBtn, { width: 14, height: 14, transform: "translate(30,50)" });
  function setMode(m) {
    instance.opts.mouseMode = m;
    self2.parent.settings.matrix.mouseMode = m;
    opts.target.style("cursor", m == "select" ? "default" : "grab");
    instance.dom.selectBtn.style("background-color", m == "select" ? instance.opts.activeBgColor : "");
    instance.dom.grabBtn.style("background-color", m == "pan" ? instance.opts.activeBgColor : "");
  }
  self2.dragToggleApi = {
    update(s = {}) {
      Object.assign(instance.opts, s);
      setMode(instance.opts.mouseMode);
    },
    getSettings() {
      return {
        mouseMode: instance.opts.mouseMode
      };
    }
  };
}
function setSvgScroll(self2, state) {
  self2.svgScrollApi = svgScroll({
    holder: self2.parent.dom.scroll,
    height: state.config.settings.matrix.scrollHeight,
    callback: (dx, eventType) => {
      const p = self2.parent;
      const s = p.settings.matrix;
      const d = p.dimensions;
      if (eventType == "move") {
        p.dom.seriesesG.attr("transform", `translate(${d.xOffset + d.seriesXoffset - dx},${d.yOffset})`);
        p.clusterRenderer.translateElems(-dx, s, d);
        p.layout.top.attr.adjustBoxTransform(-dx);
        p.layout.btm.attr.adjustBoxTransform(-dx);
        if (p.dom.topDendrogram) {
          p.dom.topDendrogram.attr("transform", `translate(${p.topDendroX - dx},0)`);
        }
      } else if (eventType == "up") {
        const c = p.getVisibleCenterCell(-dx);
        p.app.dispatch({
          type: "plot_edit",
          id: p.id,
          config: {
            settings: {
              matrix: {
                zoomCenterPct: 0.5,
                zoomIndex: c.totalIndex,
                zoomGrpIndex: c.grpIndex
              }
            }
          }
        });
      }
    }
  });
}

// plots/matrix/matrix.controls.ts
var MatrixControls = class {
  constructor(opts, appState) {
    this.activeTab = "basic";
    this.type = "matrixControls";
    this.opts = opts;
    this.parent = opts.parent;
    this.overrides = {};
    this.opts.holder.style("margin", "10px 10px 20px 10px").style("white-space", "nowrap");
    const state = this.parent.getState(appState);
    const s = state.config.settings.matrix;
    if (this.parent.setClusteringBtn)
      this.parent.setClusteringBtn(this.opts.holder, (event, data) => this.callback(event, data));
    setSamplesBtn(this, s);
    if (state.termdbConfig?.allowedTermTypes?.includes(TermTypes.GENE_VARIANT) || state.termdbConfig.queries.snvindel || this.parent.chartType == "hierCluster" && this.parent.config.dataType == TermTypes.GENE_EXPRESSION) {
      setGenesBtn(this, s);
    }
    if (s.addMutationCNVButtons && this.parent.chartType !== "hierCluster") {
      setMutationBtn(this);
      setCNVBtn(this);
    }
    setVariablesBtn(this, s);
    setDimensionsBtn(this, s);
    setLegendBtn(this);
    setDownloadBtn(this);
    setZoomInput(this);
    setDragToggle(this, {
      holder: this.opts.holder.append("div").style("display", "inline-block"),
      target: this.parent.dom.seriesesG
    });
    setSvgScroll(this, state);
    this.keyboardNavHandler = async (event) => {
      if (event.target.tagName == "BUTTON") this.keyEventTarget = event.target;
      if (event.key == "Escape") {
        this.parent.app.tip.hide();
      } else if (event.key == "Enter" || event.key == "ArrowDown") {
        const elems = event.target.tagName == "BUTTON" ? this.parent.app.tip.d.node().querySelectorAll("input, select") : event.target.querySelectorAll("input, select");
        for (const elem of elems) {
          if (elem.checkVisibility?.() || !elem.checkVisibility && elem.getBoundingClientRect().height) {
            elem.focus();
            return false;
          }
        }
      } else if (event.key == "Tab" && event.shiftKey || event.key == "Backspace" || event.key == "ArrowUp") {
        this.keyEventTarget.focus();
        return false;
      }
    };
    this.btns = this.opts.holder.selectAll(":scope>button").filter((d) => d && d.label).on(`keyup.matrix-${this.parent.id}`, this.keyboardNavHandler);
  }
  main(overrides = {}) {
    this.overrides = overrides;
    this.parent.app.tip.hide();
    this.btns.text(
      (d2) => !d2.getCount || d2.showCount == "hide" ? d2.label : d2.showCount == "append" ? `${d2.label} (n=${d2.getCount()})` : `${d2.getCount()} ${d2.label}`
    ).each(function(d2) {
      if (d2.updateBtn) d2.updateBtn(select_default(this));
    });
    const s = this.parent.settings.matrix || this.parent.config.settings.matrix;
    const min = this.parent.computedSettings.zoomMin;
    const max = this.parent.computedSettings.zoomMax;
    const increment = Math.max(0.01, Number((min / max).toFixed(2)));
    const d = this.parent.dimensions;
    if (this.zoomApi)
      this.zoomApi.update({
        value: s.zoomLevel.toFixed(2),
        min: min.toFixed(2),
        max: max.toFixed(2),
        increment,
        step: s.zoomStep || 1
      });
    if (this.svgScrollApi && d) {
      this.svgScrollApi.update({
        x: d.xOffset,
        y: d.yOffset - s.scrollHeight,
        totalWidth: d.zoomedMainW,
        visibleWidth: d.mainw,
        zoomCenter: s.zoomCenterPct * d.mainw - d.seriesXoffset
      });
    }
    if (this.dragToggleApi) {
      this.dragToggleApi.update(s.mouseMode ? { mouseMode: s.mouseMode } : {});
    }
  }
  getSettings() {
    return {
      mouseMode: this.dragToggleApi.getSettings().mouseMode
    };
  }
  async callback(event, d) {
    const app = this.opts.app;
    const parent = this.opts.parent;
    const tables = d.tables || [d];
    event.target.focus();
    app.tip.clear();
    const table = app.tip.d.append("table").attr("class", "sjpp-controls-table");
    for (const t of tables) {
      if (t.header) {
        table.append("tr").selectAll("th").data(t.header).enter().append("th").html((d2) => d2);
      }
      for (const inputConfig of t.rows) {
        const holder = table.append("tr");
        const input = await initByInput[inputConfig.type](
          Object.assign(
            {},
            {
              holder,
              app,
              dispatch: (action) => app.dispatch(action),
              id: parent.id,
              debug: this.opts.debug,
              parent
            },
            inputConfig
          )
        );
        input.main(parent.config);
      }
      if (t.customInputs) t.customInputs(this, app, parent, table);
      table.selectAll("select, input, button").attr("tabindex", 0).on("keydown", this.keyboardNavHandler);
    }
    app.tip.showunder(event.target);
  }
};

// plots/matrix/matrix.xtw.ts
var addons;
async function getTermGroups(termgroups, app) {
  const termGroups = structuredClone(termgroups);
  if (!addons)
    addons = {
      QualTWValues: discreteAddons,
      QualTWPredefinedGS: discreteAddons,
      QualTWCustomGS: discreteAddons,
      NumTWRegularBin: discreteAddons,
      NumTWCustomBin: discreteAddons,
      NumTWCont: continuousAddons,
      TermCollectionTWCont: TermCollectionContAddons
    };
  const opts = {
    vocabApi: app.vocabApi,
    addons
  };
  for (const [origIndex, tG] of termGroups.entries()) {
    tG.origIndex = origIndex;
    if (tG.type == "hierCluster") continue;
    const xtwlst = [];
    for (const tw of tG.lst) {
      const inputTw = tw.getTw?.() || tw;
      xtwlst.push(
        inputTw.type in opts.addons && routedTermTypes.has(inputTw.term.type) ? await TwRouter.init(inputTw, opts) : inputTw
      );
    }
    tG.lst = xtwlst;
  }
  return termGroups;
}
var discreteAddons = {
  setCellProps: {
    value: function(cell, anno, value, s, t, self2, width, height, dx, dy, i) {
      const tw = this.getTw();
      const key = anno.key;
      const values = tw.term.values || {};
      cell.label = "label" in anno ? anno.label : values[key]?.label ? values[key].label : key;
      const tw$id = tw.$id;
      cell.fill = self2.config.settings.matrix.twSpecificSettings?.[tw$id]?.[key]?.color || anno.color || values[anno.key]?.color || self2.data.refs.byTermId?.[tw$id]?.bins?.find((b) => anno.key == b.name)?.color;
      cell.order = t.ref.bins ? t.ref.bins.findIndex((bin) => bin.name == key) : 0;
      cell.x = cell.totalIndex * dx + cell.grpIndex * s.colgspace;
      cell.y = height * i;
      const group = tw.legend?.group || tw$id;
      return { ref: t.ref, group, value: key, entry: { key, label: cell.label, fill: cell.fill } };
    }
  }
};
var continuousAddons = {
  setCellProps: {
    value: function(cell, anno, value, s, t, self2, width, height, dx, dy, i) {
      const tw = this.getTw();
      const key = anno.key;
      const values = tw.term.values || {};
      cell.label = "label" in anno ? anno.label : values[key]?.label ? values[key].label : key;
      cell.fill = anno.color || values[anno.key]?.color;
      const tw$id = tw.$id;
      const twSpecificSettings = self2.config.settings.matrix.twSpecificSettings;
      if (!twSpecificSettings[tw$id]) twSpecificSettings[tw$id] = {};
      const twSettings = twSpecificSettings[tw$id];
      if (!twSettings.contBarH) twSettings.contBarH = s.barh;
      if (!("gap" in twSettings)) twSettings.contBarGap = 4;
      const specialValue = tw.term.values?.[cell.key];
      if (specialValue?.uncomputable) {
        cell.x = cell.totalIndex * dx + cell.grpIndex * s.colgspace;
        cell.y = height * i;
        cell.height = twSettings.contBarH;
        cell.fill = "transparent";
        cell.label = specialValue.label;
        const group = tw.legend?.group || tw.$id;
        return {
          ref: t.ref,
          group,
          value: specialValue.label || specialValue.key,
          entry: { key, label: cell.label, fill: cell.fill }
        };
      }
      cell.fill = self2.config.settings.matrix.twSpecificSettings?.[tw$id]?.contBarColor || "#555";
      if (s.transpose) {
        cell.height = t.scale(cell.key);
        cell.x = twSettings.contBarGap;
      } else {
        const vc = cell.term.valueConversion;
        let renderV = vc ? cell.key * vc.scaleFactor : cell.key;
        if (this.q.convert2ZScore) {
          renderV = (renderV - t.mean) / t.std;
          cell.fill = renderV > 0 ? "#FF6666" : "#6666FF";
          cell.zscoreLabel = ` (Z-score: ${renderV.toFixed(2)})`;
        }
        cell.label = "label" in anno ? anno.label : values[key]?.label ? values[key].label : this.term.unit ? `${cell.key.toFixed(2)} ${this.term.unit}` : cell.key.toFixed(2);
        cell.height = renderV >= 0 ? t.scales.pos(renderV) : t.scales.neg(renderV);
        cell.x = cell.totalIndex * dx + cell.grpIndex * s.colgspace;
        cell.y = renderV >= 0 ? t.counts.posMaxHt + twSettings.contBarGap - cell.height : t.counts.posMaxHt + twSettings.contBarGap;
        cell.convertedValueLabel = !vc ? "" : convertUnits(cell.key, vc.fromUnit, vc.toUnit, vc.scaleFactor);
      }
    }
  }
};
var TermCollectionContAddons = {
  setCellProps: {
    value: function(cell, anno, value, s, t, self2, width, height, dx, _dy, _i) {
      const tw = this.getTw();
      const twSpecificSettings = self2.config.settings.matrix.twSpecificSettings;
      if (!twSpecificSettings[tw.$id]) twSpecificSettings[tw.$id] = {};
      const twSettings = twSpecificSettings[tw.$id];
      if (!twSettings.contBarH) twSettings.contBarH = s.barh;
      if (!("gap" in twSettings)) twSettings.contBarGap = 4;
      const isNegative = value.value < 0;
      if (isNegative) {
        cell.height = t.scales.neg ? t.scales.neg(value.value) - t.scales.neg(0) : 0;
        cell.x = cell.totalIndex * dx + cell.grpIndex * s.colgspace;
        const cumulativeHeight = t.scales.neg ? t.scales.neg(value.pre_val_sum) - t.scales.neg(0) : 0;
        cell.y = t.counts.posMaxHt + twSettings.contBarGap + (t.scales.neg ? t.scales.neg(0) : 0) + cumulativeHeight;
      } else {
        cell.height = t.scales.pos(value.value) - t.scales.pos(0);
        cell.x = cell.totalIndex * dx + cell.grpIndex * s.colgspace;
        const cumulativeHeight = t.scales.pos(value.pre_val_sum) - t.scales.pos(0);
        cell.y = t.counts.posMaxHt + twSettings.contBarGap - t.scales.pos(0) - cumulativeHeight - cell.height;
      }
      cell.label = value.label;
      cell.fill = twSettings[value.label]?.color || value.color || tw.term.propsByTermId?.[value.label]?.color;
      cell.value = value.value;
      return {
        ref: t.ref,
        group: tw.$id,
        value: value.label,
        order: -1,
        entry: { key: value.label, label: value.label, fill: cell.fill }
      };
    }
  }
};

// plots/matrix/matrix.js
var Matrix = class _Matrix extends PlotBase {
  static type = "matrix";
  configTermKeys = ["termgroups.lst", "divideBy"];
  constructor(opts) {
    super(opts);
    this.type = _Matrix.type;
    this.holderTitle = "Sample Matrix";
    this.optionalFeatures = JSON.parse(sessionStorage.getItem("optionalFeatures") || `{}`)?.matrix || [];
    setInteractivity(this);
    setRenderers(this);
  }
  async init(appState) {
    const opts = this.opts;
    if (opts.reactsTo) this.reactsTo = opts.reactsTo;
    this.setDom = setMatrixDom;
    this.setDom(opts);
    this.config = appState.plots.find((p) => p.id === this.id);
    this.settings = Object.assign({}, this.config.settings.matrix);
    this.computed = {};
    if (this.dom.header) this.dom.header.html(this.config.preBuiltPlotTitle || this.holderTitle);
    this.setControls(appState);
    this.clusterRenderer = new MatrixCluster({ holder: this.dom.cluster, app: this.app, parent: this });
    this.legendRenderer = svgLegend({
      holder: this.dom.legendG,
      rectFillFxn: (d) => d.color,
      iconStroke: "#aaa",
      handlers: {
        legend: {
          click: this.legendClick
        }
      },
      settings: {
        isExcludedAttr: "isExcluded"
      },
      note: "CLICK A ROW LABEL OR ITEM TO APPLY FILTERING"
    });
    this.customTipApi = this.dom.tip.getCustomApi({
      d: this.dom.menubody,
      clear: (event) => {
        if (event?.target) this.dom.menutop.style("display", "none");
        this.dom.menubody.selectAll("*").remove();
        return this.customTipApi;
      },
      show: () => {
        this.dom.menubody.style("display", "block");
      },
      hide: () => {
      }
    });
    this.setPill(appState);
    const commonKeys = { mclass, dt2label, morigin };
    for (const k in commonKeys) {
      const v = commonKeys[k];
      this[k] = copyMerge({}, v, appState.termdbConfig[k] || {}, appState.termdbConfig.matrix?.[k] || {});
    }
  }
  setControls(appState) {
    this.controlsRenderer = new MatrixControls(
      {
        app: this.app,
        id: this.id,
        parent: this,
        holder: this.dom.controls,
        getSvg: () => this.dom.svg.node()
      },
      appState
    );
  }
  // reactsTo(action) {
  // 	// note: a parent app or 'plot' component is expected to already have
  // 	// a comprehensive reactsTo() call to filter the actions for this component,
  // 	// so only farther selective action filters should be applied here as needed
  // 	return true
  // }
  getState(appState) {
    const config = appState.plots.find((p) => p.id === this.id);
    const filter0 = appState.termfilter.filter0;
    this.prevFilter0 = this.state?.filter0;
    const parentConfig = appState.plots.find((p) => p.id === this.parentId);
    const termfilter = getCombinedTermFilter(appState, config.filter || parentConfig?.filter);
    return {
      isVisible: true,
      config,
      filter: termfilter.filter,
      filter0,
      // read-only, invisible filter currently only used for gdc dataset
      hasVerifiedToken: this.app.vocabApi.hasVerifiedToken(),
      tokenVerificationMessage: this.app.vocabApi.tokenVerificationMessage,
      vocab: appState.vocab,
      termdbConfig: appState.termdbConfig,
      clusterMethod: config.settings.hierCluster?.clusterMethod,
      distanceMethod: config.settings.hierCluster?.distanceMethod,
      clusterSamples: config.settings.hierCluster?.clusterSamples,
      clusterRows: config.settings.hierCluster?.clusterRows,
      zScoreTransformation: config.settings.hierCluster?.zScoreTransformation,
      nav: appState.nav,
      groups: rebaseGroupFilter(appState)
    };
  }
  async main() {
    try {
      this.config = await this.getMutableConfig();
      if (this.mayRequireToken()) return;
      const termGroups = await getTermGroups(this.config.termgroups, this.app);
      const prevTranspose = this.settings.transpose;
      Object.assign(this.settings, structuredClone(this.config.settings), this.controlsRenderer.getSettings());
      this.dom.loadingDiv.selectAll("*").remove();
      this.dom.loadingDiv.html("").style("display", "").style("position", "relative").style("left", "45%");
      this.dom.svg.style("opacity", 0.1).style("pointer-events", "none");
      delete this.clickedClusterIds;
      delete this.clickedLeftClusterIds;
      try {
        setComputedConfig(this.config);
        const promises = [];
        if (this.setHierClusterData) promises.push(this.setHierClusterData());
        promises.push(this.setData());
        this.dom.loadingDiv.html("Processing data ...");
        await Promise.all(promises);
        const warnings = this.data.warnings.join("\n");
        this.dom.warningDiv.style("display", warnings.length ? "" : "none").html(warnings);
        this.applyLegendValueFilter();
        if (this.combineData) this.combineData();
        this.app.save({ type: "plot_edit", id: this.id, config: this.config });
      } catch (e) {
        if (e == "no data") {
          this.showNoMatchingDataMessage();
          return;
        } else if (this.app.isAbortError(e)) {
          return;
        } else {
          this.dom.svg.style("display", "none");
          throw e;
        }
      }
      this.termGroups = termGroups;
      this.dom.loadingDiv.html("Updating ...").style("display", "");
      this.termOrder = this.getTermOrder(this.data);
      this.sampleGroups = this.getSampleGroups(this.hierClusterSamples || this.data);
      this.sampleOrder = this.getSampleOrder(this.data);
      this.setLayout();
      if (this.setHierColorScale) this.setHierColorScale(this.hierClusterData.clustering);
      if (!this.sampleOrder?.length) {
        this.showNoMatchingDataMessage();
      }
      this.controlsRenderer.main();
      this.serieses = this.getSerieses(this.data);
      this.dom.loadingDiv.html("Rendering ...");
      if (this.plotDendrogramHclust) this.plotDendrogramHclust();
      this.render();
      this.mayDisplayCohortMessage();
      this.dom.svg.style("display", "").style("opacity", 1).style("pointer-events", "");
      const [xGrps, yGrps] = !this.settings.matrix.transpose ? ["sampleGrps", "termGrps"] : ["termGrps", "sampleGrps"];
      const d = this.dimensions;
      this.clusterRenderer.main({
        settings: this.settings.matrix,
        xGrps: this[xGrps],
        yGrps: this[yGrps],
        dimensions: d
      });
      this.legendRenderer(this.legendData, {
        settings: Object.assign({}, this.settings.legend, {
          svgw: Math.max(400, d.mainw + d.xOffset - this.settings.matrix.margin.right),
          svgh: d.mainh + d.yOffset,
          dimensions: d,
          padleft: this.settings.legend.padleft
          //+ d.xOffset
        })
      });
      await this.adjustSvgDimensions(prevTranspose);
      this.controlsRenderer.main();
      if (this.data.removedHierClusterTerms) {
        for (const r of this.data.removedHierClusterTerms) {
          sayerror(this.dom.errorDiv, r.text + ": " + r.lst.join(", "));
        }
      }
    } catch (e) {
      const message = this.app.vocabApi.tokenVerificationMessage;
      this.mayRequireToken(message);
      if (!message) {
        this.app.tip.hide();
        this.dom.loadingDiv.style("display", "none");
        throw e;
      }
    }
    this.resetInteractions();
  }
  showNoMatchingDataMessage() {
    this.forcedSampleCount = 0;
    this.dom.svg.style("opacity", 1e-3).style("display", "none");
    if (this.termOrder && this.dimensions) this.controlsRenderer.main({ sampleCount: 0 });
    this.dom.loadingDiv.html("");
    const div = this.dom.loadingDiv.append("div").style("display", "inline-block").style("text-align", "center").style("position", "relative").style("left", "-150px");
    div.append("div").style("margin", "5px 10px").html("No matching cohort sample data for the current gene list.");
    if (this.settings.matrix.showHints?.includes("genesetEdit")) {
      const div1 = div.append("div").style("margin", "5px 10px");
      div1.append("span").html("You may change the selected cohort,");
      if (this.config.legendGrpFilter?.lst.length || this.config.legendValueFilter?.lst.length) {
        const cnvBtn = this.controlsRenderer.btns.filter((d) => d.label == "CNV")?.node();
        if (cnvBtn) {
          div1.append("br");
          div1.append("span").html("show hidden ");
          div1.append("span").html("CNV").style("cursor", "pointer").style("text-decoration", "underline").on("click", () => {
            cnvBtn.click();
          });
        }
        const mutationBtn = this.controlsRenderer.btns.filter((d) => d.label == "Mutation")?.node();
        if (cnvBtn && mutationBtn) div1.append("span").html(" or ");
        if (mutationBtn) {
          div1.append("span").style("cursor", "pointer").style("text-decoration", "underline").html("Mutation").on("click", () => {
            mutationBtn.click();
          });
        }
        if (cnvBtn || mutationBtn) div1.append("span").html(" data,");
      }
      div1.append("br");
      div1.append("span").html("or edit the gene list from the ");
      div1.append("span").style("cursor", "pointer").style("text-decoration", "underline").html("Gene Set Edit Group menu.").on("click", () => {
        const GenesBtn = this.controlsRenderer.btns.filter((d) => d.label == "Genes")?.node().click();
        const i = setInterval(() => {
          const editBtn = this.app.tip.d.selectAll("button").filter(function() {
            return this.innerHTML == "Edit Group";
          }).node();
          if (editBtn) {
            editBtn.click();
            clearInterval(i);
          }
        }, 100);
      });
    }
    this.dom.svg.style("display", "none");
  }
  mayDisplayCohortMessage() {
    const msg = deepEqual(this.state.filter0, this.prevFilter0) ? "" : "The gene list is persisted across cohorts.";
    if (msg) {
      this.dom.loadingDiv.html("");
      const div = this.dom.loadingDiv.append("div").style("display", "inline-block").style("text-align", "center").style("position", "relative").style("left", "-150px");
      div.append("div").html(msg);
      if (this.settings.matrix.showHints?.includes("genesetEdit")) {
        const div1 = div.append("div");
        div1.append("span").html(" You may edit the gene list from the ");
        div1.append("span").style("cursor", "pointer").style("text-decoration", "underline").html("Gene Set Edit Group menu.").on("click", () => {
          const GenesBtn = this.controlsRenderer.btns.filter((d) => d.label == "Genes")?.node().click();
          const i = setInterval(() => {
            const editBtn = this.app.tip.d.selectAll("button").filter(function() {
              return this.innerHTML == "Edit Group";
            }).node();
            if (editBtn) {
              editBtn.click();
              clearInterval(i);
            }
          }, 100);
        });
      }
    }
    this.dom.loadingDiv.style("display", msg ? "" : "none");
  }
  sampleKey(s) {
    return s.row.sample;
  }
  sampleLabel(s) {
    return s.label || s.row._ref_.label || "";
  }
  sampleGrpKey(s) {
    return s.grp.name;
  }
  sampleGrpLabel(s) {
    return s.grp.label || s.grp.name || "";
  }
  termKey(t) {
    return t.tw.$id;
  }
  termLabel(t) {
    return t.label;
  }
  termGrpKey(t) {
    return t.grp.name;
  }
  termGrpLabel(t) {
    return t.grp.label || t.grp.name || [{ text: "\u22EE", dx: 3, cls: "sjpp-exclude-svg-download" }];
  }
  destroy() {
    select_default(window).on(`resize.sjpp-${self.id}`, null);
  }
};
for (const m of [matrix_data_exports, matrix_groups_exports, matrix_layout_exports, matrix_serieses_exports, matrix_legend_exports]) {
  for (const methodName in m) {
    Matrix.prototype[methodName] = m[methodName];
  }
}
var matrixInit = getCompInit(Matrix);
var componentInit = matrixInit;
function makeChartBtnMenu(holder, chartsInstance) {
  chartsInstance.dom.tip.clear();
  const menuDiv = holder.append("div");
  if (chartsInstance.state.termdbConfig.matrixplots) {
    for (const plot of chartsInstance.state.termdbConfig.matrixplots) {
      menuDiv.append("button").style("margin", "10px").style("padding", "10px 15px").style("border-radius", "20px").style("border-color", "#ededed").style("display", "inline-block").text(plot.name).on("click", async () => {
        chartsInstance.dom.tip.hide();
        const config = await chartsInstance.app.vocabApi.getMatrixByName(plot.name);
        config.preBuiltPlotTitle = plot.name;
        chartsInstance.app.dispatch({
          type: "plot_create",
          config
        });
      });
    }
  }
  const chart = {
    clickTo: chartsInstance.showTree_selectlst,
    chartType: "matrix",
    usecase: { target: "matrix", detail: "termgroups" },
    processSelection: (lst) => {
      return [
        {
          name: "",
          lst: lst.map((term) => {
            return { term };
          })
        }
      ];
    }
  };
  chartsInstance.showTree_selectlst(chart);
}

export {
  Matrix,
  matrixInit,
  componentInit,
  makeChartBtnMenu
};
//# sourceMappingURL=chunk-6A3IPDE2.js.map
