A platform for community discussion. Free, open, simple.
FEATURE: resizable report cards on the admin dashboard (#43002)
Osama Sayegh95f26f1377ec
diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scssindex 6b11d8c444d..29c602e22f1 100644--- a/app/assets/stylesheets/admin/admin_dashboard.scss+++ b/app/assets/stylesheets/admin/admin_dashboard.scss@@ -486,6 +486,7 @@ $db-bar-height: var(--space-2);&.--grid {display: grid;grid-template-columns: repeat(2, minmax(0, 1fr));+ grid-auto-rows: 320px;gap: var(--space-4);@include viewport.until(sm) {diff --git a/app/assets/stylesheets/admin/dashboard/reports.scss b/app/assets/stylesheets/admin/dashboard/reports.scssindex 34d6c2016a8..4ff00bf8df6 100644--- a/app/assets/stylesheets/admin/dashboard/reports.scss+++ b/app/assets/stylesheets/admin/dashboard/reports.scss@@ -2,6 +2,7 @@.db-report {&__card {+ position: relative;border: 1px solid var(--content-border-color);border-radius: var(--d-border-radius-large);padding: var(--space-4);@@ -13,9 +14,109 @@gap: var(--space-2);@include viewport.until(sm) {- position: relative;padding-inline: 0;}++ &.--wide {+ grid-column: 1 / -1;+ }++ &.--wide,+ &.--rows-2,+ &.--rows-3,+ &.--rows-4 {+ .db-report__chart {+ overflow-y: auto;+ }+ }++ @for $rows from 2 through 4 {+ &.--rows-#{$rows} {+ grid-row: span #{$rows};+ height: auto;+ }+ }++ &.--floating {+ position: fixed;+ z-index: 100;+ }++ &.--resize-placeholder {+ margin: calc(var(--space-2) * -1);+ border-style: dashed;+ border-color: var(--tertiary);+ background: var(--tertiary-low);++ &:not(.--rows-2, .--rows-3, .--rows-4) {+ height: calc(320px + var(--space-2) * 2);+ }+ }++ &:hover .db-report__resize-handle,+ &:focus-within .db-report__resize-handle {+ opacity: 1;+ }+ }++ &__resize-handle {+ position: absolute;+ bottom: 2px;+ width: 12px;+ height: 12px;+ opacity: 0.35;++ @media (prefers-reduced-motion: no-preference) {+ transition: opacity 0.15s ease;+ }++ &.--se {+ /*! rtl:ignore */+ right: 2px;++ /*! rtl:ignore */+ cursor: nwse-resize;++ /*! rtl:ignore */+ clip-path: polygon(100% 0, 100% 100%, 0 100%);++ /*! rtl:ignore */+ background: repeating-linear-gradient(+ 135deg,+ var(--primary-medium) 0,+ var(--primary-medium) 1px,+ transparent 1px,+ transparent 4px+ );+ }++ &.--sw {+ /*! rtl:ignore */+ left: 2px;++ /*! rtl:ignore */+ cursor: nesw-resize;++ /*! rtl:ignore */+ clip-path: polygon(0 0, 100% 100%, 0 100%);++ /*! rtl:ignore */+ background: repeating-linear-gradient(+ 45deg,+ var(--primary-medium) 0,+ var(--primary-medium) 1px,+ transparent 1px,+ transparent 4px+ );+ }++ &.--resizing {+ opacity: 1;+ }++ @include viewport.until(sm) {+ display: none;+ }}&__header {diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rbindex 94414f5a0b2..18e5b4a43e8 100644--- a/app/controllers/admin/dashboard_controller.rb+++ b/app/controllers/admin/dashboard_controller.rb@@ -225,13 +225,27 @@ class Admin::DashboardController < Admin::StaffControllerendparams- .permit(items: %i[source identifier])+ .permit(items: %i[source identifier rows cols]).fetch(:items, []).map do |entry|source = entry[:source]identifier = entry[:identifier]raise Discourse::InvalidParameters.new(:items) if source.blank? || identifier.blank?- { source: source.to_s, identifier: identifier.to_s }++ rows = Integer(entry[:rows].presence || 1, exception: false)+ if rows.nil? || rows < 1 || rows > AdminDashboardReport::MAX_ROWS+ raise Discourse::InvalidParameters.new(:items)+ end++ cols = Integer(entry[:cols].presence || 1, exception: false)+ if cols.nil? || cols < 1 || cols > AdminDashboardReport::MAX_COLS+ raise Discourse::InvalidParameters.new(:items)+ end+ if rows > 1 && cols != AdminDashboardReport::MAX_COLS+ raise Discourse::InvalidParameters.new(:items)+ end++ { source: source.to_s, identifier: identifier.to_s, rows: rows, cols: cols }endendenddiff --git a/app/models/admin_dashboard_report.rb b/app/models/admin_dashboard_report.rbindex b86b7fcb17e..88e98beea57 100644--- a/app/models/admin_dashboard_report.rb+++ b/app/models/admin_dashboard_report.rb@@ -2,11 +2,26 @@class AdminDashboardReport < ActiveRecord::BaseVISIBLE_CAP = 10+ MAX_ROWS = 4+ MAX_COLS = 2validates :source, presence: truevalidates :identifier, presence: truevalidates :identifier, uniqueness: { scope: :source }+ validates :rows,+ numericality: {+ only_integer: true,+ greater_than_or_equal_to: 1,+ less_than_or_equal_to: MAX_ROWS,+ }+ validates :cols,+ numericality: {+ only_integer: true,+ greater_than_or_equal_to: 1,+ less_than_or_equal_to: MAX_COLS,+ }validate :source_must_be_registered+ validate :multi_row_cards_must_be_full_widthbefore_validation :assign_default_position, on: :create@@ -21,6 +36,11 @@ class AdminDashboardReport < ActiveRecord::Basereturn if AdminDashboard::Reports::Registry.provider_for(source)errors.add(:source, :invalid)end++ def multi_row_cards_must_be_full_width+ return if rows.to_i <= 1 || cols.to_i == MAX_COLS+ errors.add(:cols, :invalid)+ endend# == Schema Information@@ -28,8 +48,10 @@ end# Table name: admin_dashboard_reports## id :bigint not null, primary key+# cols :integer default(1), not null# identifier :string not null# position :integer not null+# rows :integer default(1), not null# source :string not null# created_at :datetime not null# updated_at :datetime not nulldiff --git a/db/migrate/20260826090055_add_rows_to_admin_dashboard_reports.rb b/db/migrate/20260826090055_add_rows_to_admin_dashboard_reports.rbnew file mode 100644index 00000000000..2d8be475cd3--- /dev/null+++ b/db/migrate/20260826090055_add_rows_to_admin_dashboard_reports.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddRowsToAdminDashboardReports < ActiveRecord::Migration[8.0]+ def change+ add_column :admin_dashboard_reports, :rows, :integer, null: false, default: 1+ end+enddiff --git a/db/migrate/20260827064809_add_cols_to_admin_dashboard_reports.rb b/db/migrate/20260827064809_add_cols_to_admin_dashboard_reports.rbnew file mode 100644index 00000000000..8cfbcfaf217--- /dev/null+++ b/db/migrate/20260827064809_add_cols_to_admin_dashboard_reports.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddColsToAdminDashboardReports < ActiveRecord::Migration[8.0]+ def change+ add_column :admin_dashboard_reports, :cols, :integer, null: false, default: 1+ end+enddiff --git a/db/structure.sql b/db/structure.sqlindex 0d315803a12..eae1af0412c 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -307,7 +307,9 @@ CREATE TABLE public.admin_dashboard_reports (source character varying NOT NULL,identifier character varying NOT NULL,created_at timestamp(6) without time zone NOT NULL,- updated_at timestamp(6) without time zone NOT NULL+ updated_at timestamp(6) without time zone NOT NULL,+ rows integer DEFAULT 1 NOT NULL,+ cols integer DEFAULT 1 NOT NULL);@@ -23422,7 +23424,9 @@ SET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES('20260828145150'),+('20260827064809'),('20260826124054'),+('20260826090055'),('20260824091843'),('20260824072257'),('20260824051214'),diff --git a/frontend/discourse/admin/components/dashboard/reports.gjs b/frontend/discourse/admin/components/dashboard/reports.gjsindex 3ac7dc9795e..284399936fe 100644--- a/frontend/discourse/admin/components/dashboard/reports.gjs+++ b/frontend/discourse/admin/components/dashboard/reports.gjs@@ -1,10 +1,11 @@import Component from "@glimmer/component";import { cached, tracked } from "@glimmer/tracking";-import { concat, hash } from "@ember/helper";+import { concat, fn, hash } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import didUpdate from "@ember/render-modifiers/modifiers/did-update";import { service } from "@ember/service";+import Modifier from "ember-modifier";import DashboardReportEmptyState from "discourse/admin/components/dashboard/report-empty-state";import DashboardReportErrorState from "discourse/admin/components/dashboard/report-error-state";import DashboardSection from "discourse/admin/components/dashboard/section";@@ -15,12 +16,111 @@ import PluginOutlet from "discourse/components/plugin-outlet";import lazyHash from "discourse/helpers/lazy-hash";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";+import { isTesting } from "discourse/lib/environment";+import { isDocumentRTL } from "discourse/lib/text-direction";+import { prefersReducedMotion } from "discourse/lib/utilities";+import { eq, gt } from "discourse/truth-helpers";import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";+import DResizeHandles from "discourse/ui-kit/d-resize-handles";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";const VISIBLE_CAP = 10;+const MAX_ROWS = 4;+const MAX_COLS = 2;++function computeColumns(cardsLike) {+ const columns = new Map();+ let cursor = 0;+ for (const card of cardsLike) {+ if (card.cols > 1) {+ columns.set(card.key, null);+ cursor = 0;+ } else {+ columns.set(card.key, cursor);+ cursor = cursor === 0 ? 1 : 0;+ }+ }+ return columns;+}++function clampBetween(value, a, b) {+ const lo = Math.min(a, b);+ const hi = Math.max(a, b);+ return Math.min(Math.max(value, lo), hi);+}++class AnimateReflow extends Modifier {+ previousRect = null;+ previousSignature = null;++ modify(element, [signature], { disabled }) {+ if (disabled) {+ this.previousRect = null;+ return;+ }++ if (prefersReducedMotion() || isTesting()) {+ return;+ }++ const firstRun = !this.previousRect;+ if (!firstRun && signature === this.previousSignature) {+ return;+ }+ this.previousSignature = signature;++ if (!firstRun) {+ element.style.transition = "none";+ element.style.transform = "";+ }++ const rect = element.getBoundingClientRect();+ const previous = this.previousRect;+ this.previousRect = rect;++ if (!previous) {+ return;+ }++ const dx = previous.left - rect.left;+ const dy = previous.top - rect.top;+ const scaleX = previous.width / rect.width;+ const scaleY = previous.height / rect.height;+ if (!dx && !dy && scaleX === 1 && scaleY === 1) {+ element.style.transition = "";+ return;+ }++ element.style.transformOrigin = "top left";+ element.style.transform = `translate(${dx}px, ${dy}px) scale(${scaleX}, ${scaleY})`;++ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ element.style.transition = "transform 0.2s ease-out";+ element.style.transform = "";+ });+ });+ }+}++class FollowPointer extends Modifier {+ modify(element, [rect]) {+ if (!rect) {+ element.style.left = "";+ element.style.top = "";+ element.style.width = "";+ element.style.height = "";+ return;+ }++ element.style.left = `${rect.left}px`;+ element.style.top = `${rect.top}px`;+ element.style.width = `${rect.width}px`;+ element.style.height = `${rect.height}px`;+ }+}export default class DashboardReports extends Component {@service currentUser;@@ -28,6 +128,27 @@ export default class DashboardReports extends Component {@tracked cards = [];@tracked loading = false;+ @tracked liveResize = null;+ @tracked freeFollow = null;+ @tracked activeResizeKey = null;++ measureCard = (handle) => handle.closest(".db-report__card");++ canResize = (card) => this.canEdit && !card.isLoading;++ columnFor = (key) => this.cardColumns.get(key);++ followRectFor = (key) =>+ this.freeFollow?.key === key ? this.freeFollow.rect : null;++ handleDirectionsFor = (card) => {+ if (card.cols > 1 || this.activeResizeKey === card.key) {+ return ["sw", "se"];+ }+ const column = this.cardColumns.get(card.key);+ const innerCornerIsLeft = isDocumentRTL() ? column === 0 : column === 1;+ return [innerCornerIsLeft ? "sw" : "se"];+ };constructor() {super(...arguments);@@ -39,9 +160,11 @@ export default class DashboardReports extends Component {}get layoutItems() {- return this.items.map(({ source, identifier }) => ({+ return this.cards.map(({ source, identifier, rows, cols }) => ({source,identifier,+ rows: rows || 1,+ cols: cols || 1,}));}@@ -53,6 +176,27 @@ export default class DashboardReports extends Component {return this.canEdit && this.items.length < VISIBLE_CAP;}+ get effectiveCards() {+ if (!this.liveResize) {+ return this.cards;+ }+ return this.cards.map((card) =>+ card.key === this.liveResize.key+ ? { ...card, rows: this.liveResize.rows, cols: this.liveResize.cols }+ : card+ );+ }++ get cardColumns() {+ return computeColumns(this.effectiveCards);+ }++ get resizeSignature() {+ return this.liveResize+ ? `${this.liveResize.key}:${this.liveResize.rows}:${this.liveResize.cols}`+ : null;+ }+@cachedget filters() {const filters = {};@@ -114,6 +258,156 @@ export default class DashboardReports extends Component {});}+ freeFollowRect(+ originRect,+ delta,+ { rowHeight, rowGap, singleWidth, fullWidth, anchorLeft }+ ) {+ const maxHeight = MAX_ROWS * rowHeight + (MAX_ROWS - 1) * rowGap;+ const height = clampBetween(+ originRect.height + delta.y,+ rowHeight,+ maxHeight+ );+ const width = clampBetween(+ originRect.width + (anchorLeft ? delta.x : -delta.x),+ singleWidth,+ fullWidth+ );+ const rightEdge = originRect.left + originRect.width;+ return {+ left: anchorLeft ? originRect.left : rightEdge - width,+ top: originRect.top,+ width,+ height,+ };+ }++ @action+ onCardResizeStart(item, direction, dragInfo) {+ const rect = dragInfo.measuredRect;+ const grid = dragInfo.measured?.closest(".db-section__wrapper");+ if (!rect || !grid) {+ return;+ }++ this.activeResizeKey = item.key;++ const style = getComputedStyle(grid);+ const columnGap = parseFloat(style.columnGap) || 0;+ const rowGap = parseFloat(style.rowGap) || 0;+ const originalRows = item.rows;+ const originalCols = item.cols;++ dragInfo.session.originalRows = originalRows;+ dragInfo.session.originalCols = originalCols;+ dragInfo.session.originRect = rect;+ dragInfo.session.rowHeight =+ originalRows > 1+ ? (rect.height - (originalRows - 1) * rowGap) / originalRows+ : rect.height;+ dragInfo.session.rowGap = rowGap;+ dragInfo.session.singleWidth =+ originalCols > 1 ? (rect.width - columnGap) / 2 : rect.width;+ dragInfo.session.fullWidth =+ originalCols > 1 ? rect.width : rect.width * 2 + columnGap;+ dragInfo.session.anchorLeft = direction === "se";+ }++ @action+ onCardResize(item, _payload, dragInfo) {+ const {+ originalRows,+ originalCols,+ originRect,+ rowHeight,+ rowGap,+ singleWidth,+ fullWidth,+ anchorLeft,+ } = dragInfo.session;+ if (!originRect) {+ return;+ }++ const rawRows = originalRows + dragInfo.delta.y / (rowHeight + rowGap);+ const liveRows = clampBetween(Math.round(rawRows), 1, MAX_ROWS);++ const colUnit = fullWidth - singleWidth;+ const signedDeltaX = anchorLeft ? dragInfo.delta.x : -dragInfo.delta.x;+ const rawCols = originalCols + signedDeltaX / colUnit;+ const liveCols =+ liveRows > 1 ? MAX_COLS : clampBetween(Math.round(rawCols), 1, MAX_COLS);++ this.liveResize = { key: item.key, rows: liveRows, cols: liveCols };+ this.freeFollow = {+ key: item.key,+ rect: this.freeFollowRect(originRect, dragInfo.delta, {+ rowHeight,+ rowGap,+ singleWidth,+ fullWidth,+ anchorLeft,+ }),+ };+ }++ @action+ async onCardResizeEnd(item, _payload, dragInfo) {+ const live = this.liveResize?.key === item.key ? this.liveResize : null;+ this.freeFollow = null;+ this.activeResizeKey = null;++ if (!dragInfo.moved) {+ this.liveResize = null;+ const isNormal = item.rows === 1 && item.cols === 1;+ await this.setSize(+ item,+ isNormal ? { rows: 1, cols: MAX_COLS } : { rows: 1, cols: 1 }+ );+ return;+ }++ if (+ live &&+ (live.rows !== dragInfo.session.originalRows ||+ live.cols !== dragInfo.session.originalCols)+ ) {+ await this.setSize(item, { rows: live.rows, cols: live.cols });+ }++ this.liveResize = null;+ }++ @action+ onCardResizeCancel() {+ this.liveResize = null;+ this.freeFollow = null;+ this.activeResizeKey = null;+ }++ @action+ async setSize(item, { rows, cols }) {+ const nextItems = this.layoutItems.map((i) =>+ i.source === item.source && i.identifier === item.identifier+ ? { ...i, rows, cols }+ : i+ );++ try {+ await ajax("/admin/dashboard/reports/layout", {+ type: "PUT",+ contentType: "application/json",+ data: JSON.stringify({ items: nextItems }),+ });+ this.cards = this.cards.map((card) =>+ card.key === item.key ? { ...card, rows, cols } : card+ );+ } catch (e) {+ popupAjaxError(e);+ }+ }+@actionasync removeReport(item) {const nextItems = this.layoutItems.filter(@@ -161,8 +455,34 @@ export default class DashboardReports extends Component {class="db-reports"{{didUpdate this.loadPayloads @data @startDate @endDate}}>- {{#each this.cards key="key" as |card|}}- <div class="db-report__card" data-identifier={{card.key}}>+ {{#each this.effectiveCards key="key" as |card|}}+ {{#if (eq card.key this.freeFollow.key)}}+ <div+ {{AnimateReflow this.resizeSignature}}+ class={{dConcatClass+ "db-report__card"+ "--resize-placeholder"+ (if (gt card.cols 1) "--wide")+ (if (gt card.rows 1) (concat "--rows-" card.rows))+ }}+ data-column={{this.columnFor card.key}}+ ></div>+ {{/if}}+ <div+ {{FollowPointer (this.followRectFor card.key)}}+ {{AnimateReflow+ this.resizeSignature+ disabled=(eq card.key this.freeFollow.key)+ }}+ class={{dConcatClass+ "db-report__card"+ (if (gt card.cols 1) "--wide")+ (if (gt card.rows 1) (concat "--rows-" card.rows))+ (if (eq card.key this.freeFollow.key) "--floating")+ }}+ data-identifier={{card.key}}+ data-column={{this.columnFor card.key}}+ ><div class="db-report__header"><a href={{card.url}} class="db-report__name">{{card.title}}</a>{{#if card.label}}@@ -203,11 +523,25 @@ export default class DashboardReports extends Component {{{/if}}</DConditionalLoadingSpinner></div>+ {{#if (this.canResize card)}}+ <DResizeHandles+ @directions={{this.handleDirectionsFor card}}+ @handleClass="db-report__resize-handle"+ @draggingClass="--resizing"+ @threshold={{8}}+ @measure={{this.measureCard}}+ @onResizeStart={{fn this.onCardResizeStart card}}+ @onResize={{fn this.onCardResize card}}+ @onResizeEnd={{fn this.onCardResizeEnd card}}+ @onResizeCancel={{fn this.onCardResizeCancel card}}+ />+ {{/if}}</div>{{/each}}{{#if this.addTileVisible}}<button+ {{AnimateReflow this.resizeSignature}}type="button"class="db-report__add-report"aria-label={{i18n "admin.dashboard.reports_section.add"}}diff --git a/frontend/discourse/tests/integration/components/dashboard/reports-test.gjs b/frontend/discourse/tests/integration/components/dashboard/reports-test.gjsindex a976d425795..af3e6d6b62c 100644--- a/frontend/discourse/tests/integration/components/dashboard/reports-test.gjs+++ b/frontend/discourse/tests/integration/components/dashboard/reports-test.gjs@@ -1,11 +1,26 @@import { tracked } from "@glimmer/tracking";-import { hash } from "@ember/helper";-import { render, settled, waitFor } from "@ember/test-helpers";+import { array, hash } from "@ember/helper";+import { getOwner } from "@ember/owner";+import {+ find,+ render,+ settled,+ triggerEvent,+ waitFor,+} from "@ember/test-helpers";import { module, test } from "qunit";import DashboardReports from "discourse/admin/components/dashboard/reports";import { registerAdminDashboardReportRenderer } from "discourse/admin/lib/admin-dashboard-report-renderers";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";+import {+ logIn,+ updateCurrentUser,+} from "discourse/tests/helpers/qunit-helpers";+import {+ settleGestureFrame,+ stubPointerCapture,+} from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";import { i18n } from "discourse-i18n";const FakeReportRenderer = <template>@@ -49,9 +64,28 @@ function deferredBulkFetch() {return { resolve: (body) => resolve(response(body)) };}+function measureRowUnit(cardSelector) {+ const cardHeight = find(cardSelector).getBoundingClientRect().height;+ const rowGap =+ parseFloat(getComputedStyle(find(".db-section__wrapper")).rowGap) || 0;+ return cardHeight + rowGap;+}++function measureColUnit(cardSelector) {+ const cardWidth = find(cardSelector).getBoundingClientRect().width;+ const columnGap =+ parseFloat(getComputedStyle(find(".db-section__wrapper")).columnGap) || 0;+ return cardWidth + columnGap;+}+module("Integration | Component | DashboardReports", function (hooks) {setupRenderingTest(hooks);+ hooks.beforeEach(function () {+ logIn(getOwner(this));+ updateCurrentUser({ admin: true });+ });+test("displays an error when the section failed to load", async function (assert) {await render(<template>@@ -216,6 +250,708 @@ module("Integration | Component | DashboardReports", function (hooks) {.exists("the chart renders again once the new range's data resolves");});+ test("does not render resize handles for a non-admin viewer", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ pretender.post("/admin/dashboard/reports/bulk", () =>+ response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ ],+ })+ );++ updateCurrentUser({ admin: false });++ const item = { ...ITEMS[0], rows: 1, cols: 1 };++ await render(+ <template>+ <DashboardReports @data={{hash items=(array item)}} />+ </template>+ );++ assert+ .dom('[data-identifier="test_source:signups"] .db-report__resize-handle')+ .doesNotExist("a non-admin viewer cannot resize report cards");+ });++ test("toggles a card's width via a plain click on its resize handle and persists it through the layout endpoint", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ pretender.post("/admin/dashboard/reports/bulk", () =>+ response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ ],+ })+ );++ let putBody;+ pretender.put("/admin/dashboard/reports/layout", (request) => {+ putBody = JSON.parse(request.requestBody);+ return response(204, {});+ });++ const item = { ...ITEMS[0], rows: 1, cols: 1 };++ await render(+ <template>+ <DashboardReports @data={{hash items=(array item)}} />+ </template>+ );++ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass("--wide", "starts at its persisted single-column size");++ const handle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle'+ ).element;+ await triggerEvent(handle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(handle, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.deepEqual(+ putBody.items,+ [{ source: "test_source", identifier: "signups", rows: 1, cols: 2 }],+ "clicking the resize handle without dragging toggles it to the smallest expanded size, wide but still a single row"+ );+ });++ test("applies a resize locally without re-fetching the dashboard or any report's chart data", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ let bulkFetchCount = 0;+ pretender.post("/admin/dashboard/reports/bulk", () => {+ bulkFetchCount++;+ return response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ ],+ });+ });+ pretender.put("/admin/dashboard/reports/layout", () => response(204, {}));++ let refreshSectionsCalls = 0;+ const refreshSections = () => {+ refreshSectionsCalls++;+ };++ const item = { ...ITEMS[0], rows: 1, cols: 1 };++ await render(+ <template>+ <DashboardReports+ @data={{hash items=(array item)}}+ @refreshSections={{refreshSections}}+ />+ </template>+ );++ assert.strictEqual(+ bulkFetchCount,+ 1,+ "control: the initial render fetches chart data once"+ );++ const handle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle'+ ).element;+ await triggerEvent(handle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(handle, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass(+ "--wide",+ "the card reflects its new persisted size immediately, from local state"+ );+ assert.strictEqual(+ refreshSectionsCalls,+ 0,+ "resizing does not trigger a full dashboard refresh"+ );+ assert.strictEqual(+ bulkFetchCount,+ 1,+ "resizing does not re-fetch any report's chart data"+ );+ });++ test("persists an earlier resize when a different card is resized afterward", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ pretender.post("/admin/dashboard/reports/bulk", () =>+ response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ {+ source: "core_report",+ identifier: "empty_report",+ key: "core_report:empty_report",+ data: { type: "empty_report", data: [], empty: true },+ },+ ],+ })+ );++ const putBodies = [];+ pretender.put("/admin/dashboard/reports/layout", (request) => {+ putBodies.push(JSON.parse(request.requestBody));+ return response(204, {});+ });++ const items = [+ { ...ITEMS[0], rows: 1, cols: 1 },+ { ...ITEMS[2], rows: 1, cols: 1 },+ ];++ await render(+ <template><DashboardReports @data={{hash items=items}} /></template>+ );++ const firstHandle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle'+ ).element;+ await triggerEvent(firstHandle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(firstHandle, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ const secondHandle = stubPointerCapture(+ '[data-identifier="core_report:empty_report"] .db-report__resize-handle'+ ).element;+ await triggerEvent(secondHandle, "pointerdown", {+ button: 0,+ pointerId: 2,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(secondHandle, "pointerup", {+ pointerId: 2,+ clientX: 0,+ clientY: 0,+ });++ assert.deepEqual(+ putBodies[1].items,+ [+ { source: "test_source", identifier: "signups", rows: 1, cols: 2 },+ {+ source: "core_report",+ identifier: "empty_report",+ rows: 1,+ cols: 2,+ },+ ],+ "the second card's resize request still carries the first card's new size"+ );+ });++ test("grows the card live row by row as a drag crosses each row boundary, reflowing its sibling, then persists on release", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ pretender.post("/admin/dashboard/reports/bulk", () =>+ response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ {+ source: "core_report",+ identifier: "empty_report",+ key: "core_report:empty_report",+ data: { type: "empty_report", data: [], empty: true },+ },+ ],+ })+ );++ let putBody;+ pretender.put("/admin/dashboard/reports/layout", (request) => {+ putBody = JSON.parse(request.requestBody);+ return response(204, {});+ });++ const items = [+ { ...ITEMS[0], rows: 1, cols: 1 },+ { ...ITEMS[2], rows: 1, cols: 1 },+ ];++ await render(+ <template><DashboardReports @data={{hash items=items}} /></template>+ );++ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass("--rows-2", "starts at its persisted single-row size");+ assert+ .dom('[data-identifier="core_report:empty_report"]')+ .hasAttribute(+ "data-column",+ "1",+ "control: the second card starts in the right column"+ );++ const handle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle'+ ).element;+ await triggerEvent(handle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ const unit = measureRowUnit('[data-identifier="test_source:signups"]');+ await triggerEvent(handle, "pointermove", {+ pointerId: 1,+ clientX: 0,+ clientY: Math.ceil(unit * 0.6),+ });+ await settleGestureFrame();+ await settleGestureFrame();++ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass(+ "--rows-2",+ "the dragged card grows live, before release, like a textarea"+ );+ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass(+ "--wide",+ "growing past one row forces it to span the full width too"+ );+ assert+ .dom('[data-identifier="core_report:empty_report"]')+ .hasAttribute(+ "data-column",+ "0",+ "its sibling is pushed to a fresh row by the real grid reflow, not left in place under an overlay"+ );++ await triggerEvent(handle, "pointermove", {+ pointerId: 1,+ clientX: 0,+ clientY: Math.ceil(unit * 0.3),+ });++ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass(+ "--rows-2",+ "dragging back under the boundary shrinks it live again"+ );+ assert+ .dom('[data-identifier="core_report:empty_report"]')+ .hasAttribute(+ "data-column",+ "1",+ "and its sibling's column reflows back too"+ );++ await triggerEvent(handle, "pointermove", {+ pointerId: 1,+ clientX: 0,+ clientY: Math.ceil(unit * 1.6),+ });++ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass("--rows-3", "crossing the next boundary grows it another row");++ await triggerEvent(handle, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: Math.ceil(unit * 1.6),+ });++ assert.deepEqual(+ putBody.items,+ [+ { source: "test_source", identifier: "signups", rows: 3, cols: 2 },+ {+ source: "core_report",+ identifier: "empty_report",+ rows: 1,+ cols: 1,+ },+ ],+ "releasing persists the row count it landed on, forcing the full width along with it"+ );+ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass(+ "--floating",+ "it settles back into the grid instead of staying fixed-positioned"+ );+ assert+ .dom(".db-report__card.--resize-placeholder")+ .doesNotExist("the placeholder is gone once the drag ends");+ });++ test("commits a card to spanning both columns while staying a single row when dragged mostly horizontally", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ pretender.post("/admin/dashboard/reports/bulk", () =>+ response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ {+ source: "core_report",+ identifier: "empty_report",+ key: "core_report:empty_report",+ data: { type: "empty_report", data: [], empty: true },+ },+ ],+ })+ );++ let putBody;+ pretender.put("/admin/dashboard/reports/layout", (request) => {+ putBody = JSON.parse(request.requestBody);+ return response(204, {});+ });++ const items = [+ { ...ITEMS[0], rows: 1, cols: 1 },+ { ...ITEMS[2], rows: 1, cols: 1 },+ ];++ await render(+ <template><DashboardReports @data={{hash items=items}} /></template>+ );++ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass("--wide", "starts at its persisted single-column size");++ const handle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle'+ ).element;+ await triggerEvent(handle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ const unit = measureColUnit('[data-identifier="test_source:signups"]');+ await triggerEvent(handle, "pointermove", {+ pointerId: 1,+ clientX: Math.ceil(unit * 0.6),+ clientY: 1,+ });+ await settleGestureFrame();+ await settleGestureFrame();++ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass(+ "--wide",+ "a mostly-horizontal drag commits the card to spanning both columns"+ );+ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass(+ "--rows-2",+ "it stays a single row since the drag barely moved vertically"+ );+ assert+ .dom('[data-identifier="core_report:empty_report"]')+ .hasAttribute(+ "data-column",+ "0",+ "its sibling is pushed to a fresh row now that the wide card fills the whole row"+ );++ await triggerEvent(handle, "pointermove", {+ pointerId: 1,+ clientX: Math.ceil(unit * 0.3),+ clientY: 1,+ });++ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass(+ "--wide",+ "dragging back under the boundary shrinks it to a single column again"+ );++ await triggerEvent(handle, "pointermove", {+ pointerId: 1,+ clientX: Math.ceil(unit * 0.6),+ clientY: 1,+ });+ await triggerEvent(handle, "pointerup", {+ pointerId: 1,+ clientX: Math.ceil(unit * 0.6),+ clientY: 1,+ });++ assert.deepEqual(+ putBody.items,+ [+ { source: "test_source", identifier: "signups", rows: 1, cols: 2 },+ {+ source: "core_report",+ identifier: "empty_report",+ rows: 1,+ cols: 1,+ },+ ],+ "releasing persists the wide-but-single-row size"+ );+ });++ test("renders both bottom corners on a wide card, and each shrinks it while keeping the opposite edge fixed", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ pretender.post("/admin/dashboard/reports/bulk", () =>+ response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ ],+ })+ );++ let putBody;+ pretender.put("/admin/dashboard/reports/layout", (request) => {+ putBody = JSON.parse(request.requestBody);+ return response(204, {});+ });++ const item = { ...ITEMS[0], rows: 1, cols: 2 };++ await render(+ <template>+ <DashboardReports @data={{hash items=(array item)}} />+ </template>+ );++ assert+ .dom(+ '[data-identifier="test_source:signups"] .db-report__resize-handle.--se'+ )+ .exists("a wide card renders a bottom-right handle");+ assert+ .dom(+ '[data-identifier="test_source:signups"] .db-report__resize-handle.--sw'+ )+ .exists("and also a bottom-left handle");++ const card = find('[data-identifier="test_source:signups"]');+ const originalRect = card.getBoundingClientRect();+ const columnGap =+ parseFloat(getComputedStyle(find(".db-section__wrapper")).columnGap) || 0;+ const singleWidth = (originalRect.width - columnGap) / 2;+ const colUnit = originalRect.width - singleWidth;++ const seHandle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle.--se'+ ).element;+ await triggerEvent(seHandle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(seHandle, "pointermove", {+ pointerId: 1,+ clientX: -Math.ceil(colUnit * 0.6),+ clientY: 1,+ });+ await settleGestureFrame();+ await settleGestureFrame();++ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass(+ "--wide",+ "dragging the bottom-right handle toward the card's center shrinks it"+ );++ await triggerEvent(seHandle, "pointerup", {+ pointerId: 1,+ clientX: -Math.ceil(colUnit * 0.6),+ clientY: 1,+ });++ assert.deepEqual(+ putBody.items,+ [{ source: "test_source", identifier: "signups", rows: 1, cols: 1 }],+ "releasing persists the shrunk single-column size"+ );++ await triggerEvent(seHandle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(seHandle, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass("--wide", "control: back to wide for the next drag");++ const swHandle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle.--sw'+ ).element;+ await triggerEvent(swHandle, "pointerdown", {+ button: 0,+ pointerId: 2,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(swHandle, "pointermove", {+ pointerId: 2,+ clientX: Math.ceil(colUnit * 0.6),+ clientY: 1,+ });+ await settleGestureFrame();+ await settleGestureFrame();++ assert+ .dom('[data-identifier="test_source:signups"]')+ .doesNotHaveClass(+ "--wide",+ "dragging the bottom-left handle toward the card's center shrinks it too"+ );++ await triggerEvent(swHandle, "pointerup", {+ pointerId: 2,+ clientX: Math.ceil(colUnit * 0.6),+ clientY: 1,+ });++ assert.deepEqual(+ putBody.items,+ [{ source: "test_source", identifier: "signups", rows: 1, cols: 1 }],+ "releasing again persists the shrunk single-column size"+ );+ });++ test("clamps the live row count at the maximum during an extreme drag", async function (assert) {+ registerAdminDashboardReportRenderer("test_source", FakeReportRenderer);++ pretender.post("/admin/dashboard/reports/bulk", () =>+ response({+ items: [+ {+ source: "test_source",+ identifier: "signups",+ key: "test_source:signups",+ data: { type: "signups", empty: false },+ },+ ],+ })+ );+ pretender.put("/admin/dashboard/reports/layout", () => response(204, {}));++ const item = { ...ITEMS[0], rows: 1, cols: 1 };++ await render(+ <template>+ <DashboardReports @data={{hash items=(array item)}} />+ </template>+ );++ const handle = stubPointerCapture(+ '[data-identifier="test_source:signups"] .db-report__resize-handle'+ ).element;+ await triggerEvent(handle, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(handle, "pointermove", {+ pointerId: 1,+ clientX: 0,+ clientY: 5000,+ });++ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass(+ "--rows-4",+ "an extreme drag stops growing at the maximum row count"+ );+ assert+ .dom('[data-identifier="test_source:signups"]')+ .hasClass("--wide", "and stays forced to the full width along with it");++ await triggerEvent(handle, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 5000,+ });+ });+test("clears every card's loading state when the whole bulk request fails", async function (assert) {pretender.post("/admin/dashboard/reports/bulk", () => response(500, {}));diff --git a/lib/admin_dashboard/reports/layout_updater.rb b/lib/admin_dashboard/reports/layout_updater.rbindex 198b84bf34e..f78242e0d89 100644--- a/lib/admin_dashboard/reports/layout_updater.rb+++ b/lib/admin_dashboard/reports/layout_updater.rb@@ -18,17 +18,19 @@ module AdminDashboardAdminDashboardReport.transaction doAdminDashboardReport.delete_allnow = Time.current- rows =+ records =items.each_with_index.map do |item, index|{source: item[:source],identifier: item[:identifier],position: index,+ rows: item[:rows] || 1,+ cols: item[:cols] || 1,created_at: now,updated_at: now,}end- AdminDashboardReport.insert_all(rows) if rows.any?+ AdminDashboardReport.insert_all(records) if records.any?endendenddiff --git a/lib/admin_dashboard/reports/section.rb b/lib/admin_dashboard/reports/section.rbindex e13e3553421..888453425f8 100644--- a/lib/admin_dashboard/reports/section.rb+++ b/lib/admin_dashboard/reports/section.rb@@ -13,7 +13,7 @@ module AdminDashboardenddef build- items = visible_items.map { |_row, resolved| serialize(resolved) }+ items = visible_items.map { |record, resolved| serialize(resolved, record) }items = filter_by_search(items) if @search{ items: items }@@ -24,31 +24,31 @@ module AdminDashboardattr_reader :guardiandef visible_items- rows = AdminDashboardReport.order(created_at: :desc).to_a- resolved_by_row_id = resolve_rows(rows)+ records = AdminDashboardReport.order(created_at: :desc).to_a+ resolved_by_record_id = resolve_records(records)- # When more rows resolve than VISIBLE_CAP allows, the older overflow+ # When more records resolve than VISIBLE_CAP allows, the older overflow# is hidden — clip by created_at recency first, then re-sort the# survivors by the admin's chosen position.- rows- .filter_map { |row| (obj = resolved_by_row_id[row.id]) && [row, obj] }+ records+ .filter_map { |record| (obj = resolved_by_record_id[record.id]) && [record, obj] }.first(AdminDashboardReport::VISIBLE_CAP)- .sort_by { |row, _obj| row.position }+ .sort_by { |record, _obj| record.position }end- def resolve_rows(rows)+ def resolve_records(records)per_source =- AdminDashboard::Reports::Registry.dispatch_per_source(rows) do |provider, group|+ AdminDashboard::Reports::Registry.dispatch_per_source(records) do |provider, group|provider.resolve_many(group.map(&:identifier), guardian: guardian)end- rows.each_with_object({}) do |row, resolved|- resolved[row.id] = per_source.dig(row.source, row.identifier)+ records.each_with_object({}) do |record, resolved|+ resolved[record.id] = per_source.dig(record.source, record.identifier)endend- def serialize(resolved)- resolved.to_h+ def serialize(resolved, record)+ resolved.to_h.merge(rows: record.rows, cols: record.cols)enddef filter_by_search(items)diff --git a/spec/lib/admin_dashboard/reports/section_spec.rb b/spec/lib/admin_dashboard/reports/section_spec.rbindex d2c6fa80570..b6143817fab 100644--- a/spec/lib/admin_dashboard/reports/section_spec.rb+++ b/spec/lib/admin_dashboard/reports/section_spec.rb@@ -54,8 +54,8 @@ RSpec.describe AdminDashboard::Reports::Section doexpect(result[:items].map { |item| item[:identifier] }).to eq(%w[b a c])end- it "serializes the resolved metadata along with a composite key" do- AdminDashboardReport.create!(source: "fake", identifier: "x", position: 0)+ it "serializes the resolved metadata along with a composite key and the row's rows/cols" do+ AdminDashboardReport.create!(source: "fake", identifier: "x", position: 0, rows: 3, cols: 2)item = described_class.build(guardian: guardian)[:items].firstexpect(item).to eq(@@ -66,6 +66,8 @@ RSpec.describe AdminDashboard::Reports::Section dolabel: "Fake",url: "/fake/x",key: "fake:x",+ rows: 3,+ cols: 2,)enddiff --git a/spec/models/admin_dashboard_report_spec.rb b/spec/models/admin_dashboard_report_spec.rbindex fa8c8318211..9a2fb016f83 100644--- a/spec/models/admin_dashboard_report_spec.rb+++ b/spec/models/admin_dashboard_report_spec.rb@@ -45,6 +45,55 @@ RSpec.describe AdminDashboardReport doexpect(record).not_to be_validexpect(record.errors.attribute_names).to include(:source)end++ it "defaults rows to 1 and rejects out-of-range row counts" do+ record = described_class.create!(source: "core_report", identifier: "signups")+ expect(record.rows).to eq(1)++ record.rows = 0+ expect(record).not_to be_valid+ expect(record.errors.attribute_names).to include(:rows)++ record.rows = described_class::MAX_ROWS + 1+ expect(record).not_to be_valid+ expect(record.errors.attribute_names).to include(:rows)++ record.rows = described_class::MAX_ROWS+ record.cols = described_class::MAX_COLS+ expect(record).to be_valid+ end++ it "defaults cols to 1 and rejects out-of-range column counts" do+ record = described_class.create!(source: "core_report", identifier: "signups")+ expect(record.cols).to eq(1)++ record.cols = 0+ expect(record).not_to be_valid+ expect(record.errors.attribute_names).to include(:cols)++ record.cols = described_class::MAX_COLS + 1+ expect(record).not_to be_valid+ expect(record.errors.attribute_names).to include(:cols)+ end++ it "allows a single-row card to span either column width" do+ record = described_class.create!(source: "core_report", identifier: "signups")++ record.cols = described_class::MAX_COLS+ expect(record).to be_valid+ end++ it "requires a card spanning more than one row to also span the full width" do+ record = described_class.create!(source: "core_report", identifier: "signups")++ record.rows = 2+ record.cols = 1+ expect(record).not_to be_valid+ expect(record.errors.attribute_names).to include(:cols)++ record.cols = described_class::MAX_COLS+ expect(record).to be_valid+ endenddescribe "default position" dodiff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rbindex 814fa263c28..f998eae16af 100644--- a/spec/requests/admin/dashboard_controller_spec.rb+++ b/spec/requests/admin/dashboard_controller_spec.rb@@ -2375,6 +2375,81 @@ RSpec.describe Admin::DashboardController doexpect(rows).to eq([["new_a", 0], ["new_b", 1]])end+ it "persists the row count and column span supplied per item, defaulting to 1 when omitted" do+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)++ put "/admin/dashboard/reports/layout.json",+ params: {+ items: [+ { source: "fake_source", identifier: "a", rows: 3, cols: 2 },+ { source: "fake_source", identifier: "b" },+ ],+ }++ expect(response.status).to eq(204)+ rows = AdminDashboardReport.order(:position).pluck(:identifier, :rows, :cols)+ expect(rows).to eq([["a", 3, 2], ["b", 1, 1]])+ end++ it "persists a single-row card that spans the full width" do+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)++ put "/admin/dashboard/reports/layout.json",+ params: {+ items: [{ source: "fake_source", identifier: "a", rows: 1, cols: 2 }],+ }++ expect(response.status).to eq(204)+ record = AdminDashboardReport.find_by(identifier: "a")+ expect(record.rows).to eq(1)+ expect(record.cols).to eq(2)+ end++ it "rejects an item with an out-of-range row count" do+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)++ put "/admin/dashboard/reports/layout.json",+ params: {+ items: [+ {+ source: "fake_source",+ identifier: "a",+ rows: AdminDashboardReport::MAX_ROWS + 1,+ },+ ],+ }++ expect(response.status).to eq(400)+ end++ it "rejects an item with an out-of-range column count" do+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)++ put "/admin/dashboard/reports/layout.json",+ params: {+ items: [+ {+ source: "fake_source",+ identifier: "a",+ cols: AdminDashboardReport::MAX_COLS + 1,+ },+ ],+ }++ expect(response.status).to eq(400)+ end++ it "rejects a multi-row item that does not span the full width" do+ DiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)++ put "/admin/dashboard/reports/layout.json",+ params: {+ items: [{ source: "fake_source", identifier: "a", rows: 2, cols: 1 }],+ }++ expect(response.status).to eq(400)+ end+it "accepts an empty layout (removes everything)" doDiscoursePluginRegistry.register_admin_dashboard_report_source(fake_provider, plugin)AdminDashboardReport.create!(source: "fake_source", identifier: "y", position: 0)