import {
  bigwigconfigpanel,
  bigwigfromtemplate
} from "./chunk-57RBC6IZ.js";
import {
  legend_newrow
} from "./chunk-UJKW42DI.js";
import "./chunk-V2OJLJSK.js";
import "./chunk-VGYTAYFK.js";
import {
  axisstyle,
  bwSetting,
  category2legend,
  font,
  make_table_2col,
  tkt
} from "./chunk-SA7APTJR.js";
import "./chunk-HJ6L54YS.js";
import "./chunk-LSEFWW72.js";
import "./chunk-SKREEF3H.js";
import {
  Menu
} from "./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 {
  dofetch3
} from "./chunk-7EMWHCVW.js";
import "./chunk-7IYJZZQI.js";
import "./chunk-M3J4MINX.js";
import "./chunk-PF4DSFDR.js";
import "./chunk-QH6W3NVF.js";
import "./chunk-NOEAT6CX.js";
import "./chunk-4UWS5Y3N.js";
import "./chunk-DD4R5P6W.js";
import "./chunk-JNITUVXP.js";
import {
  category10_default
} from "./chunk-KSGA62R2.js";
import {
  axisLeft,
  axisTop
} from "./chunk-LOZEKOES.js";
import "./chunk-TOU7EVFQ.js";
import {
  format,
  linear,
  ordinal
} from "./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 "./chunk-HFNDKYVF.js";

// src/block.tk.pgv.js
var genevaluexspace = 13;
var defaultbarcolor = "#668CFF";
var defaultbarwidth = 150;
var gvtkheaderyoff = -2;
function makeTk(tk, block) {
  const template = tk._template;
  delete tk._template;
  if (!template.tracks) throw ".tracks[] missing from " + tk.name + " track";
  if (template.tracks.length == 0) throw ".tracks[] length 0 from " + tk.name + " track";
  tk.tracks = [];
  const nameset = /* @__PURE__ */ new Set();
  for (const t0 of template.tracks) {
    const t = {};
    for (const k in t0) {
      t[k] = t0[k];
    }
    if (!t.name) throw "no name for member track of " + tk.name + ": " + JSON.stringify(t);
    if (nameset.has(t.name)) throw "duplicating member track name: " + t.name;
    nameset.add(t.name);
    if (!t.type) throw "no type for member track of " + tk.name + ": " + JSON.stringify(t);
    if (!t.file && !t.url) throw 'neither file or url given for member "' + t.name + '" of ' + tk.name;
    if (t.type == "bedj") {
    } else if (t.type == "bigwig") {
      bigwigfromtemplate(t, t0);
    } else {
      throw "invalid type of member track of " + tk.name + ": " + t.type;
    }
    t.toppad = t.toppad == void 0 ? 4 : t.toppad;
    t.bottompad = t.bottompad == void 0 ? 4 : t.bottompad;
    t.y = 0;
    tk.tracks.push(t);
  }
  tk.geneset = /* @__PURE__ */ new Set();
  if (template.genevaluetrack) {
    if (!template.genevaluetrack.file && template.genevaluetrack.url) throw "no .file or .url for genevaluetrack";
    tk.genevaluetrack = {
      file: template.genevaluetrack.file,
      url: template.genevaluetrack.url
    };
  }
  if (template.genevaluetklst) {
    if (!Array.isArray(template.genevaluetklst)) throw ".genevaluetklst should be an array";
    if (template.genevaluetklst.length == 0) throw "zero length of .genevaluetklst";
    tk.genevaluetklst = [];
    for (const gvtk of template.genevaluetklst) {
      if (!gvtk.name) throw "name missing for one genevalue track";
      if (!gvtk.file && !gvtk.url) throw "no file or url for genevalue track " + gvtk.name;
      const t = {};
      for (const k in gvtk) t[k] = gvtk[k];
      tk.genevaluetklst.push(t);
    }
  }
  if (template.bigwigsetting) {
    tk.bigwigsetting = {};
    if (template.bigwigsetting.scale) {
      if (template.bigwigsetting.scale.max) {
        if (!Number.isFinite(template.bigwigsetting.scale.max)) throw "invalid max value in bigwigsetting.scale";
        if (!Number.isFinite(template.bigwigsetting.scale.min))
          throw "invalid or missing min value in bigwigsetting.scale";
        if (template.bigwigsetting.scale.max <= template.bigwigsetting.scale.min)
          throw "max <= min in bigwigsetting.scale";
        tk.bigwigsetting.scale = { min: template.bigwigsetting.scale.min, max: template.bigwigsetting.scale.max };
      }
    }
    for (const t of tk.tracks) {
      if (t.type != "bigwig") continue;
      if (tk.bigwigsetting.scale) {
        if (tk.bigwigsetting.scale.max != void 0) {
          delete t.scale.auto;
          t.scale = {
            min: tk.bigwigsetting.scale.min,
            max: tk.bigwigsetting.scale.max
          };
        } else if (tk.bigwigsetting.scale.percentile) {
          delete t.scale.auto;
          t.scale.percentile = tk.bigwigsetting.scale.percentile;
        }
      }
      if (tk.bigwigsetting.pcolor) t.pcolor = tk.bigwigsetting.pcolor;
      if (tk.bigwigsetting.ncolor) t.ncolor = tk.bigwigsetting.ncolor;
      if (tk.bigwigsetting.pcolor2) t.pcolor = tk.bigwigsetting.pcolor2;
      if (tk.bigwigsetting.ncolor2) t.ncolor = tk.bigwigsetting.ncolor2;
    }
  }
  if (tk.genevaluetrack) {
    const gvtk = tk.genevaluetrack;
    delete tk.genevaluetrack;
    gvtk.name = tk.genevaluetype;
    delete tk.genevaluetype;
    if (tk.genevaluematchname) {
      gvtk.matchname = tk.genevaluematchname;
      delete tk.genevaluematchname;
    }
    if (tk.genebarcolor) {
      gvtk.barcolor = tk.genebarcolor;
      delete tk.genebarcolor;
    }
    if (tk.genebarwidth) {
      gvtk.barwidth = tk.genebarwidth;
      delete tk.genebarwidth;
    }
    if (!tk.genevaluetklst) {
      tk.genevaluetklst = [];
    }
    tk.genevaluetklst.push(gvtk);
  }
  if (tk.genevaluetklst) {
    for (const gvtk of tk.genevaluetklst) {
      gvtk.axisg = tk.gright.append("g");
      gvtk.label = tk.gright.append("text").attr("font-size", tk.axisfontsize + 2).attr("font-family", font).attr("class", "sja_clbtext").on("click", () => {
        gvtklabelclick(gvtk, tk, block);
      });
      if (!gvtk.barcolor) gvtk.barcolor = defaultbarcolor;
      if (!gvtk.barwidth) gvtk.barwidth = defaultbarwidth;
    }
    tk.toppad = tk.genevaluetklst.length == 1 ? 20 : 40;
    if (tk.genevaluetklst.length == 1) {
      tk.genevaluetklst[0].label.attr("text-anchor", "end").attr("x", -block.rpad).attr("y", gvtkheaderyoff);
    } else {
      for (const gvtk of tk.genevaluetklst) {
        gvtk.label.attr("y", tk.axisfontsize + 2 - tk.toppad).attr("text-anchor", "middle");
      }
    }
    tk.sample2gvtk2gene = /* @__PURE__ */ new Map();
    tk.genelsttip = new Menu({ padding: "5px" });
    setrightwidth(tk, block);
    tk.config_handle = block.maketklefthandle(tk, -block.labelfontsize + gvtkheaderyoff).text("CONFIG").attr("fill", "#858585").attr("x", 5).attr("text-anchor", "begin");
    tk.changegenelabel = tk.gright.append("text").attr("text-anchor", "end").attr("font-size", tk.axisfontsize).attr("font-family", font).attr("x", -block.rpad).attr("y", gvtkheaderyoff).attr("class", "sja_clbtext").on("click", () => {
      listgenes(tk.changegenelabel, tk, block);
    });
    if (tk.genevaluematchname) {
      for (const gvtk of tk.genevaluetklst) {
        if (!gvtk.matchname) gvtk.matchname = tk.genevaluematchname;
      }
      delete tk.genevaluematchname;
    }
  } else {
    tk.toppad = 20;
    tk.config_handle = block.maketkconfighandle(tk).attr("y", -5);
  }
  tk.config_handle.on("click", () => {
    configPanel(tk, block);
  });
  const collectleftlabw = [tk.tklabel.attr("y", -10).node().getBBox().width];
  if (block.legend && block.legend.holder) {
    let willshowlegend = false;
    if (tk.legendimg && tk.legendimg.file) {
      willshowlegend = true;
    } else if (tk.categories) {
      willshowlegend = true;
    } else if (tk.genevaluetklst) {
      willshowlegend = tk.genevaluetklst.find((i) => i.multivaluekey);
    }
    if (willshowlegend) {
      const [tr, td] = legend_newrow(block, tk.name);
      tk.tr_legend = tr;
      tk.td_legend = td;
      tk.legendtip = new Menu({ padding: "" });
    }
    if (tk.legendimg && tk.legendimg.file) {
      block.make_legend_img(tk.legendimg, tk.td_legend);
    } else if (tk.categories) {
      category2legend(tk.categories, tk.td_legend);
    }
    if (tk.genevaluetklst) {
      for (const gvtk of tk.genevaluetklst) {
        if (gvtk.multivaluekey) {
          gvtk.legend = {
            div: tk.td_legend.append("div"),
            gene2hiddenkeys: /* @__PURE__ */ new Map()
            // gene-specific setting
          };
          gvtk.legend.label_genespecific = gvtk.legend.div.append("div").style("display", "inline-block").style("margin", "5px 10px 10px 0px").style("color", "#858585").style("vertical-align", "top");
          gvtk.legend.contentdiv = gvtk.legend.div.append("div").style("display", "inline-block").style("margin", "0px 10px 10px 0px").style("vertical-align", "top").style("width", "800px");
        }
      }
    }
  }
  for (const t of tk.tracks) {
    t.g = tk.glider.append("g").attr("transform", "translate(0,0)");
    t.errg = t.g.append("g");
    t.immobileg = t.g.append("g").attr("transform", "translate(0,0)");
    t.tktip = tk.tktip;
    t.tklabel = t.immobileg.append("text").attr("font-size", tk.axisfontsize).attr("font-family", font).attr("text-anchor", "end").attr("dominant-baseline", "central").attr("x", block.tkleftlabel_xshift).attr("y", 0).text(t.name).on("mousedown", (event) => {
      event.stopPropagation();
      event.preventDefault();
      movetrack(t, tk, event.clientY);
    });
    if (t.list_description) {
      t.tklabel.on("mouseover", (event) => {
        t.tktip.clear().show(event.clientX, event.clientY);
        make_table_2col(t.tktip.d, t.list_description).style("margin", "");
      }).on("mouseout", () => t.tktip.hide());
    }
    collectleftlabw.push(t.tklabel.node().getBBox().width);
    if (tk.genevaluetklst) {
      t.genevg = t.immobileg.append("g");
      t.gvtkattr = /* @__PURE__ */ new Map();
      for (const gvtk of tk.genevaluetklst) {
        const obj = {};
        obj.gvtk_g_xshift = t.genevg.append("g");
        obj.hline = obj.gvtk_g_xshift.append("line").attr("stroke", "#ccc").attr("stroke-dasharray", "2,3").attr("shape-rendering", "crispEdges");
        obj.gvtk_g = obj.gvtk_g_xshift.append("g");
        if (gvtk.multivaluekey) {
        } else {
          obj.bar = obj.gvtk_g.append("rect").attr("width", 1);
        }
        t.gvtkattr.set(gvtk.name, obj);
      }
    }
    if (t.type == tkt.bedj) {
      t.img = t.g.append("image");
    } else if (t.type == tkt.bigwig) {
      t.img = t.g.append("image");
      t.leftaxis = t.immobileg.append("g");
    }
  }
  tk.leftLabelMaxwidth = Math.max(...collectleftlabw);
  block.setllabel();
}
async function loadTk(tk, block) {
  if (tk.uninitiated) {
    makeTk(tk, block);
    delete tk.uninitiated;
  }
  block.tkcloakon(tk);
  const tasks = [];
  for (const t of tk.tracks) {
    t.height = 20;
    t.errg.selectAll("*").remove();
    if (t.type == tkt.bedj) {
      const arg = block.tkarg_bedj(t);
      if (tk.categories) {
        arg.categories = tk.categories;
      }
      const task = dofetch3("tkbedj", { method: "POST", body: JSON.stringify(arg) }).then((data) => {
        if (data.error) throw data.error;
        t.height = t.toppad + data.height + t.bottompad;
        t.img.attr("width", block.width).attr("height", data.height).attr("xlink:href", data.src);
        if (block.pannedpx != void 0) {
          t.img.attr("x", block.pannedpx * -1);
        }
        block.bedj_tooltip(t, data);
      }).catch((e) => tkerror(t, e.message || e));
      tasks.push(task);
    } else if (t.type == tkt.bigwig) {
      const arg = block.tkarg_q(t);
      const task = dofetch3("tkbigwig", {
        method: "POST",
        body: JSON.stringify(arg)
      }).then((data) => {
        if (data.error) throw data.error;
        t.height = t.toppad + t.barheight + t.bottompad;
        t.img.attr("width", block.width).attr("height", t.barheight).attr("xlink:href", data.src);
        if (block.pannedpx != void 0) {
          t.img.attr("x", block.pannedpx * -1);
        }
        if (data.minv != void 0) {
          t.scale.min = data.minv;
        }
        if (data.maxv != void 0) {
          t.scale.max = data.maxv;
        }
        t.leftaxis.selectAll("*").remove();
        if (data.nodata) {
        } else {
          const scale = linear().domain([t.scale.min, t.scale.max]).range([t.barheight, 0]);
          axisstyle({
            axis: t.leftaxis.call(axisLeft().scale(scale).tickValues([t.scale.min, t.scale.max])),
            color: "black",
            showline: true
          });
        }
      }).catch((e) => tkerror(t, e.message || e));
      tasks.push(task);
    }
  }
  if (tk.genevaluetklst) {
    tk.sample2gvtk2gene.clear();
    tk.geneset.clear();
    for (const gvtk of tk.genevaluetklst) {
      const arg = block.tkarg_bedj(gvtk);
      arg.getdata = 1;
      const task = dofetch3("tkbedj", { method: "POST", body: JSON.stringify(arg) }).then((data) => {
        if (data.error) throw data.error;
        if (data.items && data.items.length > 0) {
          for (const i of data.items) {
            if (!i.gene || !i.sample) continue;
            tk.geneset.add(i.gene);
            if (!tk.sample2gvtk2gene.has(i.sample)) {
              tk.sample2gvtk2gene.set(i.sample, /* @__PURE__ */ new Map());
            }
            if (!tk.sample2gvtk2gene.get(i.sample).has(gvtk.name)) {
              tk.sample2gvtk2gene.get(i.sample).set(gvtk.name, /* @__PURE__ */ new Map());
            }
            if (gvtk.multivaluekey) {
              if (!tk.sample2gvtk2gene.get(i.sample).get(gvtk.name).has(i.gene)) {
                tk.sample2gvtk2gene.get(i.sample).get(gvtk.name).set(i.gene, []);
              }
              tk.sample2gvtk2gene.get(i.sample).get(gvtk.name).get(i.gene).push({
                name: i[gvtk.multivaluekey],
                value: i.value
              });
            } else {
              tk.sample2gvtk2gene.get(i.sample).get(gvtk.name).set(i.gene, i.value);
            }
          }
        }
      });
      tasks.push(task);
    }
  }
  try {
    await Promise.all(tasks);
    render_tk(tk, block);
    block.tkcloakoff(tk, {});
  } catch (e) {
    if (e.stack) console.log(e.stack);
    block.tkcloakoff(tk, { error: e.message || e });
  }
  for (const t of tk.tracks) {
    t.immobileg.attr("transform", "translate(0,0)");
  }
  block.block_setheight();
}
function render_tk(tk, block) {
  tk.height_main = 0;
  for (const t of tk.tracks) {
    t.y = tk.height_main;
    t.g.transition().attr("transform", "translate(0," + t.y + ")");
    if (t.type == tkt.bedj) {
      t.img.attr("x", 0);
      t.tklabel.attr("y", (t.height - t.toppad - t.bottompad) / 2);
    } else if (t.type == tkt.bigwig) {
      t.img.attr("x", 0);
      t.tklabel.attr("y", t.barheight / 2);
    }
    tk.height_main += t.height;
  }
  tk.height_main += tk.toppad + tk.bottompad;
  if (tk.genevaluetklst) {
    if (tk.geneset.size > 0) {
      const showgene = [...tk.geneset][0];
      showgeneplot(tk, block, showgene);
    } else {
      for (const gvtk of tk.genevaluetklst) {
        gvtk.label.text("");
      }
      for (const t of tk.tracks) {
        for (const v of t.gvtkattr.values()) {
          v.hline.transition().attr("x2", 0);
          if (v.bar) {
            v.bar.transition().attr("width", 0);
          } else {
            v.gvtk_g.selectAll("*").remove();
          }
        }
      }
      for (const gvtk of tk.genevaluetklst) {
        gvtk.axisg.selectAll("*").remove();
      }
    }
  }
}
function showgeneplot(tk, block, gene) {
  tk.__usegene = gene;
  let xoff = 0;
  for (const gvtk of tk.genevaluetklst) {
    let minv = 0;
    let maxv = 0;
    const samplekey = gvtk.matchname || "name";
    let colorvend;
    if (gvtk.multivaluekey) {
      gvtk.runtimekey2color_genespecific = /* @__PURE__ */ new Map();
      colorvend = ordinal(category10_default);
    }
    for (const t of tk.tracks) {
      t.gvtkattr.get(gvtk.name).value = void 0;
      const samplename = t[samplekey];
      if (!tk.sample2gvtk2gene.has(samplename)) {
        continue;
      }
      if (!tk.sample2gvtk2gene.get(samplename).has(gvtk.name)) {
        continue;
      }
      const genev = tk.sample2gvtk2gene.get(samplename).get(gvtk.name).get(gene);
      if (genev == void 0) continue;
      t.gvtkattr.get(gvtk.name).value = genev;
      if (gvtk.multivaluekey) {
        for (const v of genev) {
          if (!v.name) {
            continue;
          }
          if (!gvtk.runtimekey2color_genespecific.has(v.name)) {
            gvtk.runtimekey2color_genespecific.set(v.name, colorvend(v.name));
          }
          maxv = Math.max(maxv, v.value);
        }
      } else {
        maxv = Math.max(maxv, genev);
      }
    }
    for (const t of tk.tracks) {
      t.genevg.attr("transform", "translate(" + (block.width + block.rpad) + ",0)");
      const obj = t.gvtkattr.get(gvtk.name);
      const glyph_midy = (t.height - t.toppad - t.bottompad) / 2;
      obj.gvtk_g_xshift.transition().attr("transform", "translate(" + xoff + ",0)");
      obj.hline.transition().attr("y1", glyph_midy).attr("y2", glyph_midy).attr("x2", obj.value == void 0 ? 0 : gvtk.barwidth);
      if (gvtk.multivaluekey) {
        obj.gvtk_g.selectAll("*").remove();
        if (obj.value) {
          const radius = Math.min(8, glyph_midy);
          let showlst = obj.value;
          if (gvtk.legend.gene2hiddenkeys.has(tk.__usegene)) {
            showlst = obj.value.filter((i) => !gvtk.legend.gene2hiddenkeys.get(tk.__usegene).has(i.name));
          }
          obj.dotg = obj.gvtk_g.selectAll().data(showlst).enter().append("g").attr("transform", (d) => "translate(" + gvtk.barwidth * d.value / maxv + "," + glyph_midy + ")");
          obj.dotg.append("circle").attr("r", radius).attr("fill", (d) => gvtk.runtimekey2color_genespecific.get(d.name)).attr("fill-opacity", 0.2).attr("stroke", (d) => gvtk.runtimekey2color_genespecific.get(d.name)).on("mouseover", (event, d) => {
            const valuekeyname = d.name;
            for (const t2 of tk.tracks) {
              const obj2 = t2.gvtkattr.get(gvtk.name);
              if (!obj2.dotg) continue;
              obj2.dotg.filter((d2) => d2.name == valuekeyname).select("circle").attr("fill-opacity", 1);
            }
            const p = event.target.getBoundingClientRect();
            tk.tktip.clear().show(p.left, p.top);
            const lst = [
              { k: "sample", v: t.name },
              { k: gvtk.multivaluekey, v: d.name },
              { k: "value", v: d.value }
            ];
            setTimeout(make_table_2col(tk.tktip.d, lst), 500);
          }).on("mouseout", (event, d) => {
            const valuekeyname = d.name;
            for (const t2 of tk.tracks) {
              const obj2 = t2.gvtkattr.get(gvtk.name);
              if (!obj2.dotg) continue;
              obj2.dotg.filter((d2) => d2.name == valuekeyname).select("circle").attr("fill-opacity", 0.2);
            }
            tk.tktip.hide();
          });
        }
      } else {
        if (!Number.isFinite(obj.value) || obj.value == 0) {
          obj.bar.transition().attr("width", 0);
        } else {
          obj.bar.attr("fill", gvtk.barcolor).attr("height", t.height - t.toppad - t.bottompad).transition().attr("width", Math.max(1, gvtk.barwidth * obj.value / maxv));
        }
      }
    }
    if (tk.genevaluetklst.length > 1) {
      gvtk.label.transition().attr("x", xoff + gvtk.barwidth / 2);
    }
    gvtk.label.text(gene + " " + gvtk.name);
    {
      const axis = axisTop().ticks(3).scale(linear().domain([minv, maxv]).range([0, gvtk.barwidth]));
      if (gvtk.axistickformat) {
        axis.tickFormat(format(gvtk.axistickformat));
      }
      axisstyle({
        axis: gvtk.axisg.transition().attr("transform", "translate(" + xoff + "," + gvtkheaderyoff + ")").call(axis),
        color: "black",
        showline: true
      });
    }
    xoff += gvtk.barwidth + genevaluexspace;
  }
  if (tk.geneset.size == 1) {
    tk.changegenelabel.text("");
  } else {
    tk.changegenelabel.text("CHANGE GENE");
    if (tk.genevaluetklst.length == 1) {
      const w = tk.genevaluetklst[0].label.node().getBBox().width;
      tk.changegenelabel.attr("x", -block.rpad - w - 10);
    }
  }
  showlegend_gvtk(tk, block);
}
function showlegend_gvtk(tk, block) {
  if (!tk.genevaluetklst || !tk.tr_legend) return;
  for (const gvtk of tk.genevaluetklst) {
    if (gvtk.runtimekey2color_genespecific) {
      gvtk.legend.label_genespecific.text(tk.__usegene + " " + gvtk.name + " " + gvtk.multivaluekey);
      gvtk.legend.contentdiv.selectAll("*").remove();
      const lst = [];
      for (const [name, color] of gvtk.runtimekey2color_genespecific.entries()) {
        lst.push({ name, color });
      }
      if (gvtk.sitekeytrickysort) {
        lst.sort((a, b) => Number.parseInt(a.name.substr(1)) - Number.parseInt(b.name.substr(1)));
      }
      for (const { name, color } of lst) {
        const cell = gvtk.legend.contentdiv.append("div").style("display", "inline-block").attr("class", "sja_clb").on("click", () => {
          tk.legendtip.clear().showunder(cell.node());
          if (gvtk.legend.gene2hiddenkeys.has(tk.__usegene) && gvtk.legend.gene2hiddenkeys.get(tk.__usegene).has(name)) {
            tk.legendtip.d.append("div").attr("class", "sja_menuoption").text("Show").on("click", () => {
              tk.legendtip.hide();
              gvtk.legend.gene2hiddenkeys.get(tk.__usegene).delete(name);
              showgeneplot(tk, block, tk.__usegene);
            });
          } else {
            tk.legendtip.d.append("div").attr("class", "sja_menuoption").text("Hide").on("click", () => {
              tk.legendtip.hide();
              if (!gvtk.legend.gene2hiddenkeys.has(tk.__usegene))
                gvtk.legend.gene2hiddenkeys.set(tk.__usegene, /* @__PURE__ */ new Set());
              gvtk.legend.gene2hiddenkeys.get(tk.__usegene).add(name);
              showgeneplot(tk, block, tk.__usegene);
            });
          }
          tk.legendtip.d.append("div").attr("class", "sja_menuoption").text("Show only").on("click", () => {
            tk.legendtip.hide();
            if (!gvtk.legend.gene2hiddenkeys.has(tk.__usegene))
              gvtk.legend.gene2hiddenkeys.set(tk.__usegene, /* @__PURE__ */ new Set());
            gvtk.legend.gene2hiddenkeys.get(tk.__usegene).clear();
            for (const name2 of gvtk.runtimekey2color_genespecific.keys()) {
              if (name2 != name) gvtk.legend.gene2hiddenkeys.get(tk.__usegene).add(name2);
            }
            showgeneplot(tk, block, tk.__usegene);
          });
          tk.legendtip.d.append("div").attr("class", "sja_menuoption").text("Show all").on("click", () => {
            tk.legendtip.hide();
            if (!gvtk.legend.gene2hiddenkeys.has(tk.__usegene)) return;
            gvtk.legend.gene2hiddenkeys.get(tk.__usegene).clear();
            showgeneplot(tk, block, tk.__usegene);
          });
        });
        if (gvtk.legend.gene2hiddenkeys.has(tk.__usegene) && gvtk.legend.gene2hiddenkeys.get(tk.__usegene).has(name)) {
          cell.append("span").style("color", "#858585").style("text-decoration", "line-through").text(name);
        } else {
          cell.append("span").attr("class", "sja_mcdot").style("background-color", color).style("margin-left", "3px").html("&nbsp;&nbsp;");
          cell.append("span").text(name);
        }
      }
    }
  }
}
function listgenes(label, tk, block) {
  tk.tkconfigtip.clear().showunder(label.node());
  const name = Math.random().toString();
  for (const gene of tk.geneset) {
    const row = tk.tkconfigtip.d.append("div").style("padding-bottom", "3px");
    const id = Math.random().toString();
    const radio = row.append("input").attr("type", "radio").attr("id", id).attr("name", name).on("change", () => {
      showgeneplot(tk, block, gene);
    });
    if (gene == tk.__usegene) {
      radio.attr("checked", 1);
    }
    row.append("label").attr("for", id).html("&nbsp;" + gene);
  }
}
function movetrack(t, tk, y0) {
  const body = select_default(document.body);
  body.on("mousemove", (event) => {
    const dy = event.clientY - y0;
    t.g.attr("transform", "translate(0," + (t.y + dy) + ")");
    let tkidx = 0;
    for (let i = 0; i < tk.tracks.length; i++) {
      if (tk.tracks[i].name == t.name) {
        tkidx = i;
        break;
      }
    }
    if (dy < 0 && tkidx > 0) {
      let t2idx = tkidx - 1, t2 = tk.tracks[t2idx];
      while (t2.hidden) {
        t2idx--;
        if (t2idx < 0) {
          return;
        }
        t2 = tk.tracks[t2idx];
      }
      if (!t2) {
        return;
      }
      if (-dy >= t2.height) {
        tk.tracks[t2idx] = t;
        tk.tracks[tkidx] = t2;
        t.y = t2.y;
        t2.y += t.height;
        t2.g.transition().attr("transform", "translate(0," + t2.y + ")");
        y0 = event.clientY;
      }
    } else if (dy > 0 && tkidx < tk.tracks.length - 1) {
      let t2idx = tkidx + 1, t2 = tk.tracks[t2idx];
      while (t2.hidden) {
        t2idx++;
        if (t2idx >= tk.tracks.length) {
          return;
        }
        t2 = tk.tracks[t2idx];
      }
      if (!t2) {
        return;
      }
      if (dy >= t2.height) {
        tk.tracks[t2idx] = t;
        tk.tracks[tkidx] = t2;
        t2.y = t.y;
        t.y += t2.height;
        t2.g.transition().attr("transform", "translate(0," + t2.y + ")");
        y0 = event.clientY;
      }
    }
  });
  body.on("mouseup", () => {
    t.g.transition().attr("transform", "translate(0," + t.y + ")");
    body.on("mousemove", null).on("mouseup", null);
  });
}
function configPanel(tk, block) {
  tk.tkconfigtip.clear().showunder(tk.config_handle.node());
  const d = tk.tkconfigtip.d;
  {
    const hasbw = tk.tracks.find((t) => t.type == tkt.bigwig);
    if (hasbw) {
      d.append("div").append("div").style("margin-bottom", "15px").style("display", "inline-block").attr("class", "sja_menuoption").text("Common settings for all bigWig member tracks").on("click", () => {
        configPanel_bwcommon(tk, block);
      });
    }
  }
  configPanel_uniformheight(d, tk, block);
  configPanel_tkheights(d, tk, block);
  d.append("div").style("margin-top", "5px").style("color", "#858585").text("To reorder member tracks, drag on track name on the left of track display.");
}
function setrightwidth(tk, block) {
  tk.rightheadw_tk = 30;
  if (tk.genevaluetklst) {
    for (const t of tk.genevaluetklst) {
      tk.rightheadw_tk += t.barwidth;
    }
    tk.rightheadw_tk += genevaluexspace * (tk.genevaluetklst.length - 1);
  }
  block.rightheadw = 0;
  for (const t of block.tklst) {
    block.rightheadw = Math.max(block.rightheadw, t.rightheadw_tk);
  }
  block.blocksetw();
}
function configPanel_bwcommon(tk, block) {
  tk.tkconfigtip.clear();
  const mock = {
    scale: { auto: 1 },
    normalize: { disable: 1 }
  };
  if (tk.bigwigsetting) {
    for (const k in tk.bigwigsetting) {
      mock[k] = tk.bigwigsetting[k];
    }
    if (tk.bigwigsetting.scale) {
      delete mock.scale.auto;
      for (const k in tk.bigwigsetting.scale) mock.scale[k] = tk.bigwigsetting.scale[k];
    }
  }
  {
    const t1 = tk.tracks.find((t) => t.type == tkt.bigwig);
    if (!mock.pcolor) mock.pcolor = t1.pcolor;
    if (!mock.pcolor2) mock.pcolor2 = t1.pcolor2;
    if (!mock.ncolor) mock.ncolor = t1.ncolor;
    if (!mock.ncolor2) mock.ncolor2 = t1.ncolor2;
    if (!mock.barheight) mock.barheight = t1.barheight;
  }
  bigwigconfigpanel(mock, block, tk.tkconfigtip.d, (code) => {
    if (!tk.bigwigsetting) tk.bigwigsetting = {};
    if (!tk.bigwigsetting.scale) tk.bigwigsetting.scale = {};
    switch (code) {
      case bwSetting.height:
        tk.bigwigsetting.barheight = mock.barheight;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.barheight = mock.barheight;
        });
        break;
      case bwSetting.pcolor:
        tk.bigwigsetting.pcolor = mock.pcolor;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.pcolor = mock.pcolor;
        });
        break;
      case bwSetting.ncolor:
        tk.bigwigsetting.ncolor = mock.ncolor;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.ncolor = mock.ncolor;
        });
        break;
      case bwSetting.pcolor2:
        tk.bigwigsetting.pcolor2 = mock.pcolor2;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.pcolor2 = mock.pcolor2;
        });
        break;
      case bwSetting.ncolor2:
        tk.bigwigsetting.ncolor2 = mock.ncolor2;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.ncolor2 = mock.ncolor2;
        });
        break;
      case bwSetting.autoscale:
        tk.bigwigsetting.scale.auto = 1;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.scale.auto = 1;
        });
        break;
      case bwSetting.fixedscale:
        delete tk.bigwigsetting.scale.auto;
        tk.bigwigsetting.scale.min = mock.scale.min;
        tk.bigwigsetting.scale.max = mock.scale.max;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) {
            delete t.scale.auto;
            t.scale.min = mock.scale.min;
            t.scale.max = mock.scale.max;
          }
        });
        break;
      case bwSetting.percentilescale:
        delete tk.bigwigsetting.scale.auto;
        tk.bigwigsetting.scale.percentile = mock.scale.percentile;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) {
            delete t.scale.auto;
            t.scale.percentile = mock.scale.percentile;
          }
        });
        break;
      case bwSetting.nodotplot:
        delete tk.bigwigsetting.dotplotfactor;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) delete t.dotplotfactor;
        });
        break;
      case bwSetting.usedotplot:
        tk.bigwigsetting.dotplotfactor = mock.dotplotfactor;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.dotplotfactor = mock.dotplotfactor;
        });
        break;
      case bwSetting.usedividefactor:
        delete tk.bigwigsetting.normalize.disable;
        tk.bigwigsetting.normalize.dividefactor = mock.normalize.dividefactor;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) {
            delete t.normalize.disable;
            t.normalize.dividefactor = mock.normalize.dividefactor;
          }
        });
        break;
      case bwSetting.nodividefactor:
        tk.bigwigsetting.normalize.disable = 1;
        tk.tracks.forEach((t) => {
          if (t.type == tkt.bigwig) t.normalize.disable = 1;
        });
        break;
    }
    loadTk(tk, block);
  });
}
function configPanel_uniformheight(d, tk, block) {
  const row = d.append("div").style("margin-bottom", "10px");
  row.append("span").style("color", "#858585").html("Set uniform height to all member tracks&nbsp;");
  let maxheight = 0;
  for (const t of tk.tracks) {
    switch (t.type) {
      case tkt.bigwig:
        maxheight = Math.max(maxheight, t.barheight);
        break;
      case tkt.bedj:
        maxheight = Math.max(maxheight, t.stackheight);
        break;
    }
  }
  row.append("input").attr("type", "number").property("value", maxheight).attr("min", 5).style("width", "80px").on("keyup", (event) => {
    if (event.code != "Enter") return;
    const v = Number.parseInt(event.target.value);
    for (const t of tk.tracks) {
      switch (t.type) {
        case tkt.bigwig:
          t.barheight = v;
          break;
        case tkt.bedj:
          t.stackheight = v;
          break;
      }
    }
    block.tk_load(tk);
  });
}
function configPanel_tkheights(d, tk, block) {
  d.append("div").style("margin-bottom", "5px").style("color", "#858585").text("Set height for each track:");
  let scrollholder = d;
  if (tk.tracks.length > 8) {
    scrollholder = d.append("div").style("display", "inline-block").style("height", "200px").style("resize", "vertical").style("overflow-y", "scroll");
  }
  const table = scrollholder.append("table").style("margin-left", "20px");
  for (const t of tk.tracks) {
    const tr = table.append("tr");
    tr.append("td").text(t.name).style("vertical-align", "top");
    const td = tr.append("td");
    let v;
    switch (t.type) {
      case tkt.bigwig:
        v = t.barheight;
        break;
      case tkt.bedj:
        v = t.stackheight;
        break;
    }
    td.append("input").attr("type", "number").property("value", v).attr("min", 5).style("width", "80px").on("keyup", (event) => {
      if (event.code != "Enter") return;
      const v2 = Number.parseInt(event.target.value);
      switch (t.type) {
        case tkt.bigwig:
          t.barheight = v2;
          break;
        case tkt.bedj:
          t.stackheight = v2;
          break;
      }
      block.tk_load(tk);
    });
  }
}
function gvtklabelclick(gvtk, tk, block) {
  tk.tkconfigtip.clear().showunder(gvtk.label.node());
  {
    const row = tk.tkconfigtip.d.append("div").style("margin-bottom", "10px").style("color", "#858585");
    row.append("span").text(gvtk.name);
    row.append("span").html("&nbsp;CONFIG").style("font-size", ".7em");
  }
  const table = tk.tkconfigtip.d.append("table");
  {
    const tr = table.append("tr");
    tr.append("td").text("Max bar width");
    tr.append("td").append("input").attr("type", "number").property("value", gvtk.barwidth).attr("min", 50).style("width", "50px").on("keyup", (event) => {
      if (event.code != "Enter" && event.code != "NumpadEnter") return;
      const w = Number.parseInt(event.target.value);
      if (Number.isNaN(w) || w < 50) return;
      gvtk.barwidth = w;
      setrightwidth(tk, block);
      showgeneplot(tk, block, tk.__usegene);
    });
  }
  if (!gvtk.multivaluekey) {
    const tr = table.append("tr");
    tr.append("td").text("Bar color");
    tr.append("td").append("input").attr("type", "color").property("value", gvtk.barcolor).on("change", (event) => {
      gvtk.barcolor = event.target.value;
      if (gvtk.multivaluekey) {
      } else {
        for (const t of tk.tracks) {
          t.gvtkattr.get(gvtk.name).bar.attr("fill", gvtk.barcolor);
        }
      }
    });
    table.append("tr").append("td").attr("colspan", 2).append("button").text("Sort samples").on("click", () => {
      tk.tracks.sort((a, b) => {
        const va = a.gvtkattr.get(gvtk.name).value;
        const vb = b.gvtkattr.get(gvtk.name).value;
        if (vb == void 0) {
          if (va == void 0) return 0;
          return -1;
        }
        if (va == void 0) return 1;
        return vb - va;
      });
      const currentgene = tk.__usegene;
      render_tk(tk, block);
      showgeneplot(tk, block, currentgene);
      tk.tkconfigtip.hide();
    });
  }
  if (gvtk.multivaluekey) {
  }
}
function tkerror(t, msg) {
  t.errg.append("text").text(msg).attr("font-size", 12).attr("y", 14);
}
export {
  loadTk
};
//# sourceMappingURL=block.tk.pgv-XO7HP5MM.js.map
