import {
  makeButton,
  openSandbox
} from "./chunk-R2MMURGK.js";
import {
  get_tklst
} from "./chunk-IW57W7EQ.js";
import "./chunk-ZTYNN6G5.js";
import "./chunk-DKVUOBIE.js";
import "./chunk-PRZWSBMA.js";
import "./chunk-MKAF2BHB.js";
import {
  urlmap_default
} from "./chunk-WKNI3HRQ.js";
import "./chunk-VGYTAYFK.js";
import {
  block_init_default
} from "./chunk-67DBIM6H.js";
import {
  InputSearch,
  first_genetrack_tolist,
  newSandboxDiv,
  sayerror,
  throwMsgWithFilePathAndFnName
} from "./chunk-SA7APTJR.js";
import {
  string2pos
} from "./chunk-HJ6L54YS.js";
import "./chunk-LSEFWW72.js";
import "./chunk-SKREEF3H.js";
import "./chunk-HYOEWQ5P.js";
import "./chunk-HBW42TDT.js";
import "./chunk-G6O3URDN.js";
import "./chunk-FN5XPUPH.js";
import "./chunk-IIT367QZ.js";
import "./chunk-RZGEKL77.js";
import "./chunk-UI7OCM2A.js";
import "./chunk-YZK37YCC.js";
import {
  dofetch3
} from "./chunk-7EMWHCVW.js";
import "./chunk-7IYJZZQI.js";
import {
  StoreBase,
  getAppInit,
  getCompInit,
  getStoreInit
} from "./chunk-M3J4MINX.js";
import "./chunk-PF4DSFDR.js";
import "./chunk-QH6W3NVF.js";
import "./chunk-NOEAT6CX.js";
import {
  defaultcolor
} from "./chunk-4UWS5Y3N.js";
import "./chunk-DD4R5P6W.js";
import "./chunk-JNITUVXP.js";
import "./chunk-KSGA62R2.js";
import "./chunk-LOZEKOES.js";
import "./chunk-TOU7EVFQ.js";
import "./chunk-OAWQ6LOO.js";
import "./chunk-TLT4YIG3.js";
import "./chunk-KYBIQBXE.js";
import {
  select_default
} from "./chunk-I6Y4O3RR.js";
import {
  rgb
} from "./chunk-OMR2DT66.js";
import "./chunk-DQC5FFGV.js";
import "./chunk-HFNDKYVF.js";

// src/header/omniSearch.js
async function searchItems(app, tip, help, publications, jwt) {
  const userInput = select_default("input").property("value").trim();
  const data = [
    {
      title: "Genes",
      default: true,
      items: await findgenelst(userInput, app.selectgenome.property("value"), jwt),
      color: "#F2F2F2",
      callback: (d) => {
        app.drawer.dispatch({ type: "is_apps_btn_active", value: false });
        tip.hide();
        findgene2paint(d, app, app.selectgenome.property("value"), jwt);
      }
    }
  ];
  await findAppDrawerElements(app, userInput, data, tip);
  data.push({
    title: "Help",
    default: false,
    items: help.filter((d) => d.label.toLowerCase().includes(userInput.toLowerCase())),
    color: "#faebd9",
    callback: (d) => {
      window.open(d.link, d.label);
    }
  });
  data.push({
    title: "Publications",
    default: false,
    items: publications.filter(
      (d) => d.title.toLowerCase().includes(userInput.toLowerCase()) || d.appHeaderTitle.toLowerCase().includes(userInput.toLowerCase())
    ),
    color: "#E6E6FA",
    callback: (d) => {
      const url = d.pmidURL || d.doi;
      if (!url || !d.title) throw `Missing url or title for search selection`;
      window.open(url, d.title);
    }
  });
  return data;
}
async function findAppDrawerElements(app, input, data, tip) {
  const re = await dofetch3(app.cardsPath + "/index.json");
  if (re.error) throwMsgWithFilePathAndFnName(`Problem retrieving ../cards/index.json`);
  const userInput = input.toLowerCase().trim();
  const elements = [...re.elements];
  let filteredElements;
  if (userInput.length > 2) {
    await getExampleNames(elements, app);
    filteredElements = getFilteredElements(elements, userInput);
  } else {
    filteredElements = getFilteredElements(elements, userInput);
  }
  const opts = {
    app: app.drawer.opts,
    sandboxDiv: app.drawer.opts.sandboxDiv,
    genomes: app.genomes,
    fromApp: true
  };
  data.push(
    {
      title: "Tracks and Apps",
      items: filteredElements.filter((c) => c.type == "card"),
      color: "#e1edf7",
      callback: (element) => {
        app.drawer.dispatch({ type: "is_apps_btn_active", value: false });
        tip.hide();
        openSandbox(element, opts);
      }
    },
    {
      title: "Datasets",
      items: filteredElements.filter((c) => c.type == "dsButton"),
      color: "#e5f5e4",
      callback: (element) => {
        app.drawer.dispatch({ type: "is_apps_btn_active", value: false });
        tip.hide();
        openSandbox(element, opts);
      }
    }
  );
  return data;
}
async function getExampleNames(elements, app) {
  const promises = elements.map(async (elem) => {
    if (elem.hidden || elem.type != "card" || !elem.sandboxJson) return elem;
    const exs = await dofetch3(app.cardsPath + `/${elem.sandboxJson}.json`);
    if (exs?.ppcalls.length > 0) {
      for (const c of exs.ppcalls) {
        if (c.isUI) return;
        if (c?.label) elem.searchterms.push(c.label);
      }
    }
  });
  await Promise.all(promises);
}
function getFilteredElements(elements, userInput) {
  return elements.filter((elem) => {
    if (elem.hidden) return false;
    let searchTermFound = (elem.searchterms || []).reduce((searchTermFound2, searchTerm) => {
      if (searchTermFound2) return true;
      return searchTerm.toLowerCase().includes(userInput);
    }, false);
    return searchTermFound || elem.name.toLowerCase().includes(userInput);
  }).sort((a, b) => a.name.localeCompare(b.name));
}
async function findgenelst(str, genome, jwt) {
  if (str.length == 0) return;
  try {
    const data = await dofetch3("/genelookup", {
      body: {
        input: str,
        genome,
        jwt
      }
    });
    if (data.error) throw data.error;
    if (!data.hits) throw ".hits[] missing";
    return data.hits;
  } catch (err) {
  }
}
async function findgene2paint(str, app, genomename, jwt) {
  const g = app.genomes[genomename];
  if (!g) {
    console.error("unknown genome " + genomename);
    return;
  }
  const sandbox_div = newSandboxDiv(app.drawer.opts.sandboxDiv);
  sandbox_div.header.html(
    '<div style="display:inline-block;">' + str + '</div><div class="sjpp-output-sandbox-title">' + genomename + "</div>"
  );
  const urlp = urlmap_default();
  const tklst = await get_tklst(urlp, g);
  const pos = string2pos(str, g);
  if (pos) {
    const par2 = {
      hostURL: app.hostURL,
      jwt,
      holder: sandbox_div.body,
      genome: g,
      nobox: true,
      chr: pos.chr,
      start: pos.start - 1,
      // entered positions are 1-based. block uses 0-based
      stop: pos.stop - 1,
      dogtag: genomename,
      tklst,
      debugmode: app.debugmode
    };
    first_genetrack_tolist(g, par2.tklst);
    import("./block-TTN2IQAH.js").then((b) => new b.Block(par2)).catch((err) => {
      app.error0(err);
    });
    return;
  }
  const par = {
    hostURL: app.hostURL,
    jwt,
    query: str,
    genome: g,
    holder: sandbox_div.body,
    variantPageCall_snv: app.variantPageCall_snv,
    samplecart: app.samplecart,
    tklst,
    debugmode: app.debugmode
  };
  const tmp = sessionStorage.getItem("urlp_mds");
  if (tmp) {
    const l = tmp.split(",");
    if (l.length == 2) {
      par.datasetqueries = [{ dataset: l[0], querykey: l[1] }];
    }
  }
  await block_init_default(par);
}

// appdrawer/card.js
var AppDrawerCard = class {
  static type = "card";
  // handles types 'card' and 'nestedCard'
  constructor(opts) {
    this.type = "card";
    this.opts = this.validateOpts(opts);
    this.holder = opts.holder;
    this.dom = opts.dom;
    this.sandboxDiv = opts.sandboxDiv;
    setRenderers(this);
  }
  validateOpts(opts) {
    if (!opts.element.name) throw `Card .name is missing`;
    if (opts.element.type == "card") {
      if (!opts.element.sandboxJson && !opts.element.sandboxHtml)
        throw `Either .sandboxJson or .sandboxHtml is missing for card=${opts.element.name}`;
    }
    if (opts.element.type == "nestedCard") {
      if (!opts.element.children || opts.element.children.length == 0)
        throw `Missing .children for nested card = ${opts.element.name}`;
    }
    if (opts.element.ribbon) {
      if (!opts.element.ribbon.text) throw `Missing ribbon .text for ${opts.element.type} = ${opts.element.name}`;
      if ((opts.element.ribbon.text.toUpperCase() == "NEW" || opts.element.ribbon.text.toUpperCase() == "UPDATED") && !opts.element.ribbon.expireDate)
        throw `${opts.element.type} = ${opts.element.name} ribbon is ${opts.element.ribbon.text.toUpperCase()} but .expireDate is missing. Please provide`;
      if (opts.element.ribbon.expireDate) {
        if (opts.element.ribbon.expireDate >= 0) {
          throw `Flag for ${opts.element.type} = ${opts.element.name} is not a valid date`;
        }
      }
    }
    return opts;
  }
  main() {
  }
};
var cardInit = getCompInit(AppDrawerCard);
function setRenderers(self) {
  const card = self.holder.append("li");
  if (self.opts.element.type == "card") {
    card.classed("sjpp-track", true).html(
      `<div class="sjpp-track-h"><span style="font-size:14.5px;font-weight:500;">${self.opts.element.name}</span></div>
				${self.opts.element.description ? `<span class="sjpp-track-blurb" style="cursor:default">${self.opts.element.description}</span></div>` : " "}
				<span class="sjpp-track-image"><img src="${self.opts.element.image}" alt="${self.opts.element.description}"></img></span>
				</div>`
    );
  } else if (self.opts.element.type == "nestedCard") {
    card.classed("sjpp-app-drawer-card", true).html(
      `<p style="margin-left: 12px; font-size:14.5px;font-weight:500; display: block;">${self.opts.element.name}</p>
			<p style="display: block; font-size: 13px; font-weight: 300; margin-left: 20px; justify-content: center; font-style:oblique; color: #403f3f;">${self.opts.element.description}</p>`
    );
  }
  self.makeRibbon = function(ribbon) {
    const ribbonDiv = card.append("div").classed("sjpp-app-drawer-card-ribbon", true).style("align-items", "center").style("justify-content", "center");
    const text = ribbon.text.toUpperCase();
    const color = text == "BETA" ? "#418cb5" : text == "NEW" ? "#1ba176" : text == "UPDATED" ? "orange" : ribbon.color ? ribbon.color : "red";
    ribbonDiv.append("span").text(text).style("color", "white").style("background-color", rgb(color).darker()).style("height", "auto").style("width", "100%").style("top", "15%").style("left", "-30%").style("font-size", "11.5px").style("text-transform", "uppercase").style("text-align", "center");
  };
  if (self.opts.element.ribbon) {
    const today = /* @__PURE__ */ new Date();
    const ribbonExpireDate = new Date(self.opts.element.ribbon.expireDate);
    if (ribbonExpireDate > today || ribbonExpireDate == "Invalid Date") self.makeRibbon(self.opts.element.ribbon);
  }
  card.on("click", async (event) => {
    event.stopPropagation();
    await self.app.dispatch({
      type: "is_apps_btn_active",
      value: false
    });
    slideDrawer(self);
    setTimeout(async () => {
      await openSandbox(self.opts.element, self.opts);
    }, self.state.duration + 5);
  });
}

// appdrawer/dsButton.js
var AppDrawerButton = class {
  static type = "button";
  constructor(opts) {
    this.type = "button";
    this.opts = this.validateOpts(opts);
    this.holder = opts.holder;
    this.dom = opts.dom;
    this.sandboxDiv = opts.sandboxDiv;
    setRenderers2(this);
  }
  validateOpts(opts) {
    if (!opts.element.name) throw `Button name is missing`;
    if (!opts.element.sandboxJson && !opts.element.sandboxHtml)
      throw `Either .sandboxJson or .sandboxHtml is missing for button=${opts.element.name}`;
    return opts;
  }
  main() {
  }
};
var buttonInit = getCompInit(AppDrawerButton);
function setRenderers2(self) {
  const btn = makeButton({ div: self.holder, text: self.opts.element.name, margin: "20px 20px 0px" });
  btn.attr("class", "sjpp-appdrawer-dataset-btn").on("click", async (event) => {
    event.stopPropagation();
    await self.app.dispatch({
      type: "is_apps_btn_active",
      value: false
    });
    slideDrawer(self);
    await openSandbox(self.opts.element, self.opts);
  });
}

// appdrawer/layout.js
var AppDrawerLayoutComp = class {
  static type = "layout";
  constructor(opts) {
    this.type = "layout";
    this.dom = {
      holder: opts.dom.drawerDiv,
      wrapper: opts.dom.wrapper,
      sandboxDiv: opts.dom.sandboxDiv
    };
    this.state = opts.state;
    this.hasStatePreMain = true;
  }
  async validateIndexJson() {
    const index = await this.getIndexJson();
    if (!index.elements) throw `Missing elements array`;
    if (!index.elements.length) throw `No element objects provided`;
    if (index.columnsLayout) {
      if (index.columnsLayout.length == 0) throw `Missing column objects`;
      const allGridAreaValues = index.columnsLayout.map((s) => s.gridarea);
      if (allGridAreaValues.length != new Set(allGridAreaValues).size) throw `Duplicate values for .gridarea found`;
      const allSectionIdValues = [];
      for (const col of index.columnsLayout) {
        if (!col.gridarea) throw `Missing column .gridarea for column = ${col.name}`;
        if (!col.sections || col.sections.length == 0) throw `Missing section objects for column = ${col.name}`;
        for (const section of col.sections) {
          if (!section.id)
            throw `Missing section .id in ${section.name ? `section = ${section.name}` : `column = ${col.name} array`}`;
          allSectionIdValues.push(section.id);
        }
        if (col.sections.length != new Set(col.sections).size) {
          throw `Non-unique levels in line ${lineNum}: ${JSON.stringify(levelNames)}`;
        }
      }
      if (allSectionIdValues.length != new Set(allSectionIdValues).size) throw `Duplicate values for section.id found`;
      for (const element of index.elements) {
        if (!element.section) throw `.section is missing for ${element.type} = ${element.name}`;
        if (!allSectionIdValues.some((d) => d == element.section))
          throw `section = ${element.section} for ${element.type} = ${element.name} is not a column section`;
      }
    }
    return index;
  }
  async getIndexJson() {
    const re = await dofetch3(this.app.cardsPath + "/index.json");
    if (re.error) {
      sayerror(this.dom.holder.append("div"), re.error);
      return;
    }
    return re;
  }
  validateElements() {
    const features = JSON.parse(sessionStorage.getItem("optionalFeatures")) || {};
    this.elements = this.index.elements.filter((e) => !e.hidden && (!e.configFeature || features[e.configFeature]));
  }
  async init() {
    this.index = await this.validateIndexJson();
    this.elementsRendered = false;
    setRenderers3(this);
    this.validateElements();
    this.layout = this.index.columnsLayout ? this.index.columnsLayout : null;
    this.components = {
      elements: []
    };
  }
  async main() {
    if (this.elementsRendered == true) return;
    this.elementsRendered = true;
    for (const element of this.elements) {
      const holder = select_default(this.layout ? `#${element.section} > .sjpp-element-list` : `.sjpp-element-list`);
      if (element.type == "card" || element.type == "nestedCard") {
        this.components.elements.push(
          await cardInit({
            app: this.app,
            holder: holder.style("display", "grid").style("grid-template-columns", "repeat(auto-fit, minmax(320px, 1fr))").style("gap", "10px").style("list-style", "none").style("margin", "15px 0px"),
            element,
            dom: this.opts.dom,
            state: this.state,
            sandboxDiv: this.dom.sandboxDiv
          })
        );
      } else if (element.type == "dsButton") {
        this.components.elements.push(
          await buttonInit({
            app: this.app,
            holder,
            element,
            dom: this.opts.dom,
            state: this.state,
            sandboxDiv: this.dom.sandboxDiv
          })
        );
      }
    }
  }
};
var layoutInit = getCompInit(AppDrawerLayoutComp);
function setRenderers3(self) {
  if (!self.index.columnsLayout) noDefinedLayout(self);
  if (self.index.columnsLayout) columnsLayout(self);
}
function noDefinedLayout(self) {
  const flexLayout = self.dom.wrapper.append("div").style("display", "flex").style("padding", "10px").classed("sjpp-element-list", true);
  return flexLayout;
}
function columnsLayout(self) {
  const parentGrid = self.dom.wrapper.append("div").style("display", "grid").style("grid-template-columns", "repeat(auto-fit, minmax(425px, 1fr))").style("gap", "10px").style("padding", "10px").style("text-align", "left");
  const gridareas = [];
  for (const column of self.index.columnsLayout) gridareas.push(column.gridarea);
  parentGrid.style("grid-template-areas", `"${gridareas.toString().replace(",", " ")}"`);
  for (const col of self.index.columnsLayout) {
    const newCol = parentGrid.append("div").style("grid-area", col.gridarea).classed(".sjpp-track-cols", true);
    for (const section of col.sections) addSection(section, newCol);
  }
  function addSection(section, newCol) {
    const newSection = newCol.append("div").attr("id", section.id);
    if (section.name)
      newSection.append("h5").classed("sjpp-appdrawer-cols", true).style("color", rgb(defaultcolor).darker()).text(section.name);
    newSection.append("div").classed("sjpp-element-list", true).style("padding", "10px");
    return newSection;
  }
}

// appdrawer/mainBtn.js
var MainHeadboxBtn = class {
  static type = "mainBtn";
  constructor(opts) {
    this.type = "mainBtn";
    this.opts = this.validateOpts(opts);
    this.dom = opts.dom;
    this.state = opts.state;
    this.hasStatePreMain = true;
  }
  validateOpts(opts) {
    return opts.app.opts;
  }
  getState(appState) {
    return {
      appBtnActive: appState.appBtnActive,
      duration: appState.duration,
      arrowSize: appState.arrowSize,
      arrowColor: appState.arrowColor,
      hintWidth: appState.hintWidth,
      hintPos: appState.hintPos
    };
  }
  async init(appState) {
    this.state = this.getState(appState);
    setRenderers4(this);
    this.btnRendered = false;
    this.drawerFullHeight = "";
    try {
      if (window.location.pathname == "/" && !window.location.search.length)
        await this.app.dispatch({ type: "is_apps_btn_active", value: true });
      this.components = {
        layout: []
      };
    } catch (e) {
      throw e;
    }
  }
  async main(appState) {
    if (this.state.appBtnActive == true && this.btnRendered == false) {
      this.dom.drawerDiv.style("background-color", "#f5f5f5");
      this.components.layout.push(
        await layoutInit({
          app: this.app,
          dom: this.dom,
          state: this.state
        })
      );
      setTimeout(() => {
        this.drawerFullHeight = this.dom.drawerDiv.node().getBoundingClientRect().height + 5;
      }, this.state.duration + 5);
      slideDrawer(this);
      this.btnRendered = true;
    }
    if (this.state.appBtnActive == false && this.btnRendered == true) slideDrawer(this);
  }
};
var mainBtnInit = getCompInit(MainHeadboxBtn);
function setRenderers4(self) {
  self.dom.btnWrapper.style("background-color", self.state.appBtnActive ? "#b2b2b2" : "#f2f2f2").style("color", self.state.appBtnActive ? "#fff" : "#000").on("click", async (event) => {
    event.stopPropagation();
    await self.app.dispatch({ type: "is_apps_btn_active" });
    slideDrawer(self);
    if (self.state.appBtnActive) {
      setTimeout(() => {
        self.drawerFullHeight = self.dom.drawerDiv.node().getBoundingClientRect().height + 5;
      }, self.state.duration + 5);
    }
  });
  self.dom.btn.attr("class", "sja_menuoption").attr("data-testid", "sjpp-appDrawer-main-btn").style("display", "inline-block").style("background-color", "transparent").style("color", self.state.appBtnActive ? "#fff" : "#000").style("padding", self.opts.padw_sm).style("margin", "0px 5px").style("cursor", "pointer").text("Apps");
  self.dom.drawerHint.style("position", "relative").style("display", "inline-block").style("height", self.state.arrowSize.closed + "px").style("width", self.state.appBtnActive ? self.state.hintWidth.open : self.state.hintWidth.closed).style("background-color", "transparent").style("text-align", "center").style("cursor", "pointer");
  self.dom.drawerArrow.style("position", "absolute").style("font-size", self.state.arrowSize.closed + "px").style("right", self.state.hintPos.closed.rt + "px").style("bottom", self.state.hintPos.closed.btm + "px").style("background-color", "transparent").style("color", self.state.arrowColor.closed).style("opacity", self.state.appBtnActive ? 0 : 1).style("cursor", "pointer").html("&#9660;");
  self.dom.drawerArrowOpen.style("position", "absolute").style("font-size", self.state.arrowSize.open + "px").style("left", self.state.hintPos.open.left + "px").style("bottom", self.state.hintPos.open.btm + "px").style("transform", "rotate(180deg)").style("background-color", "transparent").style("color", self.state.arrowColor.open).style("opacity", self.state.appBtnActive ? 1 : 0).style("cursor", "pointer").style("pointer-events", self.state.appBtnActive ? "auto" : "none").html("&#9660;");
  self.drawerFullHeight = self.dom.drawerRow.node().getBoundingClientRect().height + 5;
}
async function slideDrawer(self) {
  self.dom.btnWrapper.transition().duration(self.opts.state.duration).style("background-color", self.state.appBtnActive ? "#b2b2b2" : "#f2f2f2").style("color", self.state.appBtnActive ? "#fff" : "#000");
  self.dom.btn.transition().duration(self.opts.state.duration).style("color", self.state.appBtnActive ? "#fff" : "#000");
  self.dom.drawerDiv.style("display", "inline-block").transition().duration(self.opts.state.duration).style("top", self.state.appBtnActive ? "0px" : "-" + self.drawerFullHeight + "px");
  self.dom.drawerRow.transition().duration(self.opts.state.duration).style("height", self.state.appBtnActive ? self.drawerFullHeight + "px" : "0px");
  self.dom.drawerHint.transition().duration(self.opts.state.duration).style("width", self.state.appBtnActive ? self.opts.state.hintWidth.open : self.opts.state.hintWidth.closed);
  self.dom.drawerArrow.transition().duration(self.opts.state.duration).style("opacity", self.state.appBtnActive ? 0 : 1);
  self.dom.drawerArrowOpen.style("pointer-events", self.state.appBtnActive ? "auto" : "none").transition().duration(self.opts.state.duration).style("opacity", self.state.appBtnActive ? 1 : 0);
}

// appdrawer/store.js
var AppDrawerStore = class _AppDrawerStore extends StoreBase {
  static type = "store";
  constructor(opts) {
    super(opts);
    this.type = _AppDrawerStore.type;
    this.defaultState = {
      // for apps drawer animation
      duration: 500,
      hintPos: {
        open: { btm: -42, left: 13 },
        closed: { btm: 3, rt: 5 }
      },
      hintWidth: { open: "0px", closed: "18px" },
      arrowSize: { open: 42, closed: 20 },
      arrowColor: { open: "rgb(242,242,242)", closed: "rgb(85,85,85)" },
      appBtnActive: false
    };
  }
  async init() {
  }
};
var appDrawerStoreInit = getStoreInit(AppDrawerStore);
AppDrawerStore.prototype.actions = {
  is_apps_btn_active(action) {
    this.state.appBtnActive = "value" in action ? action.value : !this.state.appBtnActive;
  }
};

// appdrawer/app.js
var AppDrawerApp = class _AppDrawerApp {
  static type = "app";
  constructor(opts) {
    this.type = _AppDrawerApp.type;
    const drawerDiv = opts.drawerRow.append("div").style("position", "relative").style("margin", "0 20px").style("padding", `0 ${opts.padw_sm}`).style("display", "inline-block").style("overflow", "hidden").style("border-radius", "0px 0px 5px 5px").style("width", "93vw").classed("sjpp-drawer-div", true);
    const btnWrapper = opts.headbox.append("div").style("position", "relative").style("display", "inline-block").style("margin-left", "5px").style("margin-right", "5px").style("border-radius", "5px").classed("sjpp-apps-btn-wrapper", true);
    this.dom = {
      drawerRow: opts.drawerRow,
      drawerDiv,
      sandboxDiv: opts.sandboxDiv,
      btnWrapper,
      btn: btnWrapper.append("div"),
      drawerHint: btnWrapper.append("div"),
      drawerArrow: btnWrapper.append("div"),
      drawerArrowOpen: btnWrapper.append("div"),
      wrapper: drawerDiv.append("div")
    };
  }
  preApiFreeze(api) {
    api.cardsPath = this.opts.cardsPath;
  }
  async init() {
    try {
      this.store = await appDrawerStoreInit({ app: this.api, state: this.opts.state });
      this.state = await this.store.copyState();
      this.components = {
        mainBtn: await mainBtnInit({
          app: this.api,
          dom: this.dom,
          state: this.state,
          indexJson: this.indexJson
        })
      };
      await this.api.dispatch();
    } catch (e) {
      throw e;
    }
  }
  main() {
  }
};
var appDrawerInit = getAppInit(AppDrawerApp);

// src/header/AppHeader.ts
var AppHeader = class _AppHeader {
  static {
    /** Used in both the Help button and omni search
     * .onlySearch is used to filter out items that should not appear in the Help button
     */
    this.help = [
      {
        label: "Embed in your website",
        link: "https://github.com/stjude/proteinpaint/wiki/Embedding"
      },
      {
        label: "URL parameters",
        link: "https://github.com/stjude/proteinpaint/wiki/URL-parameters"
      },
      {
        label: "All tutorials",
        link: "https://github.com/stjude/proteinpaint/wiki/"
      },
      {
        label: "User community",
        link: "https://groups.google.com/g/proteinpaint"
      },
      {
        label: "License ProteinPaint",
        link: "https://www.stjude.org/research/why-st-jude/shared-resources/technology-licensing/technologies/proteinpaint-web-application-for-visualizing-genomic-data-sj-15-0021.html",
        onlySearch: true
      },
      {
        label: "Our Team",
        link: "https://proteinpaint.stjude.org/team/",
        onlySearch: true
      }
    ];
  }
  constructor(opts) {
    this.headtip = opts.headtip;
    this.app = opts.app;
    this.data = opts.data;
    this.jwt = opts.jwt;
    this.publications = [];
  }
  async createPublicationsList() {
    const re = await dofetch3(this.app.cardsPath + "/citations.json");
    if (re.error) console.error(`Problem retrieving ../cards/citations.json`);
    this.publications = re?.publications?.length ? re.publications.filter((d) => d.appHeaderTitle).sort((a, b) => b.year - a.year) : [];
  }
  async makeheader() {
    await this.createPublicationsList();
    const color = rgb(defaultcolor);
    const padw_lg = "13px";
    const padw_input = "5px 10px";
    const padw_sm = "7px 10px";
    const doc_width = document.documentElement.clientWidth;
    const row = this.app.holder.append("div").style("white-space", "nowrap").style(
      "border-bottom",
      doc_width > 1600 ? "solid 1px rgba(" + color.r + "," + color.g + "," + color.b + ",.3)" : ""
    );
    const headbox = row.append("div").style("margin", "10px").style("padding", "8px").style("padding-bottom", "12px").style("display", doc_width < 1600 ? "block" : "inline-block").style(
      "border-bottom",
      doc_width < 1600 ? "solid 1px rgba(" + color.r + "," + color.g + "," + color.b + ",.3)" : ""
    );
    const headinfo = row.append("div").style("display", "inline-block").style("padding", padw_sm).style("padding-left", "25px").style("font-size", ".8em").style("color", rgb(defaultcolor).darker());
    {
      const row2 = headinfo.append("div").style("padding-left", "15px");
      const link = `https://github.com/stjude/proteinpaint/pkgs/container/ppfull`;
      const version = this.data.pkgver ? `Release version: <a href="${link}" target="${this.data.pkgver}">${this.data.pkgver}</a>` : `Code date: ${this.data.codedate}`;
      row2.attr("id", "sjpp-serverstat").append("span").html(`${version}, server launched: ${this.data.launchdate || "??"}.`);
      if (this.data.hasblat) {
        row2.append("a").style("margin-left", "10px").text("Running BLAT").on("click", async (event) => {
          this.headtip.clear().showunder(event.target);
          const div = this.headtip.d.append("div").style("margin", "10px");
          const wait = div.append("div").text("Loading...");
          try {
            const data = await dofetch3("blat?serverstat=1");
            if (data.error) throw data.error;
            if (!data.lst) throw "invalid response";
            wait.remove();
            for (const i of data.lst) {
              div.append("div").text(i);
            }
          } catch (e) {
            wait.text(e.message || e);
            if (e.stack) console.error(e.stack);
          }
        });
      }
    }
    if (this.data.headermessage) {
      headinfo.append("div").html(this.data.headermessage);
    }
    headbox.append("div").text("ProteinPaint").style("display", "inline-block").style("padding", padw_lg).style("color", defaultcolor).style("font-size", "1.3em").style("font-weight", "bold");
    const omniSearch = new InputSearch({
      holder: headbox,
      tip: this.headtip,
      style: {
        padding: padw_sm,
        border: `'solid 1px ${defaultcolor}`
      },
      size: 32,
      placeholder: "Gene, position, SNP, app, or dataset",
      title: "Search by gene, SNP, position, app, or dataset",
      searchItems: async () => {
        return await searchItems(this.app, this.headtip, _AppHeader.help, this.publications, this.jwt);
      }
    });
    omniSearch.initUI();
    const genome_select_div = headbox.append("div").attr("class", "sjpp-genome-select-div").style("padding", padw_sm);
    const get_placeholder = () => {
      const currG = this.app.genomes[this.app.selectgenome.property("value")];
      const opts2Show = ["Gene", "position", "app"];
      if (currG.hasSNP) opts2Show.splice(2, 0, "SNP");
      if (Object.keys(currG.datasets).length) opts2Show.push("dataset");
      const str = opts2Show.join(", ").replace(/,(?=[^,]*$)/, ", or");
      return str;
    };
    this.app.selectgenome = genome_select_div.append("select").attr("aria-label", "Select a genome").attr("class", "sjpp-genome-select").style("padding", padw_input).style("border", "solid 1px " + defaultcolor).on("change", () => {
      this.update_genome_browser_btn(this.app);
      omniSearch.updatePlaceholder(get_placeholder());
    });
    const filterGenomes = Object.values(this.app.genomes).filter((g) => !g.hideOnClient);
    for (const n of filterGenomes) {
      this.app.selectgenome.append("option").attr("n", n.name).text(`${n.species} ${n.name}`).property("value", n.name);
    }
    this.app.genome_browser_btn = this.make_genome_browser_btn(this.app, headbox, this.jwt);
    this.app.drawer = await appDrawerInit({
      holder: this.app.holder,
      genomes: this.app.genomes,
      drawerRow: this.app.holder.append("div").style("position", "relative").style("overflow-x", "visible").style("overflow-y", "hidden").classed("sjpp-drawer-row", true),
      sandboxDiv: this.app.holder.append("div").style("margin-top", "15px").classed("sjpp-drawer-sandbox", true),
      genome_browser_btn: this.app.genome_browser_btn,
      debugmode: this.app.debugmode,
      headbox,
      padw_sm,
      cardsPath: this.app.cardsPath
    });
    headbox.append("span").classed("sja_menuoption", true).attr("id", "sjpp-header-help-btn").style("padding", padw_sm).text("Help").on("click", async (event) => {
      const p = event.target.getBoundingClientRect();
      const div = this.headtip.clear().show(p.left - 0, p.top + p.height + 5);
      await div.d.append("div").style("padding", "5px 20px").selectAll("p").data(_AppHeader.help.filter((d) => !d.onlySearch)).enter().append("p").html((d) => `<a href=${d.link} target=_blank>${d.label}</a>`);
    });
    if (this.publications.length > 0) {
      headbox.append("span").classed("sja_menuoption", true).attr("id", "sjpp-header-publications-btn").style("padding", padw_sm).style("margin", "0px 5px").text("Publications").on("click", async (event) => {
        const p = event.target.getBoundingClientRect();
        const div = this.headtip.clear().show(p.left - 150, p.top + p.height + 5);
        await div.d.append("div").style("padding", "5px 20px").selectAll("p").data(this.publications).enter().append("p").html(
          (d) => `<a href=${d.pmidURL || d.doi} target=_blank>${d.appHeaderTitle}, ${d.journal}, ${d.year}</a>`
        );
      });
    }
  }
  make_genome_browser_btn(app, headbox, jwt) {
    if (app.selectgenome.node().options.length === 0) {
      console.error(`No selected selectgenome options.`);
      return;
    }
    const padw = "8px";
    const genome_btn_div = headbox.append("span");
    const genomename = app.selectgenome.node().options[app.selectgenome.property("selectedIndex")].value;
    const g_browser_btn = genome_btn_div.attr("class", "sja_menuoption").attr("id", "genome_btn").style("padding", padw).datum(genomename).text(genomename + " genome browser").on("click", () => {
      const genomeSelected = app.selectgenome.node().value;
      const g = app.genomes[genomeSelected];
      if (!g) {
        alert("Invalid genome name: " + genomeSelected);
        return;
      }
      const sandbox_div = newSandboxDiv(app.drawer.opts.sandboxDiv);
      sandbox_div.header.text(genomeSelected + " genome browser");
      const par = {
        hostURL: app.hostURL,
        jwt,
        holder: sandbox_div.body,
        genome: g,
        chr: g.defaultcoord.chr,
        start: g.defaultcoord.start,
        stop: g.defaultcoord.stop,
        nobox: true,
        tklst: [],
        debugmode: app.debugmode
      };
      first_genetrack_tolist(g, par.tklst);
      import("./block-TTN2IQAH.js").then((b) => new b.Block(par));
      app.drawer.dispatch({ type: "is_apps_btn_active", value: false });
    });
    return g_browser_btn;
  }
  update_genome_browser_btn(app) {
    app.genome_browser_btn.text(app.selectgenome.node().value + " genome browser");
    app.genome_browser_btn.datum(app.selectgenome.node().value);
  }
};
export {
  AppHeader
};
//# sourceMappingURL=AppHeader-PXLGVCVS.js.map
