Skip to content

A platform for community discussion. Free, open, simple.

UI: Improve heuristics for graphing on Data Explorer (#41044)

Natalie Tay3667a18c58b4
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs
index a191be2b44c..d2cfc39b117 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs
@@ -4,7 +4,8 @@ import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { bind } from "discourse/lib/decorators";
import loadChartJS from "discourse/lib/load-chart-js";
-import { looksLikeDate, SERIES_COLORS } from "../lib/chart-helpers";
+import I18n, { i18n } from "discourse-i18n";
+import { formatChartDateLabel, SERIES_COLORS } from "../lib/chart-helpers";
import themeColor from "../lib/themeColor";
export default class DataExplorerChart extends Component {
@@ -76,9 +77,7 @@ export default class DataExplorerChart extends Component {
callbacks: {
title: (items) => {
const label = items[0].label;
- return looksLikeDate(label)
- ? moment(label).format("LL")
- : label;
+ return formatChartDateLabel(label);
},
label: (item) => item.formattedValue,
},
@@ -101,26 +100,47 @@ export default class DataExplorerChart extends Component {
_buildMultiSeriesConfig(gridColor, labelColor) {
const stacked = this.args.stacked;
+ const isLine = this.args.chartType === "line";
+ const dualAxis = this.args.dualAxis;
const datasets = this.args.datasets.map((ds, i) => {
const color = SERIES_COLORS[i % SERIES_COLORS.length];
const result = {
label: ds.label,
data: ds.values,
- backgroundColor: color,
+ backgroundColor: isLine ? "transparent" : color,
borderColor: color,
- borderWidth: 1,
+ borderWidth: isLine ? 2 : 1,
};
+ if (dualAxis) {
+ result.yAxisID = i === 0 ? "y" : "y1";
+ if (i > 0) {
+ result.borderDash = [5, 5];
+ }
+ }
+
if (stacked) {
result.stack = "data-explorer-stack";
}
+ if (isLine) {
+ result.pointRadius = 2;
+ result.pointHoverRadius = 4;
+ result.pointBackgroundColor = color;
+ result.pointBorderColor = color;
+ result.pointStyle = "rectRounded";
+ result.borderCapStyle = "round";
+ result.borderJoinStyle = "round";
+ result.tension = 0.4;
+ result.fill = false;
+ }
+
return result;
});
const xTicks = { color: labelColor };
- if (stacked) {
+ if (stacked || isLine) {
xTicks.maxTicksLimit = 8;
}
@@ -141,35 +161,59 @@ export default class DataExplorerChart extends Component {
scales.y.stacked = true;
}
+ if (dualAxis) {
+ scales.y1 = {
+ type: "linear",
+ position: "right",
+ ticks: { color: labelColor },
+ grid: { drawOnChartArea: false },
+ beginAtZero: true,
+ };
+ }
+
return {
- type: "bar",
+ type: this.args.chartType,
data: { labels: this.args.labels, datasets },
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: true, position: "bottom" },
- tooltip: {
- mode: "index",
- intersect: false,
- callbacks: stacked
- ? {
- beforeFooter(items) {
- const total = items.reduce(
- (sum, item) => sum + (item.parsed.y || 0),
- 0
- );
- return `Total: ${total.toLocaleString()}`;
- },
- }
- : {},
- },
+ tooltip: this._multiSeriesTooltipOptions(stacked),
},
scales,
},
};
}
+ _multiSeriesTooltipOptions(stacked) {
+ const callbacks = {
+ title: (items) => {
+ const label = items[0].label;
+ return formatChartDateLabel(label);
+ },
+ };
+
+ if (stacked) {
+ callbacks.beforeFooter = (items) => {
+ const total = items.reduce(
+ (sum, item) => sum + (item.parsed.y || 0),
+ 0
+ );
+
+ return i18n("explorer.chart.tooltip.total", {
+ count: I18n.toNumber(total, { precision: 0 }),
+ });
+ };
+ }
+
+ return {
+ mode: "index",
+ intersect: false,
+ callbacks,
+ };
+ }
+
@bind
async initChart(canvas) {
const Chart = await loadChartJS();
@@ -188,7 +232,14 @@ export default class DataExplorerChart extends Component {
<template>
<canvas
{{didInsert this.initChart}}
- {{didUpdate this.updateChartData @labels @datasets @chartType @stacked}}
+ {{didUpdate
+ this.updateChartData
+ @labels
+ @datasets
+ @chartType
+ @stacked
+ @dualAxis
+ }}
></canvas>
</template>
}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
index 10b832b70c5..bfafbf3b349 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
@@ -47,24 +47,32 @@ const VIEW_COMPONENTS = {
tag_group: TagGroupViewComponent,
};
+const CHART_FORMS = ["line", "bar", "stacked", "dual-axis"];
+
export default class QueryResult extends Component {
@service site;
@tracked internalView;
+ @tracked internalChartForm;
@tracked tableExpanded = false;
@tracked hasOverflow = false;
constructor() {
super(...arguments);
- if (this.args.view) {
- return;
- }
const queryId = this.args.query?.id;
- const stored = queryId ? store.get(`view_${queryId}`) : null;
- if (stored === "chart" || stored === "table") {
- this.internalView = stored;
- } else {
- this.internalView = defaultView(this.args.content);
+
+ if (!this.args.view) {
+ const stored = queryId ? store.get(`view_${queryId}`) : null;
+ if (stored === "chart" || stored === "table") {
+ this.internalView = stored;
+ } else {
+ this.internalView = defaultView(this.args.content);
+ }
+ }
+
+ const storedChartForm = queryId ? store.get(`chart_form_${queryId}`) : null;
+ if (CHART_FORMS.includes(storedChartForm)) {
+ this.internalChartForm = storedChartForm;
}
}
@@ -90,6 +98,15 @@ export default class QueryResult extends Component {
this.setView("table");
}
+ @action
+ setChartForm(value) {
+ this.internalChartForm = value;
+ const queryId = this.args.query?.id;
+ if (queryId) {
+ store.set({ key: `chart_form_${queryId}`, value });
+ }
+ }
+
get showExpandButton() {
return this.hasOverflow && !this.tableExpanded;
}
@@ -148,6 +165,29 @@ export default class QueryResult extends Component {
];
}
+ get chartFormItems() {
+ const items = [
+ { value: "line", label: i18n("explorer.chart.form.line") },
+ { value: "bar", label: i18n("explorer.chart.form.bar") },
+ ];
+
+ if (this.isMultiSeries) {
+ items.push({
+ value: "stacked",
+ label: i18n("explorer.chart.form.stacked"),
+ });
+ }
+
+ if (this.canUseDualAxis) {
+ items.push({
+ value: "dual-axis",
+ label: i18n("explorer.chart.form.dual_axis"),
+ });
+ }
+
+ return items;
+ }
+
get colRender() {
return this.args.content.colrender || {};
}
@@ -172,19 +212,42 @@ export default class QueryResult extends Component {
return this.numericColumnIndices.length > 1;
}
+ get canUseDualAxis() {
+ return this.hasDates && this.numericColumnIndices.length === 2;
+ }
+
get hasDates() {
return this.rows?.length > 0 && looksLikeDate(String(this.rows[0][0]));
}
- get chartType() {
- if (this.isMultiSeries) {
- return "bar";
+ get defaultChartForm() {
+ if (this.hasDates) {
+ return "line";
}
- return this.hasDates ? "line" : "bar";
+ return "bar";
+ }
+
+ get availableChartForms() {
+ return this.chartFormItems.map((item) => item.value);
+ }
+
+ get chartForm() {
+ if (this.availableChartForms.includes(this.internalChartForm)) {
+ return this.internalChartForm;
+ }
+ return this.defaultChartForm;
+ }
+
+ get chartType() {
+ return ["line", "dual-axis"].includes(this.chartForm) ? "line" : "bar";
}
get isStacked() {
- return this.isMultiSeries && this.hasDates;
+ return this.chartForm === "stacked";
+ }
+
+ get usesDualAxis() {
+ return this.chartForm === "dual-axis";
}
get chartDatasets() {
@@ -403,11 +466,22 @@ export default class QueryResult extends Component {
{{#if this.chartVisible}}
<div class="query-results-chart">
+ <DSegmentedControl
+ @name="query-result-chart-form"
+ @value={{this.chartForm}}
+ @items={{this.chartFormItems}}
+ @onSelect={{this.setChartForm}}
+ @translatedLabel={{i18n "explorer.chart.form.label"}}
+ @size="small"
+ class="query-results-chart__form"
+ />
+
<DataExplorerChart
@labels={{this.chartLabels}}
@datasets={{this.chartDatasets}}
@chartType={{this.chartType}}
@stacked={{this.isStacked}}
+ @dualAxis={{this.usesDualAxis}}
/>
{{#if this.ignoredColumnNames.length}}
<p class="query-results-chart__footnote">
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js
index 3e0a46c21b9..da165e725ef 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js
@@ -1,3 +1,5 @@
+import moment from "moment";
+
export const SERIES_COLORS = [
"#1EB8D1",
"#9BC53D",
@@ -7,11 +9,38 @@ export const SERIES_COLORS = [
"#FFCD56",
];
+const DATE_LABEL_FORMATS = ["MMM D", "MMM DD", "MMM YY", "MMM YYYY"];
+const MONTH_DAY_LABEL_FORMATS = ["MMM D", "MMM DD"];
+
export function looksLikeDate(value) {
if (!value || typeof value !== "string") {
return false;
}
- return /^\d{4}-\d{2}-\d{2}/.test(value);
+
+ const normalizedValue = value.trim().replace(/\s+/g, " ");
+ if (/^\d{4}-\d{2}-\d{2}/.test(normalizedValue)) {
+ return true;
+ }
+
+ return moment(normalizedValue, DATE_LABEL_FORMATS, true).isValid();
+}
+
+export function formatChartDateLabel(value) {
+ if (!value || typeof value !== "string") {
+ return value;
+ }
+
+ const normalizedValue = value.trim().replace(/\s+/g, " ");
+ if (/^\d{4}-\d{2}-\d{2}/.test(normalizedValue)) {
+ return moment(normalizedValue).format("LL");
+ }
+
+ const monthDay = moment(normalizedValue, MONTH_DAY_LABEL_FORMATS, true);
+ if (monthDay.isValid()) {
+ return monthDay.format("MMM D");
+ }
+
+ return normalizedValue;
}
export function isNumericColumn(rows, colIndex) {
@@ -24,18 +53,76 @@ export function isNumericColumn(rows, colIndex) {
return false;
}
+const MAX_DEFAULT_CATEGORICAL_ROWS = 25;
+const MAX_DEFAULT_TIME_SERIES = 4;
+const MIN_DEFAULT_NUMERIC_DENSITY = 0.5;
+
// Picks the view to show when the user hasn't expressed a preference. A chart
// is only a good default when every non-label column can be plotted; if
// charting would silently drop columns (e.g. "user, username, reason, sum"),
-// the table is more honest. Users can still toggle to the chart.
+// the table is more honest. We also keep large categorical and sparse
+// multi-series result sets in table view by default; users can still toggle to
+// the chart.
export function defaultView(content) {
const ability = chartability(content);
if (!ability.chartable || ability.ignoredColumns.length > 0) {
return "table";
}
+ if (shouldDefaultToTable(content, ability)) {
+ return "table";
+ }
return "chart";
}
+function shouldDefaultToTable(content, ability) {
+ const rows = content?.rows ?? [];
+ const firstLabel = String(rows[0]?.[0]);
+
+ if (
+ !looksLikeDate(firstLabel) &&
+ rows.length > MAX_DEFAULT_CATEGORICAL_ROWS
+ ) {
+ return true;
+ }
+
+ if (
+ looksLikeDate(firstLabel) &&
+ ability.numericIndices.length > MAX_DEFAULT_TIME_SERIES
+ ) {
+ return true;
+ }
+
+ if (ability.numericIndices.length > 1) {
+ return (
+ numericDensity(rows, ability.numericIndices) < MIN_DEFAULT_NUMERIC_DENSITY
+ );
+ }
+
+ return false;
+}
+
+function numericDensity(rows, numericIndices) {
+ const totalCells = rows.length * numericIndices.length;
+ if (totalCells === 0) {
+ return 0;
+ }
+
+ let presentCells = 0;
+ for (const row of rows) {
+ for (const index of numericIndices) {
+ if (
+ row[index] !== null &&
+ row[index] !== undefined &&
+ row[index] !== ""
+ ) {
+ presentCells++;
+ }
+ }
+ }
+
+ return presentCells / totalCells;
+}
+
export function chartability(content) {
const { rows, columns, colrender = {} } = content ?? {};
if (!rows?.length) {
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
index 1f4adc2e302..8a969026aa5 100644
--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -749,6 +749,11 @@ table.group-reports {
margin-bottom: 1rem;
animation: fadein 2s;
+ .query-results-chart__form {
+ max-width: 100%;
+ margin-bottom: 0.75rem;
+ }
+
canvas {
height: clamp(200px, 50vh, 350px) !important;
}
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index 97f2f9588ca..88555911833 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -108,6 +108,15 @@ en:
run_options: "More run options"
view:
label: "Result view"
+ chart:
+ form:
+ label: "Chart type"
+ line: "Line"
+ bar: "Bar"
+ stacked: "Stacked"
+ dual_axis: "Dual axis"
+ tooltip:
+ total: "Total: %{count}"
chart_empty:
no_rows: "No rows to chart."
no_numeric: "This query has no numeric columns to chart."
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-chart-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-chart-test.gjs
index d2ea14173cc..853c2292f52 100644
--- a/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-chart-test.gjs
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-chart-test.gjs
@@ -83,4 +83,26 @@ module("Integration | Component | DataExplorerChart", function (hooks) {
assert.dom("canvas").exists("renders a canvas for stacked chart");
});
+
+ test("renders a dual-axis line chart", async function (assert) {
+ const labels = ["2024-01-01", "2024-01-02"];
+ const datasets = [
+ { label: "distinct_repliers", values: [263, 220] },
+ { label: "replies_per_person", values: [6, 8] },
+ ];
+
+ await render(
+ <template>
+ <DataExplorerChart
+ @labels={{labels}}
+ @datasets={{datasets}}
+ @chartType="line"
+ @stacked={{false}}
+ @dualAxis={{true}}
+ />
+ </template>
+ );
+
+ assert.dom("canvas").exists("renders a canvas for dual-axis chart");
+ });
});
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
index 6df6e8852fa..8026dea1e9f 100644
--- a/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
@@ -250,6 +250,107 @@ module("Integration | Component | QueryResult | Chart", function (hooks) {
assert.dom("canvas").exists("chart is still available via the toggle");
});
+ test("defaults to the table for large categorical result sets", async function (assert) {
+ const rows = Array.from({ length: 200 }, (_, i) => [`item-${i + 1}`, i]);
+ const content = {
+ colrender: [],
+ result_count: rows.length,
+ columns: ["name", "count"],
+ rows,
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("table")
+ .exists("table is the default for a large categorical result set");
+ assert.dom("canvas").doesNotExist("chart is not shown by default");
+
+ await click(".query-results-modes input[value='chart']");
+
+ assert.dom("canvas").exists("chart remains available via the toggle");
+ });
+
+ test("defaults to the chart for large date-based result sets", async function (assert) {
+ const rows = Array.from({ length: 200 }, (_, i) => [
+ new Date(Date.UTC(2024, 0, i + 1)).toISOString().slice(0, 10),
+ i,
+ ]);
+ const content = {
+ colrender: [],
+ result_count: rows.length,
+ columns: ["date", "count"],
+ rows,
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert.dom("canvas").exists("time series remain chart-first by default");
+ });
+
+ test("defaults to the table for sparse multi-series result sets", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 6,
+ columns: ["name", "unassignable", "stale", "super_stale"],
+ rows: [
+ ["JVM", 4, "", 19],
+ ["CFamily", "", "", ""],
+ ["DataMachineLearning", "", "", ""],
+ ["DotNET", 2, "", 3],
+ ["TaintAnalysis", 4, 1, 4],
+ ["Web", "", "", ""],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("table")
+ .exists("table is the default for sparse multi-series data");
+ assert.dom("canvas").doesNotExist("chart is not shown by default");
+
+ await click(".query-results-modes input[value='chart']");
+
+ assert.dom("canvas").exists("chart remains available via the toggle");
+ });
+
+ test("defaults to the table for wide date-based multi-series result sets", async function (assert) {
+ const numericColumns = Array.from(
+ { length: 10 },
+ (_metric, index) => `metric_${index + 1}`
+ );
+ const rows = Array.from({ length: 12 }, (_row, rowIndex) => [
+ new Date(Date.UTC(2024, rowIndex, 1)).toISOString().slice(0, 10),
+ ...numericColumns.map(
+ (_column, columnIndex) => rowIndex + columnIndex + 1
+ ),
+ ]);
+ const content = {
+ colrender: [],
+ result_count: rows.length,
+ columns: ["date", ...numericColumns],
+ rows,
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("table")
+ .exists("table is the default for too many time-series metrics");
+ assert.dom("canvas").doesNotExist("chart is not shown by default");
+
+ await click(".query-results-modes input[value='chart']");
+
+ assert.dom("canvas").exists("chart remains available via the toggle");
+ assert
+ .dom(".query-results-chart__form input[value='stacked']")
+ .exists("stacked chart remains available");
+ assert
+ .dom(".query-results-chart__form input[value='dual-axis']")
+ .doesNotExist("dual-axis is not offered for more than two metrics");
+ });
+
test("doesn't render a chart when all non-label columns are relation types", async function (assert) {
const content = {
colrender: { 1: "user", 2: "badge" },
@@ -315,6 +416,214 @@ module("Integration | Component | QueryResult | Chart", function (hooks) {
assert.dom("canvas").exists("renders a chart canvas for multi-series");
});
+ test("uses sensible chart form defaults for common result shapes", async function (assert) {
+ const cases = [
+ {
+ description: "text, number",
+ columns: ["name", "count"],
+ rows: [
+ ["alpha", 10],
+ ["beta", 20],
+ ],
+ selected: "bar",
+ available: ["line", "bar"],
+ unavailable: ["stacked", "dual-axis"],
+ },
+ {
+ description: "date, number",
+ columns: ["date", "count"],
+ rows: [
+ ["2024-01-01", 10],
+ ["2024-01-02", 20],
+ ],
+ selected: "line",
+ available: ["line", "bar"],
+ unavailable: ["stacked", "dual-axis"],
+ },
+ {
+ description: "month day, number",
+ columns: ["date", "count"],
+ rows: [
+ ["Jan 01", 10],
+ ["Jan 02", 20],
+ ],
+ selected: "line",
+ available: ["line", "bar"],
+ unavailable: ["stacked", "dual-axis"],
+ },
+ {
+ description: "month year, number",
+ columns: ["date", "count"],
+ rows: [
+ ["Jan 24", 10],
+ ["Feb 24", 20],
+ ],
+ selected: "line",
+ available: ["line", "bar"],
+ unavailable: ["stacked", "dual-axis"],
+ },
+ {
+ description: "text, number, number",
+ columns: ["name", "likes", "posts"],
+ rows: [
+ ["alpha", 10, 5],
+ ["beta", 20, 15],
+ ],
+ selected: "bar",
+ available: ["line", "bar", "stacked"],
+ unavailable: ["dual-axis"],
+ },
+ {
+ description: "date, number, number",
+ columns: ["date", "likes", "posts"],
+ rows: [
+ ["2024-01-01", 10, 5],
+ ["2024-01-02", 20, 15],
+ ],
+ selected: "line",
+ available: ["line", "bar", "stacked", "dual-axis"],
+ unavailable: [],
+ },
+ {
+ description: "date, number, number, number",
+ columns: ["date", "likes", "posts", "topics"],
+ rows: [
+ ["2024-01-01", 10, 5, 1],
+ ["2024-01-02", 20, 15, 2],
+ ],
+ selected: "line",
+ available: ["line", "bar", "stacked"],
+ unavailable: ["dual-axis"],
+ },
+ {
+ description: "date, text, number",
+ columns: ["date", "note", "count"],
+ rows: [
+ ["2024-01-01", "alpha", 10],
+ ["2024-01-02", "beta", 20],
+ ],
+ selected: "line",
+ available: ["line", "bar"],
+ unavailable: ["stacked", "dual-axis"],
+ },
+ {
+ description: "text, date, number",
+ columns: ["name", "date", "count"],
+ rows: [
+ ["alpha", "2024-01-01", 10],
+ ["beta", "2024-01-02", 20],
+ ],
+ selected: "bar",
+ available: ["line", "bar"],
+ unavailable: ["stacked", "dual-axis"],
+ },
+ ];
+
+ for (const testCase of cases) {
+ this.set("content", {
+ colrender: [],
+ result_count: testCase.rows.length,
+ columns: testCase.columns,
+ rows: testCase.rows,
+ });
+
+ await render(
+ <template>
+ <QueryResult @content={{this.content}} @view="chart" />
+ </template>
+ );
+
+ assert
+ .dom(`.query-results-chart__form input[value='${testCase.selected}']`)
+ .isChecked(`${testCase.description} defaults to ${testCase.selected}`);
+
+ for (const chartForm of testCase.available) {
+ assert
+ .dom(`.query-results-chart__form input[value='${chartForm}']`)
+ .exists(`${testCase.description} offers ${chartForm}`);
+ }
+
+ for (const chartForm of testCase.unavailable) {
+ assert
+ .dom(`.query-results-chart__form input[value='${chartForm}']`)
+ .doesNotExist(`${testCase.description} does not offer ${chartForm}`);
+ }
+ }
+ });
+
+ test("allows the chart form to be changed for date-based multi-series data", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["date", "likes", "posts"],
+ rows: [
+ ["2024-01-01", 10, 5],
+ ["2024-01-02", 20, 15],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom(".query-results-chart__form input[value='line']")
+ .isChecked("date-based multi-series data defaults to a line chart");
+ assert
+ .dom(".query-results-chart__form input[value='dual-axis']")
+ .exists("two-metric time series can use a dual-axis line chart");
+
+ await click(".query-results-chart__form input[value='stacked']");
+
+ assert
+ .dom(".query-results-chart__form input[value='stacked']")
+ .isChecked("the user can switch to stacked bars");
+ assert.dom("canvas").exists("the chart remains visible");
+ });
+
+ test("does not offer a dual-axis chart for non-date multi-series data", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user", "likes", "posts"],
+ rows: [
+ ["user1", 10, 5],
+ ["user2", 20, 15],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom(".query-results-chart__form input[value='dual-axis']")
+ .doesNotExist("dual-axis is only offered for date-based data");
+ });
+
+ test("persists the selected chart form per query", async function (assert) {
+ const query = { id: 43 };
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["date", "likes", "posts"],
+ rows: [
+ ["2024-01-01", 10, 5],
+ ["2024-01-02", 20, 15],
+ ],
+ };
+
+ await render(
+ <template><QueryResult @content={{content}} @query={{query}} /></template>
+ );
+
+ await click(".query-results-chart__form input[value='dual-axis']");
+
+ await render(
+ <template><QueryResult @content={{content}} @query={{query}} /></template>
+ );
+
+ assert
+ .dom(".query-results-chart__form input[value='dual-axis']")
+ .isChecked("chart form is restored from localStorage");
+ });
+
test("charts numeric columns and ignores text columns alongside them", async function (assert) {
const content = {
colrender: [],
diff --git a/plugins/discourse-data-explorer/test/javascripts/unit/lib/chart-helpers-test.js b/plugins/discourse-data-explorer/test/javascripts/unit/lib/chart-helpers-test.js
new file mode 100644
index 00000000000..640f5bdda7a
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/unit/lib/chart-helpers-test.js
@@ -0,0 +1,36 @@
+import { module, test } from "qunit";
+import {
+ formatChartDateLabel,
+ looksLikeDate,
+} from "../../discourse/lib/chart-helpers";
+
+module("Unit | Lib | chart-helpers", function () {
+ test("detects compact date labels for chart defaults", function (assert) {
+ assert.true(looksLikeDate("Jan 03"), "detects month/day labels");
+ assert.true(looksLikeDate("Jan 24"), "detects month/year labels");
+ assert.true(looksLikeDate("Jan 2024"), "detects long month/year labels");
+ });
+
+ test("formats tooltip labels without inventing years for compact labels", function (assert) {
+ assert.strictEqual(
+ formatChartDateLabel("2024-01-03"),
+ "January 3, 2024",
+ "expands ISO dates"
+ );
+ assert.strictEqual(
+ formatChartDateLabel("Jan 03"),
+ "Jan 3",
+ "normalizes month/day labels"
+ );
+ assert.strictEqual(
+ formatChartDateLabel("Jan 24"),
+ "Jan 24",
+ "leaves ambiguous compact labels alone"
+ );
+ assert.strictEqual(
+ formatChartDateLabel("Jan 2024"),
+ "Jan 2024",
+ "leaves month/year labels alone"
+ );
+ });
+});