Skip to content

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

UX: Render linked records in embedded Data Explorer reports (#43642)

Osama Sayeghd09bc956c0ff
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/admin-dashboard-card.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/admin-dashboard-card.gjs
index 389f6a6faf4..9439f4fd559 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/admin-dashboard-card.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/admin-dashboard-card.gjs
@@ -1,10 +1,28 @@
import Component from "@glimmer/component";
import { cached } from "@glimmer/tracking";
+import { service } from "@ember/service";
import { i18n } from "discourse-i18n";
import { chartability, chartDatasets, hasDates } from "../lib/chart-helpers";
+import {
+ buildColumnComponents,
+ buildRelationTables,
+ displayColumnNames,
+ relationLabel,
+ VIEW_COMPONENTS,
+} from "../lib/result-columns";
import DataExplorerChart from "./data-explorer-chart";
+import QueryRowContent from "./query-row-content";
+
+const CARD_VIEW_COMPONENTS = Object.fromEntries(
+ ["badge", "category", "group", "text", "topic", "user"].map((type) => [
+ type,
+ VIEW_COMPONENTS[type],
+ ])
+);
export default class DataExplorerAdminDashboardCard extends Component {
+ @service site;
+
get rows() {
return this.args.payload?.rows ?? [];
}
@@ -14,7 +32,23 @@ export default class DataExplorerAdminDashboardCard extends Component {
}
get columnLabels() {
- return this.columns.map((col) => col.replaceAll("_", " "));
+ return displayColumnNames(this.columns).map((name) =>
+ name.replaceAll("_", " ")
+ );
+ }
+
+ @cached
+ get relationTables() {
+ return buildRelationTables(this.args.payload?.relations, this.site);
+ }
+
+ @cached
+ get columnComponents() {
+ return buildColumnComponents(
+ this.args.payload,
+ this.relationTables,
+ CARD_VIEW_COMPONENTS
+ );
}
@cached
@@ -43,7 +77,9 @@ export default class DataExplorerAdminDashboardCard extends Component {
}
get chartLabels() {
- return this.rows.map((row) => row[0]);
+ const table = this.columnComponents[0]?.table;
+
+ return this.rows.map((row) => relationLabel(table?.[row[0]]) ?? row[0]);
}
get chartDatasets() {
@@ -75,11 +111,10 @@ export default class DataExplorerAdminDashboardCard extends Component {
</thead>
<tbody>
{{#each this.rows as |row|}}
- <tr>
- {{#each row as |cell|}}
- <td>{{cell}}</td>
- {{/each}}
- </tr>
+ <QueryRowContent
+ @columnComponents={{this.columnComponents}}
+ @row={{row}}
+ />
{{/each}}
</tbody>
</table>
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 9c8e173f004..3517391b3bc 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
@@ -5,7 +5,6 @@ import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { service } from "@ember/service";
import moment from "moment";
import DSegmentedControl from "discourse/components/d-segmented-control";
-import Badge from "discourse/models/badge";
import DButton from "discourse/ui-kit/d-button";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import I18n, { i18n } from "discourse-i18n";
@@ -16,37 +15,16 @@ import {
hasDates,
} from "../lib/chart-helpers";
import { dataExplorerStore } from "../lib/data-explorer-store";
+import {
+ buildColumnComponents,
+ buildRelationTables,
+ displayColumnNames,
+ relationLabel,
+} from "../lib/result-columns";
import DataExplorerChart from "./data-explorer-chart";
import QueryChartEmptyState from "./query-chart-empty-state";
import QueryResultDownloadButtons from "./query-result-download-buttons";
import QueryRowContent from "./query-row-content";
-import BadgeViewComponent from "./result-types/badge";
-import CategoryViewComponent from "./result-types/category";
-import GroupViewComponent from "./result-types/group";
-import HtmlViewComponent from "./result-types/html";
-import JsonViewComponent from "./result-types/json";
-import PostViewComponent from "./result-types/post";
-import ReltimeViewComponent from "./result-types/reltime";
-import TagGroupViewComponent from "./result-types/tag-group";
-import TextViewComponent from "./result-types/text";
-import TopicViewComponent from "./result-types/topic";
-import UrlViewComponent from "./result-types/url";
-import UserViewComponent from "./result-types/user";
-
-const VIEW_COMPONENTS = {
- topic: TopicViewComponent,
- text: TextViewComponent,
- post: PostViewComponent,
- reltime: ReltimeViewComponent,
- badge: BadgeViewComponent,
- url: UrlViewComponent,
- user: UserViewComponent,
- group: GroupViewComponent,
- html: HtmlViewComponent,
- json: JsonViewComponent,
- category: CategoryViewComponent,
- tag_group: TagGroupViewComponent,
-};
const CHART_FORMS = ["line", "bar", "stacked", "dual-axis"];
@@ -219,39 +197,12 @@ export default class QueryResult extends Component {
}
get columnNames() {
- if (!this.columns) {
- return [];
- }
- return this.columns.map((colName) => {
- if (colName.endsWith("_id")) {
- return colName.slice(0, -3);
- }
- const dIdx = colName.indexOf("$");
- if (dIdx >= 0) {
- return colName.substring(dIdx + 1);
- }
- return colName;
- });
+ return displayColumnNames(this.columns);
}
@cached
get columnComponents() {
- if (!this.columns) {
- return [];
- }
-
- const hiddenRelations = this.args.content.hidden_relations ?? {};
-
- return this.columns.map((_, idx) => {
- const type = this.colRender[idx] || "text";
-
- return {
- name: type,
- component: VIEW_COMPONENTS[type],
- table: this._relationTables[type],
- hidden: hiddenRelations[type],
- };
- });
+ return buildColumnComponents(this.args.content, this._relationTables);
}
get resultCount() {
@@ -280,24 +231,7 @@ export default class QueryResult extends Component {
@cached
get _relationTables() {
- const { relations = {} } = this.args.content;
- const tables = {
- group: this.site.groupsById,
- category: transformedRelTable(this.site.categories),
- };
-
- for (const [type, table] of Object.entries(relations)) {
- if (tables[type]) {
- continue;
- }
-
- tables[type] = transformedRelTable(
- table,
- type === "badge" ? Badge : undefined
- );
- }
-
- return tables;
+ return buildRelationTables(this.args.content.relations, this.site);
}
@cached
@@ -485,19 +419,6 @@ export default class QueryResult extends Component {
</template>
}
-function transformedRelTable(table, modelClass) {
- return Object.fromEntries(
- (table ?? []).map((item) => [
- item.id,
- modelClass ? modelClass.create(item) : item,
- ])
- );
-}
-
function joinNames(names) {
return names.join(", ");
}
-
-function relationLabel(relation) {
- return relation?.username ?? relation?.title ?? relation?.name;
-}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/result-columns.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/result-columns.js
new file mode 100644
index 00000000000..897d7dda9b8
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/result-columns.js
@@ -0,0 +1,102 @@
+import Badge from "discourse/models/badge";
+import BadgeViewComponent from "../components/result-types/badge";
+import CategoryViewComponent from "../components/result-types/category";
+import GroupViewComponent from "../components/result-types/group";
+import HtmlViewComponent from "../components/result-types/html";
+import JsonViewComponent from "../components/result-types/json";
+import PostViewComponent from "../components/result-types/post";
+import ReltimeViewComponent from "../components/result-types/reltime";
+import TagGroupViewComponent from "../components/result-types/tag-group";
+import TextViewComponent from "../components/result-types/text";
+import TopicViewComponent from "../components/result-types/topic";
+import UrlViewComponent from "../components/result-types/url";
+import UserViewComponent from "../components/result-types/user";
+
+export const VIEW_COMPONENTS = {
+ topic: TopicViewComponent,
+ text: TextViewComponent,
+ post: PostViewComponent,
+ reltime: ReltimeViewComponent,
+ badge: BadgeViewComponent,
+ url: UrlViewComponent,
+ user: UserViewComponent,
+ group: GroupViewComponent,
+ html: HtmlViewComponent,
+ json: JsonViewComponent,
+ category: CategoryViewComponent,
+ tag_group: TagGroupViewComponent,
+};
+
+export function transformedRelTable(table, modelClass) {
+ return Object.fromEntries(
+ (table ?? []).map((item) => [
+ item.id,
+ modelClass ? modelClass.create(item) : item,
+ ])
+ );
+}
+
+export function relationLabel(relation) {
+ return relation?.username ?? relation?.title ?? relation?.name;
+}
+
+export function buildRelationTables(relations, site) {
+ const tables = {
+ group: site.groupsById,
+ category: transformedRelTable(site.categories),
+ };
+
+ for (const [type, table] of Object.entries(relations ?? {})) {
+ if (tables[type]) {
+ continue;
+ }
+
+ tables[type] = transformedRelTable(
+ table,
+ type === "badge" ? Badge : undefined
+ );
+ }
+
+ return tables;
+}
+
+export function buildColumnComponents(
+ content,
+ relationTables,
+ viewComponents = VIEW_COMPONENTS
+) {
+ const {
+ columns,
+ colrender = {},
+ hidden_relations: hiddenRelations = {},
+ } = content ?? {};
+
+ if (!columns) {
+ return [];
+ }
+
+ return columns.map((_, idx) => {
+ const requested = colrender[idx];
+ const type = requested && viewComponents[requested] ? requested : "text";
+
+ return {
+ name: type,
+ component: viewComponents[type],
+ table: relationTables[type],
+ hidden: hiddenRelations[type],
+ };
+ });
+}
+
+export function displayColumnNames(columns) {
+ return (columns ?? []).map((colName) => {
+ if (colName.endsWith("_id")) {
+ return colName.slice(0, -3);
+ }
+ const dIdx = colName.indexOf("$");
+ if (dIdx >= 0) {
+ return colName.substring(dIdx + 1);
+ }
+ return colName;
+ });
+}
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
index dfe0906f7a7..a5c0f93033b 100644
--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -15,6 +15,11 @@
&__table {
overflow: auto;
font-size: var(--font-down-2);
+
+ th,
+ td {
+ white-space: nowrap;
+ }
}
&__empty {
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/admin-dashboard-card-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/admin-dashboard-card-test.gjs
new file mode 100644
index 00000000000..0c659195c80
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/admin-dashboard-card-test.gjs
@@ -0,0 +1,200 @@
+import { find, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import loadChartJS from "discourse/lib/load-chart-js";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DataExplorerAdminDashboardCard from "../../discourse/components/admin-dashboard-card";
+
+function cell(row, col) {
+ return `.de-dashboard-card__table tbody tr:nth-child(${row}) td:nth-child(${col})`;
+}
+
+async function chartData() {
+ const Chart = await loadChartJS();
+ return Chart.getChart(find("canvas")).data;
+}
+
+module(
+ "Integration | Component | DataExplorerAdminDashboardCard",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders topics as links", async function (assert) {
+ const payload = {
+ colrender: { 0: "topic" },
+ relations: {
+ topic: [
+ {
+ id: 7,
+ title: "Hello world",
+ fancy_title: "Hello world",
+ slug: "hello-world",
+ posts_count: 3,
+ },
+ ],
+ },
+ columns: ["topic_id", "views", "replies"],
+ rows: [
+ [7, 10, 1],
+ [8, 20, 2],
+ ],
+ };
+
+ await render(
+ <template>
+ <DataExplorerAdminDashboardCard @payload={{payload}} />
+ </template>
+ );
+
+ assert
+ .dom(".de-dashboard-card__table thead th:nth-child(1)")
+ .hasText("topic", "strips the id suffix from the header");
+ assert
+ .dom(`${cell(1, 1)} a`)
+ .hasAttribute("href", "/t/hello-world/7", "links to the topic")
+ .hasText("Hello world", "renders the title");
+ assert
+ .dom(cell(2, 1))
+ .hasText("8", "renders an unresolved topic id as text");
+ });
+
+ test("renders categories and parent categories from the site", async function (assert) {
+ const payload = {
+ colrender: { 0: "category", 1: "category" },
+ columns: ["category_id", "parent_category_id", "topics"],
+ rows: [[3, 3, 5]],
+ };
+
+ await render(
+ <template>
+ <DataExplorerAdminDashboardCard @payload={{payload}} />
+ </template>
+ );
+
+ assert
+ .dom(".de-dashboard-card__table thead th:nth-child(2)")
+ .hasText("parent category", "strips the id suffix and underscores");
+ assert
+ .dom(`${cell(1, 1)} .badge-category__name`)
+ .hasText("meta", "renders the category badge");
+ assert
+ .dom(`${cell(1, 2)} .badge-category__name`)
+ .hasText("meta", "renders the parent category badge");
+ });
+
+ test("renders users, badges, and groups", async function (assert) {
+ const payload = {
+ colrender: { 0: "user", 1: "badge", 2: "group" },
+ relations: {
+ user: [
+ {
+ id: 1,
+ username: "eviltrout",
+ avatar_template: "/images/avatar.png",
+ },
+ ],
+ badge: [
+ {
+ id: 1,
+ name: "badge name",
+ display_name: "badge display name",
+ icon: "user",
+ },
+ ],
+ },
+ columns: ["user_id", "badge_id", "group_id", "count"],
+ rows: [[1, 1, 1, 4]],
+ };
+
+ await render(
+ <template>
+ <DataExplorerAdminDashboardCard @payload={{payload}} />
+ </template>
+ );
+
+ assert
+ .dom(`${cell(1, 1)} a[data-user-card="eviltrout"]`)
+ .exists("renders the user link");
+ assert
+ .dom(`${cell(1, 2)} .badge-display-name`)
+ .hasText("badge display name", "renders the badge");
+ assert
+ .dom(`${cell(1, 3)} a`)
+ .hasText("admins", "resolves the group from the site");
+ });
+
+ test("renders post ids as plain text", async function (assert) {
+ const payload = {
+ colrender: { 0: "post" },
+ relations: {
+ post: [
+ {
+ id: 1,
+ topic_id: 1,
+ post_number: 1,
+ excerpt: "foo",
+ username: "user1",
+ avatar_template: "",
+ },
+ ],
+ },
+ columns: ["post_id", "likes", "flags"],
+ rows: [[1, 2, 0]],
+ };
+
+ await render(
+ <template>
+ <DataExplorerAdminDashboardCard @payload={{payload}} />
+ </template>
+ );
+
+ assert.dom(cell(1, 1)).hasText("1", "keeps the raw id");
+ assert
+ .dom(`${cell(1, 1)} aside`)
+ .doesNotExist("does not render the post excerpt");
+ });
+
+ test("marks relations hidden from the current user", async function (assert) {
+ const payload = {
+ colrender: { 0: "topic" },
+ relations: { topic: [] },
+ hidden_relations: { topic: [42] },
+ columns: ["topic_id", "views", "replies"],
+ rows: [[42, 1, 0]],
+ };
+
+ await render(
+ <template>
+ <DataExplorerAdminDashboardCard @payload={{payload}} />
+ </template>
+ );
+
+ assert
+ .dom(`${cell(1, 1)} .query-result-hidden`)
+ .hasText("42", "keeps the id with the hidden marker");
+ });
+
+ test("labels chart entries with the resolved relation", async function (assert) {
+ const payload = {
+ colrender: { 0: "category" },
+ columns: ["category_id", "count"],
+ rows: [
+ [3, 10],
+ [999, 20],
+ ],
+ };
+
+ await render(
+ <template>
+ <DataExplorerAdminDashboardCard @payload={{payload}} />
+ </template>
+ );
+
+ assert.dom("canvas").exists("renders a chart for two-column results");
+ assert.deepEqual(
+ (await chartData()).labels,
+ ["meta", 999],
+ "uses the category name and falls back to the raw id"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-data-explorer/test/javascripts/unit/lib/result-columns-test.js b/plugins/discourse-data-explorer/test/javascripts/unit/lib/result-columns-test.js
new file mode 100644
index 00000000000..eb8668dbaab
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/unit/lib/result-columns-test.js
@@ -0,0 +1,90 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import {
+ buildColumnComponents,
+ buildRelationTables,
+ displayColumnNames,
+ relationLabel,
+ VIEW_COMPONENTS,
+} from "../../discourse/lib/result-columns";
+
+module("Unit | Lib | result-columns", function (hooks) {
+ setupTest(hooks);
+
+ test("displayColumnNames strips id suffixes and type prefixes", function (assert) {
+ assert.deepEqual(
+ displayColumnNames(["topic_id", "topic$latest", "count"]),
+ ["topic", "latest", "count"],
+ "keeps plain names untouched"
+ );
+ });
+
+ test("displayColumnNames handles missing columns", function (assert) {
+ assert.deepEqual(
+ displayColumnNames(undefined),
+ [],
+ "returns an empty list"
+ );
+ });
+
+ test("relationLabel prefers username, then title, then name", function (assert) {
+ assert.strictEqual(relationLabel({ username: "u", title: "t" }), "u");
+ assert.strictEqual(relationLabel({ title: "t", name: "n" }), "t");
+ assert.strictEqual(relationLabel({ name: "n" }), "n");
+ assert.strictEqual(relationLabel(undefined), undefined);
+ });
+
+ test("buildRelationTables seeds categories and groups from the site", function (assert) {
+ const site = this.owner.lookup("service:site");
+ const tables = buildRelationTables(
+ { topic: [{ id: 7, title: "Seven" }], category: [] },
+ site
+ );
+
+ assert.strictEqual(tables.category[3].name, "meta", "uses site categories");
+ assert.strictEqual(tables.group[1].name, "admins", "uses site groups");
+ assert.strictEqual(
+ tables.topic[7].title,
+ "Seven",
+ "indexes relations by id"
+ );
+ });
+
+ test("buildColumnComponents maps colrender types to components", function (assert) {
+ const content = {
+ columns: ["topic_id", "count"],
+ colrender: { 0: "topic" },
+ hidden_relations: { topic: [42] },
+ };
+ const tables = { topic: { 7: { id: 7 } } };
+
+ const [topic, count] = buildColumnComponents(content, tables);
+
+ assert.strictEqual(topic.name, "topic");
+ assert.strictEqual(topic.component, VIEW_COMPONENTS.topic);
+ assert.strictEqual(topic.table, tables.topic);
+ assert.deepEqual(topic.hidden, [42]);
+ assert.strictEqual(count.name, "text");
+ assert.strictEqual(count.table, undefined);
+ });
+
+ test("buildColumnComponents falls back to text for types outside the view map", function (assert) {
+ const content = {
+ columns: ["post_id"],
+ colrender: { 0: "post" },
+ };
+ const tables = { post: { 1: { id: 1 } } };
+
+ const [post] = buildColumnComponents(content, tables, {
+ text: VIEW_COMPONENTS.text,
+ topic: VIEW_COMPONENTS.topic,
+ });
+
+ assert.strictEqual(post.name, "text", "treats the column as text");
+ assert.strictEqual(post.table, undefined, "does not attach a lookup table");
+ });
+
+ test("buildColumnComponents handles a payload without columns", function (assert) {
+ assert.deepEqual(buildColumnComponents(undefined, {}), []);
+ });
+});