A platform for community discussion. Free, open, simple.
DEV: Remove duplication in the new admin dashboard (#41374)
Alan Guo Xiang Tan4c78a8add7f2
diff --git a/frontend/discourse/admin/components/dashboard/engagement/headline.gjs b/frontend/discourse/admin/components/dashboard/engagement/headline.gjsindex f18a4132c76..20d7232cced 100644--- a/frontend/discourse/admin/components/dashboard/engagement/headline.gjs+++ b/frontend/discourse/admin/components/dashboard/engagement/headline.gjs@@ -1,9 +1,13 @@import Component from "@glimmer/component";import { concat } from "@ember/helper";import { LinkTo } from "@ember/routing";+import {+ formatDeltaPercent,+ formatKpiValue,+} from "discourse/admin/lib/dashboard-format";import DTooltip from "discourse/float-kit/components/d-tooltip";import { eq } from "discourse/truth-helpers";-import I18n, { i18n } from "discourse-i18n";+import { i18n } from "discourse-i18n";const PRESET_PERIODS = ["last_7_days", "last_30_days", "last_3_months"];const PERCENTAGE_KPIS = ["dau_mau"];@@ -14,14 +18,9 @@ class MetricItem extends Component {}get displayValue() {- const value = this.args.metric.value;- if (value == null) {- return "—";- }- if (this.isPercentage) {- return `${I18n.toNumber(value, { precision: 1 })}%`;- }- return I18n.toNumber(value, { precision: 0 });+ return formatKpiValue(this.args.metric.value, {+ percentage: this.isPercentage,+ });}get hasDelta() {@@ -39,17 +38,7 @@ class MetricItem extends Component {}get deltaText() {- const value = this.args.metric.percent_change;- const abs = Math.abs(value);-- if (abs > 0 && abs < 1) {- const sign = value > 0 ? "+" : "-";- return `${sign}${I18n.toNumber(abs, { precision: 1 })}%`;- }-- const rounded = Math.round(value);- const sign = rounded > 0 ? "+" : "";- return `${sign}${I18n.toNumber(rounded, { precision: 0 })}%`;+ return formatDeltaPercent(this.args.metric.percent_change);}<template>diff --git a/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs b/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjsindex c633c5fe7a8..8fcab686c7c 100644--- a/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs+++ b/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs@@ -28,13 +28,21 @@ export default class WhosPosting extends Component {return (category?.subcategories?.length ?? 0) > 0;}+ get #categoryFilters() {+ if (!this.categoryId) {+ return null;+ }+ const filters = { category: this.categoryId };+ if (this.includeSubcategories) {+ filters.include_subcategories = true;+ }+ return filters;+ }+get reportQuery() {const query = {};- if (this.categoryId) {- const filters = { category: this.categoryId };- if (this.includeSubcategories) {- filters.include_subcategories = true;- }+ const filters = this.#categoryFilters;+ if (filters) {query.filters = filters;}if (this.args.startDate) {@@ -110,11 +118,9 @@ export default class WhosPosting extends Component {start_date: this.args.startDate?.toISOString().slice(0, 10),end_date: this.args.endDate?.toISOString().slice(0, 10),};- if (this.categoryId) {- data.filters = { category: this.categoryId };- if (this.includeSubcategories) {- data.filters.include_subcategories = true;- }+ const filters = this.#categoryFilters;+ if (filters) {+ data.filters = filters;}try {diff --git a/frontend/discourse/admin/components/dashboard/kpi-tile.gjs b/frontend/discourse/admin/components/dashboard/kpi-tile.gjsindex 7fe20de845b..2a129fd8953 100644--- a/frontend/discourse/admin/components/dashboard/kpi-tile.gjs+++ b/frontend/discourse/admin/components/dashboard/kpi-tile.gjs@@ -3,9 +3,13 @@ import { concat, hash } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import { LinkTo } from "@ember/routing";+import {+ formatDeltaPercent,+ formatKpiValue,+} from "discourse/admin/lib/dashboard-format";import DTooltip from "discourse/float-kit/components/d-tooltip";import dIcon from "discourse/ui-kit/helpers/d-icon";-import I18n, { i18n } from "discourse-i18n";+import { i18n } from "discourse-i18n";const PERCENTAGE_KPIS = ["dau_mau"];@@ -15,14 +19,7 @@ export default class KpiTile extends Component {}get displayValue() {- const value = this.args.value;- if (value == null) {- return "—";- }- if (this.isPercentage) {- return `${I18n.toNumber(value, { precision: 1 })}%`;- }- return I18n.toNumber(value, { precision: 0 });+ return formatKpiValue(this.args.value, { percentage: this.isPercentage });}get label() {@@ -42,17 +39,7 @@ export default class KpiTile extends Component {}get deltaText() {- const value = this.args.percentChange;- const abs = Math.abs(value);-- if (abs > 0 && abs < 1) {- const sign = value > 0 ? "+" : "-";- return `${sign}${I18n.toNumber(abs, { precision: 1 })}%`;- }-- const rounded = Math.round(value);- const sign = rounded > 0 ? "+" : "";- return `${sign}${I18n.toNumber(rounded, { precision: 0 })}%`;+ return formatDeltaPercent(this.args.percentChange);}get ariaLabel() {diff --git a/frontend/discourse/admin/components/dashboard/reports.gjs b/frontend/discourse/admin/components/dashboard/reports.gjsindex f22f5d42a26..87e5f266107 100644--- a/frontend/discourse/admin/components/dashboard/reports.gjs+++ b/frontend/discourse/admin/components/dashboard/reports.gjs@@ -20,8 +20,6 @@ import { i18n } from "discourse-i18n";const VISIBLE_CAP = 10;-const rendererFor = (source) => lookupAdminDashboardReportRenderer(source);-export default class DashboardReports extends Component {@service currentUser;@service modal;@@ -39,6 +37,13 @@ export default class DashboardReports extends Component {return this.args.data?.items ?? [];}+ get layoutItems() {+ return this.items.map(({ source, identifier }) => ({+ source,+ identifier,+ }));+ }+get canEdit() {return this.currentUser?.admin;}@@ -69,10 +74,7 @@ export default class DashboardReports extends Component {this.loading = true;try {const payloads = await loadDashboardReports({- items: this.items.map(({ source, identifier }) => ({- source,- identifier,- })),+ items: this.layoutItems,filters: this.filters,});this.cards = this.items.map((item) => ({@@ -95,11 +97,9 @@ export default class DashboardReports extends Component {@actionasync removeReport(item) {- const nextItems = this.items- .filter(- (i) => !(i.source === item.source && i.identifier === item.identifier)- )- .map(({ source, identifier }) => ({ source, identifier }));+ const nextItems = this.layoutItems.filter(+ (i) => !(i.source === item.source && i.identifier === item.identifier)+ );try {await ajax("/admin/dashboard/reports/layout", {@@ -155,7 +155,10 @@ export default class DashboardReports extends Component {{{#if card.payload.empty}}<DashboardReportEmptyState />{{else}}- {{#let (rendererFor card.source) as |Renderer|}}+ {{#let+ (lookupAdminDashboardReportRenderer card.source)+ as |Renderer|+ }}{{#if Renderer}}<Renderer@item={{card}}diff --git a/frontend/discourse/admin/components/dashboard/search.gjs b/frontend/discourse/admin/components/dashboard/search.gjsindex cf2bb8e385f..0445d76a5cc 100644--- a/frontend/discourse/admin/components/dashboard/search.gjs+++ b/frontend/discourse/admin/components/dashboard/search.gjs@@ -4,6 +4,7 @@ import { LinkTo } from "@ember/routing";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import DashboardSection from "discourse/admin/components/dashboard/section";+import { formatDeltaPercent } from "discourse/admin/lib/dashboard-format";import DTooltip from "discourse/float-kit/components/d-tooltip";import dBasePath from "discourse/ui-kit/helpers/d-base-path";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@@ -19,19 +20,6 @@ function formatCount(value) {return I18n.toNumber(value, { precision: 0 });}-function formatDelta(value) {- const abs = Math.abs(value);-- if (abs > 0 && abs < 1) {- const sign = value > 0 ? "+" : "-";- return `${sign}${I18n.toNumber(abs, { precision: 1 })}%`;- }-- const rounded = Math.round(value);- const sign = rounded > 0 ? "+" : "";- return `${sign}${I18n.toNumber(rounded, { precision: 0 })}%`;-}-function badgeLabel(status) {return i18n(`admin.dashboard.sections.search.content_gaps.badge.${status}`);}@@ -84,7 +72,7 @@ export default class DashboardSearch extends Component {}return {- text: formatDelta(change),+ text: formatDeltaPercent(change),className: change > 0 ? "--pos" : "--neg",};}@@ -102,7 +90,7 @@ export default class DashboardSearch extends Component {}return {- text: formatDelta(change),+ text: formatDeltaPercent(change),className: change > 0 ? "--neg" : "--pos",};}diff --git a/frontend/discourse/admin/components/dashboard/traffic.gjs b/frontend/discourse/admin/components/dashboard/traffic.gjsindex 65f8ecd77d9..dcaf1df9e5a 100644--- a/frontend/discourse/admin/components/dashboard/traffic.gjs+++ b/frontend/discourse/admin/components/dashboard/traffic.gjs@@ -31,7 +31,7 @@ export default class DashboardTraffic extends Component {hiddenLabels = ["page_view_crawler"];get browserPageviews() {- return this.args.traffic?.kpis?.browser_pageviews?.value ?? 0;+ return this.#kpiValue("browser_pageviews") ?? 0;}get headlineCount() {@@ -87,21 +87,23 @@ export default class DashboardTraffic extends Component {}get showLoggedInShare() {- const loggedInShare = this.args.traffic?.kpis?.logged_in_share?.value;- return loggedInShare !== null && loggedInShare !== undefined;+ return this.#kpiValue("logged_in_share") != null;}get loggedInShare() {- return `${this.args.traffic?.kpis?.logged_in_share?.value ?? 0}%`;+ return `${this.#kpiValue("logged_in_share") ?? 0}%`;}get showDirectTraffic() {- const directTraffic = this.args.traffic?.kpis?.direct_traffic?.value;- return directTraffic !== null && directTraffic !== undefined;+ return this.#kpiValue("direct_traffic") != null;}get directTraffic() {- return `${this.args.traffic?.kpis?.direct_traffic?.value ?? 0}%`;+ return `${this.#kpiValue("direct_traffic") ?? 0}%`;+ }++ #kpiValue(key) {+ return this.args.traffic?.kpis?.[key]?.value;}get chartModel() {@@ -226,11 +228,6 @@ export default class DashboardTraffic extends Component {</DTooltip>{{/if}}</h3>- {{! <p>- Placeholder: Logged-in traffic is growing steadily. Two spikes on- Mar 8-9 drove a burst of anonymous visitors who didn't log in,- pulling the logged-in share down slightly to 38%.- </p> }}</div>{{#if (or this.showLoggedInShare this.showDirectTraffic)}}@@ -286,11 +283,6 @@ export default class DashboardTraffic extends Component {{{/if}}</div>- {{! <div class="db-section__callout">- Placeholder: Spikes on Mar 8 and Mar 9 - a Hacker News post linking to- the plugin release docs drove a surge in anonymous pageviews.- </div> }}-{{#if @fetchError}}<div class="db-section__traffic-chart"><div class="db-section__traffic-chart-message" role="alert">diff --git a/frontend/discourse/admin/controllers/admin/dashboard.js b/frontend/discourse/admin/controllers/admin/dashboard.jsindex 434919c030d..1c88925a78e 100644--- a/frontend/discourse/admin/controllers/admin/dashboard.js+++ b/frontend/discourse/admin/controllers/admin/dashboard.js@@ -53,23 +53,24 @@ export default class AdminDashboardController extends Controller {}get startDate() {- if (this.safePeriod === PERIOD_CUSTOM && this.start_date) {- const parsed = moment(this.start_date, "YYYY-MM-DD", true);- if (parsed.isValid()) {- return parsed.startOf("day").toDate();- }- }- return calculatePresetStartDate(this.safePeriod);+ return (+ this.#customDate(this.start_date, "startOf") ??+ calculatePresetStartDate(this.safePeriod)+ );}get endDate() {- if (this.safePeriod === PERIOD_CUSTOM && this.end_date) {- const parsed = moment(this.end_date, "YYYY-MM-DD", true);- if (parsed.isValid()) {- return parsed.endOf("day").toDate();- }+ return (+ this.#customDate(this.end_date, "endOf") ?? moment().endOf("day").toDate()+ );+ }++ #customDate(value, edge) {+ if (this.safePeriod !== PERIOD_CUSTOM || !value) {+ return null;}- return moment().endOf("day").toDate();+ const parsed = moment(value, "YYYY-MM-DD", true);+ return parsed.isValid() ? parsed[edge]("day").toDate() : null;}@actiondiff --git a/frontend/discourse/admin/lib/dashboard-format.js b/frontend/discourse/admin/lib/dashboard-format.jsnew file mode 100644index 00000000000..65de9cff800--- /dev/null+++ b/frontend/discourse/admin/lib/dashboard-format.js@@ -0,0 +1,24 @@+import I18n from "discourse-i18n";++export function formatKpiValue(value, { percentage = false } = {}) {+ if (value == null) {+ return "—";+ }+ if (percentage) {+ return `${I18n.toNumber(value, { precision: 1 })}%`;+ }+ return I18n.toNumber(value, { precision: 0 });+}++export function formatDeltaPercent(value) {+ const abs = Math.abs(value);++ if (abs > 0 && abs < 1) {+ const sign = value > 0 ? "+" : "-";+ return `${sign}${I18n.toNumber(abs, { precision: 1 })}%`;+ }++ const rounded = Math.round(value);+ const sign = rounded > 0 ? "+" : "";+ return `${sign}${I18n.toNumber(rounded, { precision: 0 })}%`;+}diff --git a/frontend/discourse/tests/unit/admin/lib/dashboard-format-test.js b/frontend/discourse/tests/unit/admin/lib/dashboard-format-test.jsnew file mode 100644index 00000000000..e7066a9bc2c--- /dev/null+++ b/frontend/discourse/tests/unit/admin/lib/dashboard-format-test.js@@ -0,0 +1,50 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import {+ formatDeltaPercent,+ formatKpiValue,+} from "discourse/admin/lib/dashboard-format";++module("Unit | Admin | Lib | dashboard-format", function (hooks) {+ setupTest(hooks);++ module("formatKpiValue", function () {+ test("returns an em dash when the value is null", function (assert) {+ assert.strictEqual(formatKpiValue(null), "—");+ });++ test("returns an em dash when the value is undefined", function (assert) {+ assert.strictEqual(formatKpiValue(undefined), "—");+ });++ test("formats a count with no decimals and a thousands separator", function (assert) {+ assert.strictEqual(formatKpiValue(1100), "1,100");+ });++ test("formats a percentage value with a percent suffix and one decimal", function (assert) {+ assert.strictEqual(formatKpiValue(21.6, { percentage: true }), "21.6%");+ });+ });++ module("formatDeltaPercent", function () {+ test("prefixes a positive delta with a plus and rounds to a whole percent", function (assert) {+ assert.strictEqual(formatDeltaPercent(12.02), "+12%");+ });++ test("keeps one decimal for a sub-1% positive delta", function (assert) {+ assert.strictEqual(formatDeltaPercent(0.4), "+0.4%");+ });++ test("keeps one decimal and a minus sign for a sub-1% negative delta", function (assert) {+ assert.strictEqual(formatDeltaPercent(-0.4), "-0.4%");+ });++ test("renders an exact-zero delta without a sign", function (assert) {+ assert.strictEqual(formatDeltaPercent(0), "0%");+ });++ test("rounds a larger negative delta and keeps the minus sign", function (assert) {+ assert.strictEqual(formatDeltaPercent(-38.5), "-38%");+ });+ });+});