Skip to content

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

FEATURE: Dynamic chart types for data explorer (#39036)

Natalie Tay36424c90c73f
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-bar-chart.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-bar-chart.gjs
deleted file mode 100644
index 0e18488789a..00000000000
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-bar-chart.gjs
+++ /dev/null
@@ -1,96 +0,0 @@
-import Component from "@glimmer/component";
-import { on } from "@ember/modifier";
-import { action } from "@ember/object";
-import didInsert from "@ember/render-modifiers/modifiers/did-insert";
-import { bind } from "discourse/lib/decorators";
-import loadChartJS from "discourse/lib/load-chart-js";
-import themeColor from "../lib/themeColor";
-
-export default class DataExplorerBarChart extends Component {
- chart;
- barsColor = themeColor("--tertiary");
- barsHoverColor = themeColor("--tertiary-high");
- gridColor = themeColor("--primary-low");
- labelsColor = themeColor("--primary-medium");
-
- willDestroy() {
- super.willDestroy(...arguments);
- this.chart.destroy();
- }
-
- get config() {
- const data = this.data;
- const options = this.options;
- return {
- type: "bar",
- data,
- options,
- };
- }
-
- get data() {
- const labels = this.args.labels;
- return {
- labels,
- datasets: [
- {
- label: this.args.datasetName,
- data: this.args.values,
- backgroundColor: this.barsColor,
- hoverBackgroundColor: this.barsHoverColor,
- },
- ],
- };
- }
-
- get options() {
- return {
- plugins: {
- legend: {
- labels: {
- color: this.labelsColor,
- },
- },
- },
- scales: {
- x: {
- grid: {
- color: this.gridColor,
- },
- ticks: {
- color: this.labelsColor,
- },
- },
- y: {
- grid: {
- color: this.gridColor,
- },
- ticks: {
- beginAtZero: true,
- color: this.labelsColor,
- },
- },
- },
- };
- }
-
- @bind
- async initChart(canvas) {
- const Chart = await loadChartJS();
- const context = canvas.getContext("2d");
- this.chart = new Chart(context, this.config);
- }
-
- @action
- updateChartData() {
- this.chart.data = this.data;
- this.chart.update();
- }
-
- <template>
- <canvas
- {{didInsert this.initChart}}
- {{on "change" this.updateChartData}}
- ></canvas>
- </template>
-}
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
new file mode 100644
index 00000000000..cfcb28a474a
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-chart.gjs
@@ -0,0 +1,161 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { bind } from "discourse/lib/decorators";
+import loadChartJS from "discourse/lib/load-chart-js";
+import { SERIES_COLORS } from "../lib/chart-helpers";
+import themeColor from "../lib/themeColor";
+
+export default class DataExplorerChart extends Component {
+ chart;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.chart?.destroy();
+ }
+
+ get config() {
+ const gridColor = themeColor("--primary-low");
+ const labelColor = themeColor("--primary-medium");
+
+ if (this.args.datasets.length > 1) {
+ return this._buildMultiSeriesConfig(gridColor, labelColor);
+ }
+
+ return this._buildSingleSeriesConfig(gridColor, labelColor);
+ }
+
+ _buildSingleSeriesConfig(gridColor, labelColor) {
+ const isLine = this.args.chartType === "line";
+ const primaryColor = themeColor("--tertiary");
+
+ const dataset = {
+ label: this.args.datasets[0].label,
+ data: this.args.datasets[0].values,
+ backgroundColor: isLine ? "transparent" : primaryColor,
+ borderColor: primaryColor,
+ borderWidth: isLine ? 2 : 0,
+ pointRadius: isLine ? 2 : 0,
+ pointHoverRadius: isLine ? 4 : 0,
+ tension: 0.3,
+ };
+
+ const xTicks = { color: labelColor };
+ if (isLine) {
+ xTicks.maxTicksLimit = 8;
+ }
+
+ return {
+ type: this.args.chartType,
+ data: { labels: this.args.labels, datasets: [dataset] },
+ options: {
+ responsive: true,
+ maintainAspectRatio: true,
+ plugins: {
+ legend: { display: false },
+ },
+ scales: {
+ x: {
+ ticks: xTicks,
+ grid: { display: false },
+ },
+ y: {
+ ticks: { color: labelColor },
+ grid: { color: gridColor },
+ beginAtZero: true,
+ },
+ },
+ },
+ };
+ }
+
+ _buildMultiSeriesConfig(gridColor, labelColor) {
+ const stacked = this.args.stacked;
+
+ 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,
+ borderColor: color,
+ borderWidth: 1,
+ };
+
+ if (stacked) {
+ result.stack = "data-explorer-stack";
+ }
+
+ return result;
+ });
+
+ const xTicks = { color: labelColor };
+ if (stacked) {
+ xTicks.maxTicksLimit = 8;
+ }
+
+ const scales = {
+ x: {
+ ticks: xTicks,
+ grid: { display: false },
+ },
+ y: {
+ ticks: { color: labelColor },
+ grid: { color: gridColor },
+ beginAtZero: true,
+ },
+ };
+
+ if (stacked) {
+ scales.x.stacked = true;
+ scales.y.stacked = true;
+ }
+
+ return {
+ type: "bar",
+ data: { labels: this.args.labels, datasets },
+ options: {
+ responsive: true,
+ maintainAspectRatio: true,
+ 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()}`;
+ },
+ }
+ : {},
+ },
+ },
+ scales,
+ },
+ };
+ }
+
+ @bind
+ async initChart(canvas) {
+ const Chart = await loadChartJS();
+ const context = canvas.getContext("2d");
+ this.chart = new Chart(context, this.config);
+ }
+
+ @action
+ updateChartData() {
+ if (this.chart) {
+ this.chart.destroy();
+ }
+ this.initChart(this.chart?.canvas);
+ }
+
+ <template>
+ <canvas {{didInsert this.initChart}}></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 48370a2ca23..3e7893817d3 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
@@ -11,7 +11,8 @@ import Badge from "discourse/models/badge";
import Category from "discourse/models/category";
import I18n, { i18n } from "discourse-i18n";
import { QUERY_RESULT_MAX_LIMIT } from "discourse/plugins/discourse-data-explorer/discourse/lib/constants";
-import DataExplorerBarChart from "./data-explorer-bar-chart";
+import { isNumericColumn, looksLikeDate } from "../lib/chart-helpers";
+import DataExplorerChart from "./data-explorer-chart";
import QueryRowContent from "./query-row-content";
import BadgeViewComponent from "./result-types/badge";
import CategoryViewComponent from "./result-types/category";
@@ -66,8 +67,49 @@ export default class QueryResult extends Component {
return this.args.content.explain;
}
- get chartDatasetName() {
- return this.columnNames[1];
+ get numericColumnIndices() {
+ if (!this.rows?.length || !this.columns?.length) {
+ return [];
+ }
+ const indices = [];
+ for (let i = 1; i < this.columns.length; i++) {
+ if (this.colRender[i]) {
+ continue;
+ }
+ if (
+ typeof this.rows[0][i] === "number" ||
+ isNumericColumn(this.rows, i)
+ ) {
+ indices.push(i);
+ }
+ }
+ return indices;
+ }
+
+ get isMultiSeries() {
+ return this.numericColumnIndices.length > 1;
+ }
+
+ get hasDates() {
+ return this.rows?.length > 0 && looksLikeDate(String(this.rows[0][0]));
+ }
+
+ get chartType() {
+ if (this.isMultiSeries) {
+ return "bar";
+ }
+ return this.hasDates ? "line" : "bar";
+ }
+
+ get isStacked() {
+ return this.isMultiSeries && this.hasDates;
+ }
+
+ get chartDatasets() {
+ return this.numericColumnIndices.map((colIdx) => ({
+ label: this.columnNames[colIdx],
+ values: this.rows.map((r) => Number(r[colIdx])),
+ }));
}
get columnNames() {
@@ -99,11 +141,6 @@ export default class QueryResult extends Component {
});
}
- get chartValues() {
- // return an array with the second value of this.row
- return this.rows.map((item) => item[1]);
- }
-
get colCount() {
return this.columns.length;
}
@@ -158,14 +195,7 @@ export default class QueryResult extends Component {
}
get canShowChart() {
- const hasTwoColumns = this.colCount === 2;
- const secondColumnContainsNumber =
- this.resultCount[0] > 0 && typeof this.rows[0][1] === "number";
- const secondColumnContainsId = this.colRender[1];
-
- return (
- hasTwoColumns && secondColumnContainsNumber && !secondColumnContainsId
- );
+ return this.rows?.length > 0 && this.numericColumnIndices.length > 0;
}
get chartLabels() {
@@ -356,10 +386,11 @@ export default class QueryResult extends Component {
<section>
{{#if this.chartDisplayed}}
- <DataExplorerBarChart
+ <DataExplorerChart
@labels={{this.chartLabels}}
- @values={{this.chartValues}}
- @datasetName={{this.chartDatasetName}}
+ @datasets={{this.chartDatasets}}
+ @chartType={{this.chartType}}
+ @stacked={{this.isStacked}}
/>
{{else}}
<table class="query-results-table">
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
new file mode 100644
index 00000000000..33722edb248
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js
@@ -0,0 +1,25 @@
+export const SERIES_COLORS = [
+ "#1EB8D1",
+ "#9BC53D",
+ "#721D8D",
+ "#E84A5F",
+ "#8A6916",
+ "#FFCD56",
+];
+
+export function looksLikeDate(value) {
+ if (!value || typeof value !== "string") {
+ return false;
+ }
+ return /^\d{4}-\d{2}-\d{2}/.test(value);
+}
+
+export function isNumericColumn(rows, colIndex) {
+ for (const row of rows) {
+ const val = row[colIndex];
+ if (val !== null && val !== undefined && val !== "") {
+ return Number.isFinite(Number(val));
+ }
+ }
+ return false;
+}
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-bar-chart-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-bar-chart-test.gjs
deleted file mode 100644
index 6b7547631d7..00000000000
--- a/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-bar-chart-test.gjs
+++ /dev/null
@@ -1,26 +0,0 @@
-import { array } from "@ember/helper";
-import { render } from "@ember/test-helpers";
-import { module, test } from "qunit";
-import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import DataExplorerBarChart from "../../discourse/components/data-explorer-bar-chart";
-
-module(
- "Data Explorer Plugin | Integration | Component | data-explorer-bar-chart",
- function (hooks) {
- setupRenderingTest(hooks);
-
- test("renders a chart", async function (assert) {
- await render(
- <template>
- <DataExplorerBarChart
- @labels={{array "label_1" "label_2"}}
- @values={{array 115 1000}}
- @datasetName="data"
- />
- </template>
- );
-
- assert.dom("canvas").exists("renders a canvas");
- });
- }
-);
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
new file mode 100644
index 00000000000..0c18e69a9e0
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-chart-test.gjs
@@ -0,0 +1,89 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DataExplorerChart from "../../discourse/components/data-explorer-chart";
+
+module(
+ "Data Explorer Plugin | Integration | Component | data-explorer-chart",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders a bar chart with a single dataset", async function (assert) {
+ const labels = ["label_1", "label_2"];
+ const datasets = [{ label: "data", values: [115, 1000] }];
+
+ await render(
+ <template>
+ <DataExplorerChart
+ @labels={{labels}}
+ @datasets={{datasets}}
+ @chartType="bar"
+ @stacked={{false}}
+ />
+ </template>
+ );
+
+ assert.dom("canvas").exists("renders a canvas");
+ });
+
+ test("renders a line chart", async function (assert) {
+ const labels = ["2024-01-01", "2024-01-02"];
+ const datasets = [{ label: "count", values: [10, 20] }];
+
+ await render(
+ <template>
+ <DataExplorerChart
+ @labels={{labels}}
+ @datasets={{datasets}}
+ @chartType="line"
+ @stacked={{false}}
+ />
+ </template>
+ );
+
+ assert.dom("canvas").exists("renders a canvas for line chart");
+ });
+
+ test("renders a multi-series chart", async function (assert) {
+ const labels = ["user1", "user2"];
+ const datasets = [
+ { label: "likes", values: [10, 20] },
+ { label: "posts", values: [5, 15] },
+ ];
+
+ await render(
+ <template>
+ <DataExplorerChart
+ @labels={{labels}}
+ @datasets={{datasets}}
+ @chartType="bar"
+ @stacked={{false}}
+ />
+ </template>
+ );
+
+ assert.dom("canvas").exists("renders a canvas for multi-series chart");
+ });
+
+ test("renders a stacked chart", async function (assert) {
+ const labels = ["2024-01-01", "2024-01-02"];
+ const datasets = [
+ { label: "likes", values: [10, 20] },
+ { label: "posts", values: [5, 15] },
+ ];
+
+ await render(
+ <template>
+ <DataExplorerChart
+ @labels={{labels}}
+ @datasets={{datasets}}
+ @chartType="bar"
+ @stacked={{true}}
+ />
+ </template>
+ );
+
+ assert.dom("canvas").exists("renders a canvas for stacked 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 235b716ce91..b2d0832a110 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
@@ -233,7 +233,7 @@ module(
assert.dom("div.result-info button:nth-child(3)").doesNotExist();
});
- test("doesn't render a chart button when data contains more than two columns", async function (assert) {
+ test("renders a chart button when data contains multiple numeric columns", async function (assert) {
const content = {
colrender: [],
result_count: 2,
@@ -246,9 +246,66 @@ module(
await render(<template><QueryResult @content={{content}} /></template>);
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(i18n("explorer.show_graph"));
+ });
+
+ test("doesn't render a chart button when all non-label columns are relation types", async function (assert) {
+ const content = {
+ colrender: { 1: "user", 2: "badge" },
+ relations: {
+ user: [{ id: 1, username: "user1" }],
+ badge: [{ id: 1, name: "badge1" }],
+ },
+ result_count: 1,
+ columns: ["topic_id", "user_id", "badge_id"],
+ rows: [[1, 1, 1]],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
assert.dom("div.result-info button:nth-child(3)").doesNotExist();
});
+ test("renders a chart for date-based data", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["date", "count"],
+ rows: [
+ ["2024-01-01", 10],
+ ["2024-01-02", 20],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("div.result-info button:nth-child(3) span")
+ .hasText(i18n("explorer.show_graph"));
+
+ await click("div.result-info button:nth-child(3)");
+ assert.dom("canvas").exists("renders a chart canvas");
+ });
+
+ test("renders a multi-series chart", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user_name", "like_count", "post_count"],
+ rows: [
+ ["user1", 10, 5],
+ ["user2", 20, 15],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ await click("div.result-info button:nth-child(3)");
+ assert.dom("canvas").exists("renders a chart canvas for multi-series");
+ });
+
test("handles no results", async function (assert) {
const content = {
colrender: [],