import {
  getDefaultBoxplotSettings
} from "./chunk-PCZNTK74.js";
import {
  DownloadMenu,
  ListSamples,
  PlotBase,
  axisstyle,
  controlsInit,
  defaultUiLabels,
  drawBoxplot,
  fillTermWrapper,
  filterJoin,
  getCombinedTermFilter,
  getFilterItemByTag,
  getMaxLabelWidth,
  renderTable,
  renderTerm1Label,
  term0_term2_defaultQ
} 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 "./chunk-7EMWHCVW.js";
import "./chunk-7IYJZZQI.js";
import {
  copyMerge,
  getCompInit
} from "./chunk-M3J4MINX.js";
import "./chunk-PF4DSFDR.js";
import "./chunk-QH6W3NVF.js";
import {
  isErrorResponse,
  isNumTermCollection,
  isNumericTerm,
  isSingleCellTerm
} from "./chunk-NOEAT6CX.js";
import "./chunk-4UWS5Y3N.js";
import "./chunk-DD4R5P6W.js";
import "./chunk-JNITUVXP.js";
import "./chunk-KSGA62R2.js";
import {
  axisLeft,
  axisTop
} from "./chunk-LOZEKOES.js";
import "./chunk-TOU7EVFQ.js";
import {
  format,
  linear,
  log
} from "./chunk-OAWQ6LOO.js";
import {
  decimalPlacesUntilFirstNonZero
} from "./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";

// plots/boxplot/model/Model.ts
var Model = class {
  constructor(boxplot, config) {
    this.boxplot = boxplot;
    this.config = config;
    this.state = boxplot.state;
    this.app = boxplot.app;
    this.settings = config.settings.boxplot;
  }
  async getData() {
    const data = await this.app.vocabApi.getViolinBox(
      this.setRequestOpts(),
      {},
      this.boxplot.api.getAbortSignal()
    );
    return data;
  }
  setRequestOpts() {
    const isNumericTC = this.config.term.term.type == "termCollection" && this.config.term.term.memberType == "numeric";
    const opts = {
      plotType: "box",
      tw: this.getContinousTerm(),
      filter: this.state.termfilter.filter,
      filter0: this.state.termfilter.filter0,
      orderByMedian: this.settings.orderByMedian,
      isLogScale: this.settings.isLogScale,
      removeOutliers: this.settings.removeOutliers,
      showAssocTests: this.settings.showAssocTests
    };
    if (!isNumericTC) {
      if (this.config.term2)
        opts.overlayTw = this.getContinousTerm() == this.config.term ? this.config.term2 : this.config.term;
      if (this.config.term0) opts.divideTw = this.config.term0;
    }
    return opts;
  }
  getContinousTerm() {
    if (!this.config?.term2) return this.config.term;
    if (this.config.term.term.type == "termCollection" && this.config.term.term.memberType == "numeric")
      return this.config.term;
    return isNumericTerm(this.config.term.term) && this.config.term.q.mode == "continuous" ? this.config.term : this.config.term2;
  }
};

// plots/boxplot/viewModel/LegendDataMapper.ts
var LegendDataMapper = class {
  constructor(config) {
    this.legendData = [];
    this.config = config;
    const isTerm2 = config?.term2;
    const isTerm0 = config?.term0;
    if (config.term.term.type != "termCollection" && config.term.q?.descrStats) {
      this.legendData.push({
        label: `Descriptive Statistics${isTerm2 ? `: ${config.term.term.name}` : ""}`,
        items: this.setDescrStatItems(config.term.q.descrStats)
      });
    }
    if (isTerm2 && isTerm2.q?.descrStats && !isTerm0) {
      this.legendData.push({
        label: `Descriptive Statistics: ${config.term2.term.name}`,
        items: this.setDescrStatItems(isTerm2.q.descrStats)
      });
    }
  }
  map(charts, uncomputableValues) {
    const hiddenPlots = this.getHiddenPlots(charts);
    if (this.config.term.term?.values) {
      const term1Label = this.config.term2 ? this.config.term.term.name : "Other categories";
      const term1Data = this.setHiddenCategoryItems(this.config.term, term1Label, hiddenPlots, uncomputableValues || []);
      if (term1Data) this.legendData.push(term1Data);
    }
    if (this.config.term2?.term?.values) {
      const term2Data = this.setHiddenCategoryItems(
        this.config.term2,
        this.config.term2.term.name,
        hiddenPlots,
        uncomputableValues || []
      );
      if (term2Data) this.legendData.push(term2Data);
    }
    return this.legendData;
  }
  getHiddenPlots(charts) {
    const hiddenPlots = Object.values(charts).reduce((plotMap, chart) => {
      for (const p of chart.plots ?? []) {
        if (!p.isHidden || plotMap.has(p.key)) continue;
        plotMap.set(p.key, {
          key: p.key,
          text: p.key,
          isHidden: true,
          isPlot: true
        });
      }
      return plotMap;
    }, /* @__PURE__ */ new Map()).values();
    return Array.from(hiddenPlots);
  }
  setDescrStatItems(stats) {
    return Object.values(stats).map((s) => ({
      key: s.key,
      text: `${s.label}: ${s.value}`,
      isHidden: false,
      isPlot: false
    }));
  }
  setHiddenCategoryItems(tw, label, hiddenPlots, uncomputableValues) {
    const termData = { label, items: [] };
    if (hiddenPlots.length) {
      for (const key of Object.keys(tw.q.hiddenValues || {})) {
        const plot = hiddenPlots.find((p) => p.key === key);
        if (plot) termData.items.push(plot);
      }
    }
    if (uncomputableValues && uncomputableValues.length) {
      for (const v of Object.values(tw.term.values || {})) {
        const uncomputableItem = uncomputableValues.find((u) => u.label === v.label);
        if (uncomputableItem) {
          termData.items.push({
            key: uncomputableItem.label,
            text: `${uncomputableItem.label}, n=${uncomputableItem.value}`,
            isHidden: true,
            isPlot: false
          });
        }
      }
    }
    return termData.items.length ? termData : null;
  }
};

// plots/boxplot/viewModel/ChartsDataMapper.ts
var ChartsDataMapper = class {
  /** Top padding for the svg */
  #topPad = 20;
  /** Bottom padding for the svg */
  #bottomPad = 25;
  /** Horizontal, or right and left padding */
  #horizPad = 120;
  /** For outliers, set a radius rather than using the default. */
  #outRadius = 5;
  /** Offset applied when divide by term is present
   * Creates space for the subtitle*/
  #divideByOffset = 20;
  constructor(data, settings, maxLabelLgth, useDefaultSettings) {
    this.validateInputData(data);
    this.absMin = data.absMin;
    this.absMax = data.absMax;
    this.charts = Object.values(data.charts);
    this.settings = settings;
    if (useDefaultSettings) {
      const { rowHeight, rowSpace } = this.getRowSettings(this.charts);
      this.rowHeight = rowHeight;
      this.rowSpace = rowSpace;
    } else {
      this.rowHeight = settings.rowHeight;
      this.rowSpace = settings.rowSpace;
    }
    this.totalLabelSize = maxLabelLgth + settings.labelPad;
    this.totalBoxSize = this.rowHeight + this.rowSpace;
  }
  /** Same checks are in the server route */
  validateInputData(data) {
    if (!data) throw new Error("No data provided to ChartDataMapper");
    if (!data.charts) throw new Error("No charts data provided to ChartDataMapper");
    if (!Array.isArray(data.charts) && typeof data.charts !== "object")
      throw new Error("Invalid charts data provided to ChartDataMapper");
    if (data.absMin === void 0 || data.absMax === void 0)
      throw new Error("Missing absMin or absMax in data provided to ChartDataMapper");
  }
  /** Set the row settings based on all plots */
  getRowSettings(charts) {
    let totalNumPlots = 0;
    for (const chart of charts) {
      totalNumPlots = totalNumPlots + chart.plots.filter((p) => !p.isHidden).length;
    }
    const isLargePlotCount = totalNumPlots > 20;
    const rowHeight = totalNumPlots > 10 ? isLargePlotCount ? 20 : 35 : 50;
    const rowSpace = totalNumPlots > 10 ? isLargePlotCount ? 10 : 12 : 15;
    return { rowHeight, rowSpace };
  }
  map(config) {
    const chartData = {};
    for (const chart of this.charts) {
      let incrPad = 40;
      const plotDim = this.setPlotDimensions(chart, config, this.settings, incrPad);
      if (config?.term0) incrPad += this.#divideByOffset;
      incrPad += 30;
      chartData[chart.chartId] = {
        plotDim,
        plots: this.setPlotData(chart, config, this.settings, incrPad),
        wilcoxon: chart?.wilcoxon || null
      };
    }
    return chartData;
  }
  setPlotDimensions(chart, config, settings, incrPad) {
    const svg = this.setSvgDimensions(settings, chart, incrPad, config);
    const plotCenter = this.totalLabelSize + settings.plotLength / 2;
    const plotDim = {
      //Add 1 to the max is big enough so the upper line to boxplot isn't cutoff
      domain: [this.absMin, this.absMax <= 1 ? this.absMax : this.absMax + 1],
      range: [0, settings.plotLength],
      svg,
      subtitle: this.setSubtitleDimensions(
        config,
        settings,
        svg.height,
        chart.chartId,
        chart.sampleCount,
        plotCenter,
        incrPad
      ),
      title: this.setTitleDimensions(config, settings, svg.height, plotCenter, incrPad),
      axis: {
        x: settings.isVertical ? this.#horizPad / 2 + incrPad + this.#topPad : this.totalLabelSize,
        y: this.#topPad + (settings.isVertical ? settings.labelPad : incrPad + 20),
        values: (ticks) => {
          if (settings.isLogScale) return this.filterTickValues(ticks);
          return ticks;
        },
        format: (d) => {
          if (settings.isLogScale) {
            if (Number.isInteger(d)) return format(".0f")(d);
            const dec = decimalPlacesUntilFirstNonZero(d);
            if (dec > 1) return format(`.${dec + 1}f`)(d);
            return format(".2f")(d);
          }
          return d.toString();
        }
      }
    };
    if (config?.term0) {
      if (settings.isVertical) plotDim.axis.x += this.#divideByOffset;
      else plotDim.axis.y += this.#divideByOffset;
    }
    return plotDim;
  }
  setSvgDimensions(settings, chart, incrPad, config) {
    let plotsSpace = chart.plots.filter((p) => !p.isHidden).length * this.totalBoxSize + this.#topPad + this.#bottomPad + incrPad;
    if (config?.term0) plotsSpace += this.#divideByOffset + incrPad;
    const length = settings.plotLength + this.totalLabelSize + this.#horizPad / 2;
    return {
      width: settings.isVertical ? plotsSpace + this.#horizPad : length,
      height: settings.isVertical ? length : plotsSpace
    };
  }
  setSubtitleDimensions(config, settings, height, chartId, sampleCount, plotCenter, incrPad) {
    const dim = {
      x: null,
      y: null,
      text: null
    };
    if (config.term0) {
      dim.x = settings.isVertical ? this.#horizPad / 2 : plotCenter;
      dim.y = settings.isVertical ? height - plotCenter - this.#horizPad / 2 : this.#topPad + incrPad / 2;
      dim.text = `${getChartSubtitle(config, chartId)} (n=${sampleCount})`;
    }
    return dim;
  }
  setTitleDimensions(config, settings, height, plotCenter, incrPad) {
    const dim = {
      x: settings.isVertical ? this.#horizPad / 2 : plotCenter,
      y: settings.isVertical ? height - plotCenter - this.#horizPad / 2 : this.#topPad + incrPad / 2,
      text: config.term.q.mode == "continuous" ? config.term.term.name : config.term2.term.name
    };
    if (config?.term0) {
      if (settings.isVertical) dim.x += this.#divideByOffset + 10;
      else dim.y += this.#divideByOffset + 10;
    }
    return dim;
  }
  filterTickValues(ticks) {
    if (!ticks || ticks.length == 0) {
      throw new Error("No ticks provided to filterTickValues");
    }
    const significantLessThanOne = ticks.filter((t) => t < 1).length / ticks.length;
    const range = ticks[ticks.length - 1] - ticks[0];
    const spread = range > 1e3 ? 4 : range > 100 ? 3 : 2;
    const formattedTicks = ticks.filter((t, i) => {
      if (t === 0 || i == ticks.length - 1 && i % spread !== 0) return t;
      else if (t <= 1 && significantLessThanOne > 0.5) {
        if (i % 5 === 0) return t;
      } else if (i % spread === 0) return t;
    });
    return formattedTicks;
  }
  setPlotData(chart, config, settings, incrPad) {
    const plots = structuredClone(chart.plots.filter((p) => !p.isHidden));
    for (const plot of plots) {
      let color;
      const term2 = config.term2;
      if (term2) {
        if (term2.q.type == "predefined-groupset" || term2.q.type == "custom-groupset") {
          const groupset = term2.q.type == "predefined-groupset" ? term2.term.groupsetting.lst[term2.q.predefined_groupset_idx] : term2.q.customset;
          if (!groupset) throw "groupset is missing";
          const group = groupset.groups.find((g) => g.name == plot.seriesId);
          if (group?.color) color = group.color;
        } else {
          color = term2.term.values?.[plot.seriesId]?.color;
        }
      }
      if (!color) color = settings.color;
      if (!plot.color) plot.color = color;
      if (settings.displayMode == "dark") plot.color = rgb(plot.color).brighter(0.75);
      if (plot.boxplot.out.length) {
        const maxOut = plot.boxplot.out.reduce(
          (a, b) => Math.max(a.value, b.value)
        );
        if (maxOut && maxOut.value > chart.absMax) chart.absMax = maxOut.value;
        plot.boxplot.radius = this.#outRadius;
      }
      plot.boxplot.rectFill = settings.displayMode == "dark" ? "black" : settings.displayMode == "filled" ? color : "white";
      plot.x = settings.isVertical ? this.#horizPad / 2 + incrPad : this.totalLabelSize;
      plot.y = this.#topPad + (settings.isVertical ? settings.plotLength + settings.labelPad : incrPad);
      incrPad += this.totalBoxSize;
      plot.chartId = chart.chartId || " ";
    }
    return plots;
  }
};
function getChartSubtitle(config, chartId) {
  if (!config.term0) return chartId;
  return config.term0.term.values && chartId in config.term0.term.values ? config.term0.term.values[chartId].label : chartId;
}

// plots/boxplot/viewModel/ViewModel.ts
var ViewModel = class {
  constructor(config, data, settings, maxLabelLgth, useDefaultSettings) {
    const chartsMapper = new ChartsDataMapper(data, settings, maxLabelLgth, useDefaultSettings);
    const legendMapper = new LegendDataMapper(config);
    const charts = chartsMapper.map(config);
    this.rowHeight = chartsMapper.rowHeight;
    this.rowSpace = chartsMapper.rowSpace;
    this.viewData = {
      backgroundColor: settings.displayMode == "dark" ? "black" : "white",
      textColor: settings.displayMode == "dark" ? "white" : "black",
      charts,
      legend: legendMapper.map(data.charts, data.uncomputableValues || [])
    };
  }
};

// plots/boxplot/interactions/BoxPlotInteractions.ts
var BoxPlotInteractions = class {
  constructor(app, dom, id, getResData) {
    this.app = app;
    this.dom = dom;
    this.id = id;
    this.getResData = getResData;
  }
  help() {
    window.open("https://github.com/stjude/proteinpaint/wiki/Box-plot");
  }
  /** Option to add a global filter from the box plot label menu. */
  addFilter(plot) {
    const state = this.app.getState();
    const sampleList = this.initListSamples(plot);
    const filterUiRoot = getFilterItemByTag(state.termfilter.filter, "filterUiRoot");
    const filter = filterJoin([filterUiRoot, sampleList.tvslst]);
    filter.tag = "filterUiRoot";
    this.app.dispatch({
      type: "filter_replace",
      filter
    });
  }
  /** Option to hide a plot from the box plot label menu. */
  hidePlot(plot) {
    const plotConfig = this.getPlotConfig();
    const config = structuredClone(plotConfig);
    const contTerm = config.term.q.mode == "continuous" ? "term2" : "term";
    if (!config[contTerm].q.hiddenValues) config[contTerm].q.hiddenValues = {};
    config[contTerm].q.hiddenValues[plot.key] = 1;
    this.app.dispatch({
      type: "plot_edit",
      id: this.id,
      config
    });
  }
  /** Trigger when clicking on a hidden plot in the legend */
  unhidePlot(item) {
    const plotConfig = this.getPlotConfig();
    const config = structuredClone(plotConfig);
    const contTerm = config.term.q.mode == "continuous" ? "term2" : "term";
    delete config[contTerm].q.hiddenValues[item.key];
    this.app.dispatch({
      type: "plot_edit",
      id: this.id,
      config
    });
  }
  initListSamples(plot) {
    const state = this.app.getState();
    const plotConfig = this.getPlotConfig();
    const config = structuredClone(plotConfig);
    const bins = this.getResData().bins;
    const start = this.getResData().absMin;
    const end = this.getResData().absMax;
    const contTerm = config.term.q.mode == "continuous" ? config.term : config.term2;
    const term = config.term != contTerm ? contTerm : config.term;
    const term2 = config.term != contTerm ? config.term : config.term2;
    const sampleList = new ListSamples({
      app: this.app,
      termfilter: state.termfilter,
      term,
      term2,
      term0: config.term0,
      plot,
      bins,
      start,
      end
    });
    return sampleList;
  }
  /** Option from box plot label to show the samples in a table within the tooltip. */
  async listSamples(plot) {
    const sampleList = this.initListSamples(plot);
    const data = await sampleList.getData();
    const [rows, columns] = sampleList.setTableData(data);
    return [rows, columns];
  }
  /** Callback for color picker in plot(s) label menu */
  updatePlotColor(plot, color) {
    if (!plot.seriesId) return;
    const plotConfig = this.getPlotConfig();
    const config = structuredClone(plotConfig);
    config.term2.term.values[plot.seriesId].color = color;
    this.app.dispatch({
      type: "plot_edit",
      id: this.id,
      config
    });
  }
  getPlotConfig() {
    return this.app.getState().plots.find((p) => p.id === this.id);
  }
  clearDom() {
    this.dom.error.style("padding", "").text("");
    this.dom.charts.selectAll("*").remove();
    this.dom.legend.selectAll("*").remove();
  }
};

// plots/boxplot/view/LegendRender.ts
var LegendRenderer = class {
  constructor(legendDiv, legendData, interactions, textColor) {
    this.interactions = interactions;
    this.textColor = textColor;
    this.renderLegend(legendDiv, legendData);
  }
  renderLegend(legendDiv, legendData) {
    legendDiv.attr("id", "sjpp-boxplot-legend");
    for (const section of legendData) {
      legendDiv.append("div").style("opacity", "0.75").style("color", this.textColor).text(section.label);
      const sectionDiv = legendDiv.append("div").style("padding-left", "10px");
      for (const item of section.items) {
        this.addItem(item, sectionDiv);
      }
    }
  }
  addItem(item, sectionDiv) {
    const legendItem = sectionDiv.append("div");
    if (item.isPlot) {
      legendItem.append("div").style("display", "inline-block").style("margin-right", "3px").style("position", "relative").style("vertical-align", "middle").html(`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="${this.textColor}" class="bi bi-arrow-counterclockwise" viewBox="0 0 16 16" style="vertical-align: middle; display: block; margin: auto;">
                <path stroke="#000" stroke-width="0.25" fill-rule="evenodd" d="M8 3a5 5 0 1 1-4.546 2.914.5.5 0 0 0-.908-.417A6 6 0 1 0 8 2v1z"/>
                <path d="M8 4.466V.534a.25.25 0 0 0-.41-.192L5.23 2.308a.25.25 0 0 0 0 .384l2.36 1.966A.25.25 0 0 0 8 4.466z"/>
                </svg>`);
    }
    legendItem.append("div").style("display", "inline-block").style("color", this.textColor).style("text-decoration", item.isHidden ? "line-through" : "").text(item.text);
    if (item.isPlot) {
      legendItem.attr("aria-label", `Click to unhide plot`).on("click", () => {
        this.interactions.unhidePlot(item);
      });
    }
  }
};

// plots/boxplot/view/BoxPlotToolTips.ts
var BoxPlotToolTips = class {
  constructor(plot, g, tip, isVertical) {
    this.tablePadding = "3px";
    this.plot = plot;
    this.g = g;
    this.boxplot = plot.boxplot;
    this.isVertical = isVertical;
    this.tip = tip;
    this.addLabelTooltip();
    this.addOutliersTooltip();
  }
  //Add rendering preferences here to maintain styles
  //across all tooltip instances
  addText(text) {
    this.tip.d.append("div").text(text);
  }
  addLabelTooltip() {
    if (Object.keys(this.plot.descrStats).length < 2) return;
    this.boxplot.labelG.on("mouseover", (event) => {
      this.tip.clear();
      if (this.isVertical) this.tip.show(event.clientX, event.clientY);
      else this.tip.showunder(this.boxplot.labelG.node());
      const table = this.tip.d.append("table").attr("class", "sja_simpletable");
      table.append("tr").style("text-align", "center").append("td").attr("colspan", 2).style("padding", this.tablePadding).text(this.plot.key);
      for (const stat of Object.values(this.plot.descrStats)) {
        const row = table.append("tr");
        row.append("td").style("padding", this.tablePadding).style("opacity", 0.5).text(stat.label);
        row.append("td").style("padding", this.tablePadding).style("text-align", "center").style("opacity", stat.value === null || stat.value === void 0 ? 0.5 : 1).text(stat.value ?? "N/A");
      }
    });
    this.boxplot.labelG.on("mouseout", () => {
      this.tip.hide();
    });
  }
  // addLineToolTips() {
  // 	const addToolTips = (elem, text: string) => {
  // 		const elemBBox = elem.node().getBBox()
  // 		//Add an expanded area for the tooltip
  // 		//Easier for user to hover over
  // 		this.g
  // 			.append('rect')
  // 			.attr('x', elemBBox.x - 10)
  // 			.attr('y', elemBBox.y - 10)
  // 			.attr('width', elemBBox.width + 20)
  // 			.attr('height', elemBBox.height + 20)
  // 			.attr('fill', 'transparent')
  // 			.style('pointer-events', 'all')
  // 			.on('mouseover', () => {
  // 				this.tip.clear().showunder(elem.node())
  // 				this.addText(text)
  // 			})
  // 			.on('mouseout', () => {
  // 				this.tip.hide()
  // 			})
  // 	}
  // 	if (this.boxplot.linep50) {
  // 		const median = this.plot.descrStats.find((d: any) => d.id == 'median')
  // 		if (!median) throw `Missing median value for ${this.plot.key}`
  // 		addToolTips(this.boxplot.linep50, `Median: ${median.value}`)
  // 	}
  // 	if (this.boxplot.linew1) {
  // 		addToolTips(this.boxplot.linew1, `${this.boxplot.w1}`)
  // 	}
  // 	if (this.boxplot.linew2) {
  // 		addToolTips(this.boxplot.linew2, `${this.boxplot.w2}`)
  // 	}
  // }
  addOutliersTooltip() {
    this.g.selectAll("circle").data(this.boxplot.out).each((d, i, nodes) => {
      const circle = select_default(nodes[i]);
      circle.on("mouseover", () => {
        this.tip.clear().showunder(circle.node());
        this.addText(d.value);
      });
      circle.on("mouseout", () => {
        this.tip.hide();
      });
    });
  }
};

// plots/boxplot/view/BoxPlotLabelMenu.ts
var BoxPlotLabelMenu = class {
  constructor(plot, app, interactions, tip, isVertical) {
    const options = [];
    if (app.getState().nav.header_mode === "with_tabs")
      options.push({
        text: `Add filter: ${plot.key}`,
        isVisible: () => true,
        callback: () => interactions.addFilter(plot)
      });
    options.push({
      text: `Hide ${plot.key}`,
      isVisible: () => true,
      callback: () => interactions.hidePlot(plot)
    });
    if (app.getState().nav.header_mode === "with_tabs")
      options.push({
        text: `List samples`,
        isVisible: (state) => state.termdbConfig.displaySampleIds && app.vocabApi.hasVerifiedToken(),
        callback: async (event) => {
          if (isVertical) tip.clear().show(event.clientX, event.clientY);
          else tip.clear().showunder(plot.boxplot.labelG.node());
          const [rows, columns] = await interactions.listSamples(plot);
          const tableDiv = tip.d.append("div");
          renderTable({
            rows,
            columns,
            div: tableDiv,
            maxHeight: "35vh",
            resize: true,
            showLines: true,
            dataTestId: "sjpp-listsampletable"
          });
        }
      });
    plot.boxplot.labelG.on("click", (event) => {
      tip.clear();
      if (isVertical) tip.show(event.clientX, event.clientY);
      else tip.showunder(plot.boxplot.labelG.node());
      const state = app.getState();
      for (const opt of options) {
        if (!opt.isVisible(state)) continue;
        tip.d.append("div").classed("sja_menuoption", true).text(opt.text).on("click", (event2) => {
          tip.hide();
          opt.callback(event2);
        });
      }
      if (plot.color) {
        tip.d.append("div").style("padding", "5px 10px").style("display", "inline-block").text("Color:").append("input").attr("type", "color").property("value", rgb(plot.color).formatHex()).on("change", (event2) => {
          interactions.updatePlotColor(plot, event2.target.value);
          tip.hide();
        });
      }
    });
  }
};

// plots/boxplot/view/AssociationTableRender.ts
var AssociationTableRender = class {
  constructor(div, data) {
    const wrapper = div.style("vertical-align", "top").style("margin-top", "30px");
    wrapper.append("div").text("Group comparisons (Wilcoxon's rank sum test)").style("font-weight", "600").style("text-align", "center");
    const tableDiv = wrapper.append("div").style("margin-top", "5px");
    renderTable({
      div: tableDiv,
      columns: [{ label: "Group 1" }, { label: "Group 2" }, { label: "P-Value" }],
      rows: data
    });
  }
};

// plots/boxplot/view/ChartRender.ts
var ChartRender = class {
  constructor(dom, settings, app, interactions, chart, backgroundColor, textColor) {
    this.app = app;
    this.interactions = interactions;
    this.textColor = textColor;
    const plotDim = chart.plotDim;
    dom.svg.transition().attr("width", plotDim.svg.width).attr("height", plotDim.svg.height).style("fill", backgroundColor);
    const setScaleFunc = settings.isLogScale ? log().base(10) : linear();
    const scale = setScaleFunc.domain(plotDim.domain).range(plotDim.range);
    this.renderTitles(plotDim, dom, settings);
    this.renderBoxPlots(dom, chart, scale, settings);
    this.renderAxis(plotDim, dom, scale, settings);
    if (chart.wilcoxon && dom.assocTableDiv) {
      new AssociationTableRender(dom.assocTableDiv, chart.wilcoxon);
    }
  }
  renderTitles(plotDim, dom, settings) {
    const transformStr = `translate(${plotDim.title.x}, ${plotDim.title.y})${settings.isVertical ? `,rotate(-90)` : ""}`;
    dom.title.attr("class", "sjpp-boxplot-title").style("font-weight", 600).attr("text-anchor", "middle").attr("transform", transformStr).attr("fill", this.textColor).text(plotDim.title.text.length > 80 ? plotDim.title.text.slice(0, 80) + "..." : plotDim.title.text);
    if (plotDim.subtitle.text) {
      const subTransformStr = `translate(${plotDim.subtitle.x}, ${plotDim.subtitle.y})${settings.isVertical ? `,rotate(-90)` : ""}`;
      dom.subtitle.attr("class", "sjpp-boxplot-subtitle").style("font-size", "1.1em").attr("text-anchor", "middle").attr("transform", subTransformStr).attr("fill", this.textColor).text(plotDim.subtitle.text.length > 80 ? plotDim.subtitle.text.slice(0, 80) + "..." : plotDim.subtitle.text);
    }
  }
  renderAxis(plotDim, dom, scale, settings) {
    if (settings.isVertical) scale.range([scale.range()[1], scale.range()[0]]);
    const ticks = scale.ticks();
    const tickValues = plotDim.axis.values(ticks);
    dom.axis.attr("class", "sjpp-boxplot-axis").attr("transform", `translate(${plotDim.axis.x}, ${plotDim.axis.y})`).transition().call(
      settings.isVertical ? axisLeft(scale).tickValues(tickValues).tickFormat((d) => plotDim.axis.format(d)).tickPadding(8) : axisTop(scale).tickValues(tickValues).tickFormat((d) => plotDim.axis.format(d))
    );
    axisstyle({
      axis: dom.axis,
      showline: true,
      fontsize: 12,
      color: this.textColor
    });
  }
  renderBoxPlots(dom, chart, scale, settings) {
    for (const plot of chart.plots) {
      const g = dom.boxplots.append("g").attr("class", "sjpp-boxplot-plot").attr("padding", "5px");
      drawBoxplot({
        bp: plot.boxplot,
        g,
        color: settings.displayMode == "filled" ? "black" : plot.color,
        scale,
        rowheight: settings.rowHeight,
        labpad: settings.labelPad,
        labColor: this.textColor
      });
      const transformStr = `translate(${plot.x}, ${plot.y})${settings.isVertical ? `, rotate(-90)` : ""}`;
      g.attr("transform", transformStr);
      if (settings.isVertical) {
        g.select("text").attr("transform", "rotate(45)");
      }
      new BoxPlotToolTips(plot, g, dom.tip, settings.isVertical);
      const numCollection = isNumTermCollection(this.interactions.getPlotConfig().term.term);
      if (!numCollection && chart.plots.length > 1) {
        const labelMenuTip = new Menu({ padding: "" });
        new BoxPlotLabelMenu(
          plot,
          this.app,
          this.interactions,
          labelMenuTip,
          settings.isVertical
          /*chart*/
        );
      }
    }
  }
};

// plots/boxplot/view/View.ts
var View = class {
  constructor(viewData, settings, dom, app, interactions) {
    this.app = app;
    this.dom = dom;
    this.interactions = interactions;
    this.settings = settings;
    if (!viewData || !viewData.charts) return;
    dom.div.style("background-color", viewData.backgroundColor);
    for (const chart of Object.values(viewData.charts)) {
      const chartWrapper = dom.charts.append("div").attr("class", "sjpp-boxplot-chart-wrapper");
      const svg = chartWrapper.append("svg").attr("class", "sjpp-boxplot-svg");
      chart["svg"] = svg;
      const chartDom = {
        svg,
        tip: dom.tip
      };
      if (chart.plotDim.subtitle.text) {
        chartDom.subtitle = svg.append("text");
      }
      chartDom.title = svg.append("text");
      chartDom.axis = svg.append("g");
      chartDom.boxplots = svg.append("g").attr("class", "sjpp-boxplot-boxplots");
      if (chart.wilcoxon) {
        chartDom.assocTableDiv = chartWrapper.append("div").attr("class", "sjpp-boxplot-wilcoxon").style("display", "inline-block");
      }
      new ChartRender(
        chartDom,
        this.settings,
        this.app,
        this.interactions,
        chart,
        viewData.backgroundColor,
        viewData.textColor
      );
    }
    new LegendRenderer(dom.legend, viewData.legend, interactions, viewData.textColor);
  }
};

// plots/boxplot/BoxPlotControlInputs.ts
function setBoxPlotControlInputs(state, app, opts, getCharts, useDefaultSettings) {
  const controlLabels = state.config.controlLabels;
  if (!controlLabels) throw new Error("controls labels not found");
  let specialCase = "default";
  if (isSingleCellTerm(state.config.term.term)) {
    if (!state.config.term.term.sample) console.error("single cell term without sample specified in config, unexpected");
    else {
      specialCase = {
        type: "singleCell",
        config: { sample: state.config.term.term.sample }
      };
    }
  }
  const inputs = [
    {
      type: "term",
      configKey: "term",
      chartType: "boxplot",
      usecase: { target: "boxplot", detail: "term" },
      label: controlLabels.term1?.label || renderTerm1Label,
      vocabApi: app.vocabApi,
      menuOptions: "edit",
      // Hide term1 control for termCollection; later reenable when tw edit menu works to allow choosing subset of member terms
      // and take into account state changes.
      getDisplayStyle: (plot) => isNumTermCollection(plot.config.term?.term) ? "none" : ""
    },
    {
      type: "term",
      configKey: "term2",
      chartType: "boxplot",
      usecase: { target: "boxplot", detail: "term2", specialCase },
      title: controlLabels.term2.title || controlLabels.term2.label,
      label: controlLabels.term2.label,
      vocabApi: app.vocabApi,
      numericEditMenuVersion: opts.numericEditMenuVersion || ["continuous", "discrete"],
      defaultQ4fillTW: term0_term2_defaultQ,
      // Hide term2 control when numeric termCollection is detected
      // and take into account state changes.
      getDisplayStyle: (plot) => isNumTermCollection(plot.config.term?.term) ? "none" : ""
    },
    {
      type: "term",
      configKey: "term0",
      chartType: "boxplot",
      usecase: { target: "boxplot", detail: "term0", specialCase },
      title: controlLabels.term0.title || controlLabels.term0.label,
      label: controlLabels.term0.label,
      vocabApi: app.vocabApi,
      // by default, do not allow continuous mode for divide-by term, since
      // it will create a separate violin-overlay group per unique float or integer value
      // and there will nonsensical tens/hundreds of these charts based on the cohort size
      numericEditMenuVersion: opts.numericEditMenuVersion || ["discrete"],
      defaultQ4fillTW: term0_term2_defaultQ,
      // Hide term0 control when numeric termCollection is detected
      // and take into account state changes.
      getDisplayStyle: (plot) => isNumTermCollection(plot.config.term?.term) ? "none" : ""
    },
    {
      label: "Order by",
      title: "Order box plots by parameters",
      type: "radio",
      chartType: "boxplot",
      settingsKey: "orderByMedian",
      options: [
        { label: "Default", value: false },
        { label: "Median values", value: true }
      ],
      getDisplayStyle: () => {
        const charts = getCharts();
        let style = "none";
        for (const k of Object.keys(charts)) {
          const chart = charts[k];
          if (chart.plots.length > 1) style = "";
        }
        return style;
      }
    },
    {
      label: "Scale",
      title: "Change the axis scale",
      type: "radio",
      chartType: "boxplot",
      settingsKey: "isLogScale",
      options: [
        { label: "Linear", value: false },
        { label: "Log10", value: true }
      ]
    },
    {
      label: "Orientation",
      title: "Change the orientation of the box plots",
      type: "radio",
      chartType: "boxplot",
      settingsKey: "isVertical",
      options: [
        { label: "Horizontal", value: false },
        { label: "Vertical", value: true }
      ]
    },
    {
      label: "Plot length",
      title: "Set the plot length of the entire plot in pixels, >=200",
      type: "number",
      chartType: "boxplot",
      settingsKey: "plotLength",
      debounceInterval: 500,
      min: 200,
      step: 10
    },
    {
      label: "Box size",
      title: "Set the box size or thickness in pixels of each box plot between 20 and 50",
      type: "number",
      chartType: "boxplot",
      settingsKey: "rowHeight",
      step: 1,
      max: 50,
      min: 20,
      debounceInterval: 500,
      processInput: (val) => {
        if (useDefaultSettings == true) useDefaultSettings = false;
        return val;
      }
    },
    {
      label: "Plots padding",
      title: "Set the space between each box plot. Number must be between 10 and 20",
      type: "number",
      chartType: "boxplot",
      settingsKey: "rowSpace",
      step: 1,
      max: 20,
      min: 10,
      debounceInterval: 500,
      processInput: (val) => {
        if (useDefaultSettings == true) useDefaultSettings = false;
        return val;
      }
    },
    {
      label: "Default color",
      type: "color",
      chartType: "boxplot",
      settingsKey: "color",
      getDisplayStyle: () => {
        const charts = getCharts();
        let style = "";
        for (const k of Object.keys(charts)) {
          const chart = charts[k];
          if (chart.plots.length > 1) style = "none";
        }
        return style;
      }
    },
    {
      label: "Display mode",
      title: "Apply a dark theme to the plot",
      type: "radio",
      chartType: "boxplot",
      settingsKey: "displayMode",
      options: [
        { label: "Default", value: "default" },
        { label: "Filled", value: "filled" },
        { label: "Dark mode", value: "dark" }
      ]
    },
    {
      label: "Show association tests",
      boxLabel: "",
      type: "checkbox",
      chartType: "boxplot",
      settingsKey: "showAssocTests",
      title: `Show association tests next to the box plots.`,
      getDisplayStyle: (plot) => {
        return plot?.term2 ? "" : "none";
      }
    }
  ];
  if (state.termdbConfig?.boxplots?.removeOutliers) {
    inputs.push({
      label: "Remove outliers",
      boxLabel: "",
      type: "checkbox",
      chartType: "boxplot",
      settingsKey: "removeOutliers",
      title: `Option to remove outliers from the analysis`
    });
  }
  return inputs;
}

// plots/boxplot/BoxPlot.ts
var TdbBoxplot = class _TdbBoxplot extends PlotBase {
  constructor(opts, api) {
    super(opts);
    this.useDefaultSettings = true;
    this.configTermKeys = ["term", "term0", "term2"];
    this.opts = opts;
    this.api = api;
    this.type = _TdbBoxplot.type;
    this.components = {
      controls: {}
    };
    const holder = opts.holder.classed("sjpp-boxplot-main", true);
    const { controls, errdiv, loadingDiv, mainDiv, renderedData, charts, legendDiv } = this.getStandardDomLayout(
      holder,
      opts
    );
    this.dom = {
      controls,
      div: mainDiv,
      error: errdiv,
      loading: loadingDiv,
      renderedData,
      charts: charts.attr("class", "sjpp-boxplot-charts").style("display", "flex").style("flex-direction", "row").style("flex-wrap", "wrap").style("max-width", "100vw"),
      legend: legendDiv.append("div").attr("class", "sjpp-boxplot-legend").style("margin-top", "25px"),
      tip: new Menu()
    };
    if (opts.header) this.dom.header = opts.header.html("Box plot");
  }
  static {
    this.type = "boxplot";
  }
  async setControls() {
    const state = this.getState(this.app.getState());
    const inputs = setBoxPlotControlInputs(
      state,
      this.app,
      this.opts,
      () => {
        return this.data?.charts || [];
      },
      this.useDefaultSettings
    );
    this.components.controls = await controlsInit({
      app: this.app,
      id: this.id,
      holder: this.dom.controls.style("display", "inline-block"),
      inputs
    });
    this.components.controls.on("downloadClick.boxplot", (event) => {
      this.download(event);
    });
    this.components.controls.on("helpClick.boxplot", () => {
      this.interactions.help();
    });
    if (state.vocab.dslabel.toLowerCase() == "gdc") {
      this.dom.controls.select('div[aria-label="Documentation"]').remove();
    }
  }
  reactsTo(action) {
    if (action.type.startsWith("plot_")) {
      return (action.id === this.id || action.id == this.parentId) && (!action.config?.childType || action.config?.childType == this.type);
    }
    return true;
  }
  getState(appState) {
    const config = appState.plots.find((p) => p.id === this.id);
    if (!config) {
      throw new Error(
        `No plot with id='${this.id}' found. Did you set this.id before this.api = getComponentApi(this)?`
      );
    }
    const parentConfig = appState.plots.find((p) => p.id === this.parentId);
    const termfilter = getCombinedTermFilter(appState, config.filter || parentConfig?.filter);
    return {
      termdbConfig: appState.termdbConfig,
      termfilter,
      vocab: appState.vocab,
      config: Object.assign({}, config, {
        settings: {
          boxplot: config.settings.boxplot
        }
      })
    };
  }
  async init() {
    this.dom.div.style("display", "inline-block").style("margin-left", "20px");
    this.interactions = new BoxPlotInteractions(this.app, this.dom, this.id, () => {
      return this.data;
    });
    await this.setControls();
  }
  async main() {
    const c = this.state.config;
    if (c.childType != this.type && c.chartType != this.type) return;
    if (!this.interactions) throw new Error("Interactions not initialized [box plot main()]");
    const config = await this.getMutableConfig();
    const settings = config.settings.boxplot;
    const model = new Model(this, config);
    try {
      this.toggleLoadingDiv("block", "block");
      const data = await model.getData();
      if (isErrorResponse(data)) throw new Error(data.error);
      config.term.q.descrStats = data.descrStats;
      config.bins = data.bins;
      if (!data.charts || !Object.keys(data.charts).length) {
        this.interactions.clearDom();
        this.dom.error.style("padding", "20px 20px 20px 60px").text("No visible box plot data to render");
        this.toggleLoadingDiv("none");
        return;
      }
      this.data = data;
    } catch (e) {
      this.toggleLoadingDiv("none", "none");
      if (this.app.isAbortError(e)) return;
      if (e.stack) console.log(e.stack);
      if (e instanceof Error) console.error(e.message || e);
      throw new Error(e);
    }
    this.interactions.clearDom();
    const labels = Object.values(this.data.charts).reduce((labels2, chart) => {
      const chartLabels = chart.plots.filter((p) => !p.isHidden).map((p) => p.boxplot.label);
      labels2.push(...chartLabels);
      return labels2;
    }, []);
    const tempsvg = this.dom.charts.append("svg");
    const maxLabelLgth = getMaxLabelWidth(tempsvg.append("g"), labels);
    tempsvg.remove();
    const viewModel = new ViewModel(config, this.data, settings, maxLabelLgth, this.useDefaultSettings);
    if (!viewModel.viewData) throw new Error("No viewData from ViewModel");
    if ((viewModel.rowSpace !== settings.rowSpace || viewModel.rowHeight !== settings.rowHeight) && this.useDefaultSettings == true) {
      settings.rowSpace = viewModel.rowSpace;
      settings.rowHeight = viewModel.rowHeight;
      this.app.save({
        type: "plot_edit",
        id: this.id,
        config: {
          settings: {
            boxplot: {
              rowSpace: viewModel.rowSpace,
              rowHeight: viewModel.rowHeight
            }
          }
        }
      });
    }
    this.toggleLoadingDiv("none");
    this.dom.renderedData.style("display", "");
    new View(viewModel.viewData, settings, this.dom, this.app, this.interactions);
    this.data.charts = viewModel.viewData.charts;
  }
  getChartImages() {
    const chartImages = [];
    const charts = this.data.charts;
    for (const [key, chart] of Object.entries(charts)) {
      const svg = chart.svg;
      const title = getChartSubtitle(this.state.config, key);
      const name = `${this.state.config.term.term.name}  ${title}`;
      chartImages.push({ name, svg });
    }
    return chartImages;
  }
  download(event) {
    if (!this.state) return;
    const name2svg = this.getChartImages();
    const dm = new DownloadMenu(name2svg, this.state.config.term.term.name);
    dm.show(event.clientX, event.clientY, event.target);
  }
};
var boxplotInit = getCompInit(TdbBoxplot);
var componentInit = boxplotInit;
async function getPlotConfig(opts, app) {
  try {
    if (!opts.term) throw new Error("opts.term{} missing");
    if (opts.term.term?.type == "termCollection") {
    }
    await fillTermWrapper(opts.term, app.vocabApi);
    if (opts.term2) await fillTermWrapper(opts.term2, app.vocabApi);
    if (opts.term0) await fillTermWrapper(opts.term0, app.vocabApi);
  } catch (e) {
    console.error(new Error(`${e} [boxplot getPlotConfig()]`));
    throw new Error(`boxplot getPlotConfig() failed`);
  }
  const config = {
    id: opts.term.term.id || opts.term.$id,
    controlLabels: Object.assign({}, defaultUiLabels, app.vocabApi.termdbConfig.uiLabels || {}),
    settings: {
      controls: {
        term2: null,
        term0: null
      },
      boxplot: getDefaultBoxplotSettings(app, opts.overrides || {})
    }
  };
  return copyMerge(config, opts);
}
export {
  TdbBoxplot,
  boxplotInit,
  componentInit,
  getPlotConfig
};
//# sourceMappingURL=BoxPlot-PUZKHACO.js.map
