Skip to content

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

FIX: Load uncached categories so Boards preserves names and selections (#43731)

Régis Hanolb82bfacb8fb8
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs
index b7aa4e55ab2..a163f1a4259 100644
--- a/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs
@@ -23,6 +23,7 @@ import DiscourseURL from "discourse/lib/url";
import { prefersReducedMotion } from "discourse/lib/utilities";
import Category from "discourse/models/category";
import { or } from "discourse/truth-helpers";
+import DAsyncContent from "discourse/ui-kit/d-async-content";
import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
import dBoundCategoryLink from "discourse/ui-kit/helpers/d-bound-category-link";
@@ -37,6 +38,7 @@ import {
isRecencyColumn,
sortCardsForColumn,
} from "../lib/boards-card-ordering";
+import { loadCategories } from "../lib/boards-categories";
import { boardsBoardConfigureUrl, boardsBoardUrl } from "../lib/boards-urls";
import Board from "../models/board";
import Card from "../models/card";
@@ -205,18 +207,12 @@ export default class BoardsBoardViewer extends Component {
this.#stopHorizontalAutoScroll();
}
- get boardCategories() {
- return (this.board.category_ids || [])
- .map((id) => Category.findById(id))
- .filter(Boolean);
- }
-
get boardTagNames() {
return this.board.tag_names || [];
}
get hasBoardFilters() {
- return this.boardCategories.length > 0 || this.boardTagNames.length > 0;
+ return this.board.category_ids?.length > 0 || this.boardTagNames.length > 0;
}
get allSameCategory() {
@@ -571,7 +567,7 @@ export default class BoardsBoardViewer extends Component {
}
@action
- onPromoteToTopic(cardId) {
+ async onPromoteToTopic(cardId) {
let card;
let column;
for (const col of this.columns) {
@@ -611,7 +607,13 @@ export default class BoardsBoardViewer extends Component {
const categoryId =
column.move_to_category_id || this.board.category_ids?.[0];
if (categoryId) {
- opts.category = Category.findById(categoryId);
+ try {
+ opts.category = await Category.asyncFindById(categoryId);
+ } catch (error) {
+ this._cleanupPromotion();
+ popupAjaxError(error);
+ return;
+ }
}
this.composer.openNewTopic(opts);
}
@@ -957,6 +959,7 @@ export default class BoardsBoardViewer extends Component {
async #handleBoardUpdated() {
try {
const result = await ajax(`/boards/api/boards/${this.board.id}.json`);
+ await Board.preloadCategories(result);
if (result.columns) {
this.columns = result.columns.map((col) =>
Column.create({
@@ -1426,9 +1429,16 @@ export default class BoardsBoardViewer extends Component {
<div class="discourse-boards-board-viewer__metadata">
{{#if this.hasBoardFilters}}
<div class="discourse-boards-board-viewer__constraint">
- {{#each this.boardCategories as |category|}}
- {{dBoundCategoryLink category link=true}}
- {{/each}}
+ <DAsyncContent
+ @asyncData={{loadCategories}}
+ @context={{this.board.category_ids}}
+ >
+ <:content as |categories|>
+ {{#each categories as |category|}}
+ {{dBoundCategoryLink category link=true}}
+ {{/each}}
+ </:content>
+ </DAsyncContent>
{{#if this.boardTagNames.length}}
<div class="list-tags">
{{dDiscourseTags null tags=this.boardTagNames}}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-card.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-card.gjs
index cf66419cd4f..28883b2135d 100644
--- a/plugins/boards/assets/javascripts/discourse/components/boards-card.gjs
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-card.gjs
@@ -14,7 +14,7 @@ import renderTags from "discourse/lib/render-tags";
import { emojiUnescape } from "discourse/lib/text";
import DiscourseURL from "discourse/lib/url";
import { escapeExpression } from "discourse/lib/utilities";
-import Category from "discourse/models/category";
+import DAsyncContent from "discourse/ui-kit/d-async-content";
import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
import dCategoryBadge from "discourse/ui-kit/helpers/d-category-badge";
@@ -23,6 +23,7 @@ import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { renderAvatar } from "discourse/ui-kit/helpers/d-user-avatar";
import { i18n } from "discourse-i18n";
+import { loadCategory } from "../lib/boards-categories";
import { boardsBoardUrl, boardsCardUrl } from "../lib/boards-urls";
import AutoLinkedText from "./auto-linked-text";
import BoardsCardDetailModal from "./modal/boards-card-detail";
@@ -113,11 +114,8 @@ export default class BoardsCard extends Component {
return tags.length ? renderTags(null, { tags }) : null;
}
- get category() {
- if (this.args.allSameCategory || !this.topic?.category_id) {
- return null;
- }
- return Category.findById(this.topic.category_id);
+ get categoryId() {
+ return this.args.allSameCategory ? null : this.topic?.category_id;
}
get isDetailed() {
@@ -613,12 +611,21 @@ export default class BoardsCard extends Component {
{{/if}}
<div class="discourse-boards-card__row discourse-boards-card__meta-data">
- {{#if this.category}}
- <div
- class="discourse-boards-card__category discourse-boards-card__row-item"
+ {{#if this.categoryId}}
+ <DAsyncContent
+ @asyncData={{loadCategory}}
+ @context={{this.categoryId}}
>
- {{dCategoryBadge this.category}}
- </div>
+ <:content as |category|>
+ {{#if category}}
+ <div
+ class="discourse-boards-card__category discourse-boards-card__row-item"
+ >
+ {{dCategoryBadge category}}
+ </div>
+ {{/if}}
+ </:content>
+ </DAsyncContent>
{{/if}}
{{#if this.isDetailed}}
<div class="discourse-boards-card__row-item">
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs
index cd763c91c58..fc0a6f3d5af 100644
--- a/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs
@@ -4,8 +4,8 @@ import { action } from "@ember/object";
import { LinkTo } from "@ember/routing";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
-import Category from "discourse/models/category";
import { eq, or } from "discourse/truth-helpers";
+import DAsyncContent from "discourse/ui-kit/d-async-content";
import DButton from "discourse/ui-kit/d-button";
import DFilterControls from "discourse/ui-kit/d-filter-controls";
import DPageHeader from "discourse/ui-kit/d-page-header";
@@ -15,14 +15,9 @@ import dBoundCategoryLink from "discourse/ui-kit/helpers/d-bound-category-link";
import dDiscourseTags from "discourse/ui-kit/helpers/d-discourse-tags";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+import { loadCategories } from "../lib/boards-categories";
import BoardsBoardSettings from "./modal/boards-board-settings";
-function boardCategories(board) {
- return (board.category_ids || [])
- .map((id) => Category.findById(id))
- .filter(Boolean);
-}
-
export default class BoardsPage extends Component {
@service modal;
@service router;
@@ -131,9 +126,16 @@ export default class BoardsPage extends Component {
{{#if (or board.category_ids.length board.tag_names.length)}}
<div class="discourse-boards-board-card__constraints">
- {{#each (boardCategories board) as |category|}}
- {{dBoundCategoryLink category link=false}}
- {{/each}}
+ <DAsyncContent
+ @asyncData={{loadCategories}}
+ @context={{board.category_ids}}
+ >
+ <:content as |categories|>
+ {{#each categories as |category|}}
+ {{dBoundCategoryLink category link=false}}
+ {{/each}}
+ </:content>
+ </DAsyncContent>
{{#if board.tag_names.length}}
<div class="list-tags">
{{dDiscourseTags null tags=board.tag_names}}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs
index 9903e7c2da1..5c1f3f9eddb 100644
--- a/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs
@@ -12,10 +12,12 @@ import discourseDebounce from "discourse/lib/debounce";
import { slugify } from "discourse/lib/utilities";
import CategorySelector from "discourse/select-kit/components/category-selector";
import { eq, or } from "discourse/truth-helpers";
+import DAsyncContent from "discourse/ui-kit/d-async-content";
import DButton from "discourse/ui-kit/d-button";
import DModal from "discourse/ui-kit/d-modal";
import { i18n } from "discourse-i18n";
import { buildDefaultBoardAcl } from "../../lib/boards-access-control";
+import { loadCategories } from "../../lib/boards-categories";
import BoardsAccessControlField from "../boards-access-control-field";
import BoardsEditableTitle from "../boards-editable-title";
@@ -124,13 +126,6 @@ export default class BoardsBoardSettings extends Component {
this.showAdvanced = !this.showAdvanced;
}
- @action
- selectedCategories(categoryIds) {
- return (categoryIds || [])
- .map((id) => this.site.categories?.find((c) => c.id === id))
- .filter(Boolean);
- }
-
@action
onConstraintTypeChange(type, { set }) {
set("constraint_type", type);
@@ -329,10 +324,17 @@ export default class BoardsBoardSettings extends Component {
as |field|
>
<field.Control>
- <CategorySelector
- @categories={{this.selectedCategories data.category_ids}}
- @onChange={{fn this.onCategoriesChange field}}
- />
+ <DAsyncContent
+ @asyncData={{loadCategories}}
+ @context={{data.category_ids}}
+ >
+ <:content as |categories|>
+ <CategorySelector
+ @categories={{categories}}
+ @onChange={{fn this.onCategoriesChange field}}
+ />
+ </:content>
+ </DAsyncContent>
</field.Control>
</form.Field>
{{/if}}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs
index 24c45371234..bdd5bf8d795 100644
--- a/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs
@@ -2,11 +2,12 @@ import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { fn } from "@ember/helper";
import { action } from "@ember/object";
-import Category from "discourse/models/category";
import { eq, not } from "discourse/truth-helpers";
+import DAsyncContent from "discourse/ui-kit/d-async-content";
import DButton from "discourse/ui-kit/d-button";
import DModal from "discourse/ui-kit/d-modal";
import { i18n } from "discourse-i18n";
+import { loadCategories } from "../../lib/boards-categories";
function includes(arr, item) {
return arr.includes(item);
@@ -29,17 +30,6 @@ export default class BoardsConstraintFix extends Component {
}
}
- get categoryOptions() {
- const { mismatches } = this.args.model;
- if (!mismatches.needsCategory) {
- return [];
- }
- return mismatches.boardCategoryIds.map((id) => {
- const cat = Category.findById(id);
- return { id, name: cat?.name || `Category ${id}` };
- });
- }
-
get tagOptions() {
const { mismatches } = this.args.model;
if (!mismatches.needsTags) {
@@ -112,18 +102,25 @@ export default class BoardsConstraintFix extends Component {
<div class="discourse-boards-constraint-fix__field">
<label>{{i18n "boards.board.constraint_fix_category"}}</label>
<div class="discourse-boards-constraint-fix__options">
- {{#each this.categoryOptions as |cat|}}
- <DButton
- class={{if
- (eq this.selectedCategoryId cat.id)
- "btn-primary discourse-boards-constraint-fix__option--selected"
- "btn-default"
- }}
- data-category-id={{cat.id}}
- @action={{fn this.selectCategory cat.id}}
- @translatedLabel={{cat.name}}
- />
- {{/each}}
+ <DAsyncContent
+ @asyncData={{loadCategories}}
+ @context={{@model.mismatches.boardCategoryIds}}
+ >
+ <:content as |categories|>
+ {{#each categories as |cat|}}
+ <DButton
+ class={{if
+ (eq this.selectedCategoryId cat.id)
+ "btn-primary discourse-boards-constraint-fix__option--selected"
+ "btn-default"
+ }}
+ data-category-id={{cat.id}}
+ @action={{fn this.selectCategory cat.id}}
+ @translatedLabel={{cat.name}}
+ />
+ {{/each}}
+ </:content>
+ </DAsyncContent>
</div>
</div>
{{/if}}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-topic-card-detail.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-topic-card-detail.gjs
index 3f06d3464b6..eab6aa1786d 100644
--- a/plugins/boards/assets/javascripts/discourse/components/modal/boards-topic-card-detail.gjs
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-topic-card-detail.gjs
@@ -8,9 +8,9 @@ import { ajax } from "discourse/lib/ajax";
import renderTags from "discourse/lib/render-tags";
import { emojiUnescape } from "discourse/lib/text";
import { escapeExpression } from "discourse/lib/utilities";
-import Category from "discourse/models/category";
import Topic from "discourse/models/topic";
import { or } from "discourse/truth-helpers";
+import DAsyncContent from "discourse/ui-kit/d-async-content";
import DButton from "discourse/ui-kit/d-button";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
import DDecoratedHtml from "discourse/ui-kit/d-decorated-html";
@@ -19,6 +19,7 @@ import dCategoryBadge from "discourse/ui-kit/helpers/d-category-badge";
import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+import { loadCategory } from "../../lib/boards-categories";
import { columnColorVariable } from "../../lib/boards-column-helpers";
export default class BoardsTopicCardDetail extends Component {
@@ -47,13 +48,6 @@ export default class BoardsTopicCardDetail extends Component {
);
}
- get category() {
- if (!this.topic?.category_id) {
- return null;
- }
- return Category.findById(this.topic.category_id);
- }
-
get allAssignedUsers() {
if (this.topic?.all_assigned_users?.length) {
return this.topic.all_assigned_users;
@@ -131,15 +125,22 @@ export default class BoardsTopicCardDetail extends Component {
{{#if
(or
- this.category
+ this.topic.category_id
this.tagsHtml
this.allAssignedUsers.length
this.columnData
)
}}
<div class="discourse-boards-topic-card-detail__meta">
- {{#if this.category}}
- {{dCategoryBadge this.category link=true}}
+ {{#if this.topic.category_id}}
+ <DAsyncContent
+ @asyncData={{loadCategory}}
+ @context={{this.topic.category_id}}
+ >
+ <:content as |category|>
+ {{dCategoryBadge category link=true}}
+ </:content>
+ </DAsyncContent>
{{/if}}
{{#if this.tagsHtml}}
<span class="discourse-boards-topic-card-detail__tags">
diff --git a/plugins/boards/assets/javascripts/discourse/lib/boards-categories.js b/plugins/boards/assets/javascripts/discourse/lib/boards-categories.js
new file mode 100644
index 00000000000..9cc71d0199f
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/boards-categories.js
@@ -0,0 +1,26 @@
+import Category from "discourse/models/category";
+import Site from "discourse/models/site";
+
+export function loadCategory(id) {
+ return Category.findById(id) || Category.asyncFindById(id);
+}
+
+export function loadCategories(ids = []) {
+ ids = [...new Set(ids.filter(Boolean))];
+ const categories = Category.findByIds(ids);
+
+ if (
+ !Site.current().lazy_load_categories ||
+ categories.length === ids.length
+ ) {
+ return categories;
+ }
+
+ return Category.asyncFindByIds(ids);
+}
+
+export async function preloadCategories(ids) {
+ try {
+ await loadCategories(ids);
+ } catch {}
+}
diff --git a/plugins/boards/assets/javascripts/discourse/models/board.js b/plugins/boards/assets/javascripts/discourse/models/board.js
index 2260f9027cd..82793d6e4d2 100644
--- a/plugins/boards/assets/javascripts/discourse/models/board.js
+++ b/plugins/boards/assets/javascripts/discourse/models/board.js
@@ -1,8 +1,11 @@
import { tracked } from "@glimmer/tracking";
+import { preloadCategories } from "../lib/boards-categories";
import Column from "./column";
export default class Board {
- static createPayload(data) {
+ static async createPayload(data) {
+ await Board.preloadCategories(data);
+
return {
...data,
board: Board.create(data.board),
@@ -17,6 +20,16 @@ export default class Board {
return new Board(args);
}
+ static preloadCategories({ board, columns = [] }) {
+ return preloadCategories([
+ ...(board.category_ids || []),
+ ...columns.flatMap((column) => [
+ column.move_to_category_id,
+ ...(column.cards || []).map((card) => card.topic?.category_id),
+ ]),
+ ]);
+ }
+
@tracked anonymous_can_read;
@tracked archived;
@tracked can_archive;
diff --git a/plugins/boards/assets/javascripts/discourse/routes/boards.js b/plugins/boards/assets/javascripts/discourse/routes/boards.js
index 5578bc743a1..9e710292a47 100644
--- a/plugins/boards/assets/javascripts/discourse/routes/boards.js
+++ b/plugins/boards/assets/javascripts/discourse/routes/boards.js
@@ -1,6 +1,7 @@
import { ajax } from "discourse/lib/ajax";
import DiscourseRoute from "discourse/routes/discourse";
import { i18n } from "discourse-i18n";
+import { preloadCategories } from "../lib/boards-categories";
import Board from "../models/board";
export default class BoardsRoute extends DiscourseRoute {
@@ -10,6 +11,10 @@ export default class BoardsRoute extends DiscourseRoute {
async model() {
const data = await ajax("/boards/api/boards.json");
+ await preloadCategories(
+ data.boards.flatMap((board) => board.category_ids || [])
+ );
+
return data.boards.map((board) => Board.create(board));
}
}
diff --git a/plugins/boards/test/javascripts/acceptance/boards-category-loading-test.js b/plugins/boards/test/javascripts/acceptance/boards-category-loading-test.js
new file mode 100644
index 00000000000..66e0b651d4a
--- /dev/null
+++ b/plugins/boards/test/javascripts/acceptance/boards-category-loading-test.js
@@ -0,0 +1,113 @@
+import { visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import PermissionType from "discourse/models/permission-type";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import {
+ acceptance,
+ publishToMessageBus,
+} from "discourse/tests/helpers/qunit-helpers";
+
+const CATEGORY_ID = 12345;
+const CATEGORY_NAME = "Unvisited category";
+const BOARD_ID = 1;
+const COLUMN_ID = 10;
+const CARD_ID = 101;
+const category = {
+ id: CATEGORY_ID,
+ name: CATEGORY_NAME,
+ slug: "unvisited-category",
+ color: "0088CC",
+ text_color: "FFFFFF",
+ permission: PermissionType.FULL,
+};
+
+acceptance("Boards category loading", function (needs) {
+ needs.user({ can_manage_boards: true });
+ needs.settings({ boards_enabled: true });
+ needs.site({ lazy_load_categories: true });
+
+ needs.hooks.beforeEach(function () {
+ this.card = {
+ id: CARD_ID,
+ board_id: BOARD_ID,
+ column_id: COLUMN_ID,
+ card_type: "topic",
+ position: 0,
+ topic_id: 42,
+ topic: {
+ id: 42,
+ title: "Unvisited topic",
+ slug: "unvisited-topic",
+ category_id: CATEGORY_ID,
+ },
+ };
+ this.column = {
+ id: COLUMN_ID,
+ title: "Todo",
+ default_sort: "priority",
+ cards: [
+ {
+ ...this.card,
+ id: CARD_ID + 1,
+ topic_id: 43,
+ position: 1,
+ topic: { ...this.card.topic, id: 43, category_id: 1 },
+ },
+ ],
+ };
+ this.board = {
+ id: BOARD_ID,
+ name: "Category audit",
+ slug: "category-audit",
+ can_write: true,
+ can_manage: true,
+ category_ids: [],
+ tag_names: [],
+ columns: [this.column],
+ };
+ pretender.get("/categories/find", (request) =>
+ response({
+ categories: request.queryParams.ids.map((id) =>
+ Number(id) === CATEGORY_ID
+ ? category
+ : {
+ ...category,
+ id: Number(id),
+ name: "Uncategorized",
+ slug: "uncategorized",
+ }
+ ),
+ })
+ );
+ pretender.get(`/boards/api/boards/${BOARD_ID}.json`, () =>
+ response({ board: this.board, columns: [this.column] })
+ );
+ });
+
+ test("incoming topic cards load their categories", async function (assert) {
+ await visit(`/boards/category-audit/${BOARD_ID}`);
+ await publishToMessageBus(`/boards/${BOARD_ID}`, {
+ type: "card_created",
+ card: this.card,
+ });
+
+ assert
+ .dom(`[data-card-id="${CARD_ID}"] .discourse-boards-card__category`)
+ .includesText(CATEGORY_NAME, "the incoming card loads its category");
+ });
+
+ test("board refresh loads newly configured categories", async function (assert) {
+ await visit(`/boards/category-audit/${BOARD_ID}`);
+ this.board.category_ids = [CATEGORY_ID];
+ await publishToMessageBus(`/boards/${BOARD_ID}`, {
+ type: "board_updated",
+ });
+
+ assert
+ .dom(".discourse-boards-board-viewer__constraint")
+ .includesText(
+ CATEGORY_NAME,
+ "the refreshed board loads its new constraint"
+ );
+ });
+});
diff --git a/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs b/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs
new file mode 100644
index 00000000000..87dae8eff35
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs
@@ -0,0 +1,234 @@
+import Service from "@ember/service";
+import { click, getRootElement, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import PermissionType from "discourse/models/permission-type";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import BoardsBoardViewer from "discourse/plugins/boards/discourse/components/boards-board-viewer";
+import BoardsCard from "discourse/plugins/boards/discourse/components/boards-card";
+import BoardsPage from "discourse/plugins/boards/discourse/components/boards-page";
+import BoardsBoardSettings from "discourse/plugins/boards/discourse/components/modal/boards-board-settings";
+import BoardsConstraintFix from "discourse/plugins/boards/discourse/components/modal/boards-constraint-fix";
+import BoardsTopicCardDetail from "discourse/plugins/boards/discourse/components/modal/boards-topic-card-detail";
+import BoardsFabricators from "discourse/plugins/boards/discourse/lib/fabricators";
+import Board from "discourse/plugins/boards/discourse/models/board";
+
+const CATEGORY_ID = 12345;
+const CATEGORY_NAME = "Unvisited category";
+const ADDITIONAL_CATEGORY_ID = 12346;
+const ADDITIONAL_CATEGORY_NAME = "Another category";
+const category = {
+ id: CATEGORY_ID,
+ name: CATEGORY_NAME,
+ slug: "unvisited-category",
+ color: "0088CC",
+ text_color: "FFFFFF",
+ permission: PermissionType.FULL,
+};
+const additionalCategory = {
+ ...category,
+ id: ADDITIONAL_CATEGORY_ID,
+ name: ADDITIONAL_CATEGORY_NAME,
+ slug: "another-category",
+};
+
+module("Integration | Component | Boards category loading", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.site.set("lazy_load_categories", true);
+ this.owner.lookup("service:modal").containerElement = getRootElement();
+ this.fabricators = new BoardsFabricators(this.owner);
+ this.board = this.fabricators.board();
+ this.board.category_ids = [CATEGORY_ID];
+ this.board.tag_names = [];
+ this.column = this.fabricators.column();
+ this.column.cards = [];
+ this.model = { board: this.board, columns: [this.column] };
+ this.onSave = sinon.spy();
+ this.closeModal = sinon.spy();
+ this.settingsModel = {
+ board: this.board,
+ isNew: false,
+ onSave: this.onSave,
+ };
+ const messageBus = this.owner.lookup("service:message-bus");
+ sinon.stub(messageBus, "subscribe");
+ sinon.stub(messageBus, "unsubscribe");
+ pretender.get("/categories/find", (request) =>
+ response({
+ categories: [category, additionalCategory].filter((item) =>
+ request.queryParams.ids.includes(String(item.id))
+ ),
+ })
+ );
+ pretender.post("/categories/search", () =>
+ response({ categories: [additionalCategory] })
+ );
+ pretender.post(
+ `/boards/api/boards/${this.board.id}/constraint-preview`,
+ () => response({ cards_to_remove: 0 })
+ );
+ pretender.post("/access-control/evaluate.json", () => response({}));
+ pretender.get("/posts/by_number/42/1.json", () =>
+ response({ cooked: "<p>Topic body</p>" })
+ );
+ this.topicCard = this.fabricators.card({
+ board_id: this.board.id,
+ column_id: this.column.id,
+ topic: {
+ id: 42,
+ title: "Topic in an unvisited category",
+ slug: "unvisited-topic",
+ category_id: CATEGORY_ID,
+ },
+ });
+ });
+
+ for (const cacheState of ["cached", "uncached"]) {
+ test(`constraint dialog names a ${cacheState} category`, async function (assert) {
+ if (cacheState === "cached") {
+ this.site.updateCategory(category);
+ }
+
+ this.constraintModel = {
+ topic: { category_id: 1 },
+ mismatches: {
+ needsCategory: true,
+ boardCategoryIds: [CATEGORY_ID],
+ },
+ };
+ await render(
+ <template>
+ <BoardsConstraintFix @model={{this.constraintModel}} />
+ </template>
+ );
+
+ assert.dom(`[data-category-id="${CATEGORY_ID}"]`).hasText(CATEGORY_NAME);
+ });
+ }
+
+ test("a category omitted by the server does not prevent loading the board", async function (assert) {
+ this.board.category_ids = [CATEGORY_ID, ADDITIONAL_CATEGORY_ID];
+ pretender.get("/categories/find", () =>
+ response({ categories: [category] })
+ );
+
+ const payload = await Board.createPayload(this.model);
+
+ assert.strictEqual(
+ payload.board.id,
+ this.board.id,
+ "the board remains available"
+ );
+ });
+
+ test("boards list displays category constraints", async function (assert) {
+ this.boards = [this.board];
+ await render(<template><BoardsPage @boards={{this.boards}} /></template>);
+
+ assert
+ .dom(".discourse-boards-board-card__constraints")
+ .includesText(CATEGORY_NAME, "the board constraint is visible");
+ });
+
+ test("board header displays category constraints", async function (assert) {
+ await render(
+ <template><BoardsBoardViewer @model={{this.model}} /></template>
+ );
+
+ assert
+ .dom(".discourse-boards-board-viewer__constraint")
+ .includesText(CATEGORY_NAME, "the board constraint is visible");
+ });
+
+ test("topic card displays its category", async function (assert) {
+ await render(
+ <template>
+ <BoardsCard @board={{this.board}} @card={{this.topicCard}} />
+ </template>
+ );
+
+ assert
+ .dom(".discourse-boards-card__category")
+ .includesText(CATEGORY_NAME, "the topic category is visible");
+ });
+
+ test("topic detail displays its category", async function (assert) {
+ this.detailModel = { card: this.topicCard };
+ pretender.post(
+ `/boards/api/boards/${this.board.id}/cards/${this.topicCard.id}/view`,
+ () => response({})
+ );
+ await render(
+ <template><BoardsTopicCardDetail @model={{this.detailModel}} /></template>
+ );
+
+ assert
+ .dom(".discourse-boards-topic-card-detail__meta")
+ .includesText(CATEGORY_NAME, "the topic category is visible");
+ });
+
+ test("adding a category preserves existing category constraints", async function (assert) {
+ await render(
+ <template>
+ <BoardsBoardSettings
+ @closeModal={{this.closeModal}}
+ @inline={{true}}
+ @model={{this.settingsModel}}
+ />
+ </template>
+ );
+ assert.dom(".category-selector").includesText(CATEGORY_NAME);
+
+ const selector = selectKit(".category-selector");
+ await selector.expand();
+ await selector.selectRowByValue(ADDITIONAL_CATEGORY_ID);
+ await formKit().submit();
+
+ assert.true(this.onSave.calledOnce, "settings are saved");
+ assert.deepEqual(
+ this.onSave.firstCall.args[0].category_ids,
+ [CATEGORY_ID, ADDITIONAL_CATEGORY_ID],
+ "adding a category retains the original constraint"
+ );
+ });
+
+ for (const source of ["board", "column"]) {
+ test(`promoting a floater passes the ${source} category to the composer`, async function (assert) {
+ const card = this.fabricators.card({
+ board_id: this.board.id,
+ column_id: this.column.id,
+ });
+ this.column.cards = [card];
+
+ if (source === "column") {
+ this.board.category_ids = [];
+ this.column.move_to_category_id = CATEGORY_ID;
+ }
+
+ const openNewTopic = sinon.stub().resolves();
+ this.owner.register(
+ "service:composer",
+ class extends Service {
+ openNewTopic = openNewTopic;
+ }
+ );
+ await render(
+ <template><BoardsBoardViewer @model={{this.model}} /></template>
+ );
+ await click(".discourse-boards-card__actions-trigger");
+ await click(".fk-d-menu button:has(.d-icon-plus)");
+
+ assert.true(openNewTopic.calledOnce, "the composer opens");
+ assert.strictEqual(
+ openNewTopic.firstCall.args[0].category?.id,
+ CATEGORY_ID,
+ "the composer receives the intended category"
+ );
+ });
+ }
+});