Skip to content

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

DEV: Convert `TopicList`, `NavItem` and `CategoryList` to TypeScript (#45195)

Sérgio Saquetim9912bab70ae7
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 7b6826b41b6..23d7c3e64fc 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -1701,6 +1701,8 @@ class _PluginApi {
* before: "top",
* forceActive: (category, args, router) => router.currentURL === "/a/b/c/d",
* })
+ *
+ * @param {import("discourse/models/nav-item").NavigationBarItem} item
*/
addNavigationBarItem(item) {
if (!item["name"]) {
diff --git a/frontend/discourse/app/models/category-list.js b/frontend/discourse/app/models/category-list.ts
similarity index 55%
rename from frontend/discourse/app/models/category-list.js
rename to frontend/discourse/app/models/category-list.ts
index b293b781752..8b2e3d6333e 100644
--- a/frontend/discourse/app/models/category-list.js
+++ b/frontend/discourse/app/models/category-list.ts
@@ -7,31 +7,79 @@ import LegacyArrayLikeObject from "discourse/lib/legacy-array-like-object";
import PreloadStore from "discourse/lib/preload-store";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { applyValueTransformer } from "discourse/lib/transformer";
+import type {
+ CategoryFields,
+ default as Category,
+} from "discourse/models/category";
import Site from "discourse/models/site";
-import Topic from "discourse/models/topic";
+import Topic, { type TopicCreateAttrs } from "discourse/models/topic";
+import type { TopicListParams } from "discourse/models/topic-list";
+import type StoreService from "discourse/services/store";
import { i18n } from "discourse-i18n";
+/** Detailed categories contain listable topic payloads and recursively serialized children. */
+export interface CategoryListCategory extends Omit<
+ CategoryFields,
+ "topics" | "subcategory_list"
+> {
+ topics?: (TopicCreateAttrs<Topic> | Topic)[];
+ subcategory_list?: CategoryListCategory[];
+}
+
+export interface CategoryListEnvelope {
+ category_list?: {
+ categories?: CategoryListCategory[];
+ can_create_category?: boolean;
+ can_create_topic?: boolean;
+ };
+}
+
+/** Only the combined categories page installs loadBefore; it does not initialize params. */
+export interface CategoryListFields {
+ params?: TopicListParams;
+ loadBefore?: (topicIds: number[], storeInSession?: boolean) => Promise<void>;
+}
+
+export type CategoryListCreateAttrs<M = CategoryList> = Partial<
+ Omit<M, "parentCategory">
+> & {
+ categories?: Category[];
+ parentCategory?: Pick<Category, "id"> | null;
+} & Record<string, unknown>;
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface CategoryList extends CategoryListFields {}
+
const STAT_PERIODS = ["week", "month"];
/**
* Represents a list of categories with their related metadata and functionality
*/
-export default class CategoryList extends LegacyArrayLikeObject {
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class CategoryList extends LegacyArrayLikeObject<Category> {
/**
* Creates category objects from API result data
*
- * @param {import("discourse/services/store").default} store - The store instance
- * @param {Record<string, unknown>} result - The API result containing category data
- * @param {import("discourse/models/category").default | null} [parentCategory] - Optional parent category
- * @returns {CategoryList} A new CategoryList instance with the processed categories
+ * @param store - The store instance
+ * @param result - The API result containing category data
+ * @param parentCategory - Optional parent category
*/
- static categoriesFrom(store, result, parentCategory = null) {
+ static categoriesFrom(
+ store: StoreService,
+ result: CategoryListEnvelope | null | undefined,
+ parentCategory: Pick<Category, "id"> | null = null
+ ) {
// Find the period that is most relevant
const list = result?.category_list?.categories || [];
const statPeriod =
STAT_PERIODS.find(
(period) =>
- list.filter((c) => c?.[`topics_${period}`] > 0).length >=
+ list.filter(
+ (c) =>
+ (c?.[
+ `topics_${period}` as "topics_week" | "topics_month"
+ ] as number) > 0
+ ).length >=
list.length * 0.66
) || "all";
@@ -40,13 +88,14 @@ export default class CategoryList extends LegacyArrayLikeObject {
list.forEach((c) => Site.current().updateCategory(c));
const categories = CategoryList.create({ store });
- list.forEach((c) => {
+ list.forEach((c: CategoryListCategory | Category) => {
c = this._buildCategoryResult(c, statPeriod);
if (
(parentCategory && c.parent_category_id === parentCategory.id) ||
(!parentCategory && !c.parent_category_id)
) {
- categories.content.push(c);
+ // The reassigned callback parameter now holds the hydrated Category.
+ categories.content.push(c as Category);
}
});
return categories;
@@ -54,19 +103,27 @@ export default class CategoryList extends LegacyArrayLikeObject {
/**
* Builds a category result object with stats and topic data
- * @param {Object} rawCategoryData - The raw category data
- * @param {string} statPeriod - The period to use for stats ('week', 'month', or 'all')
- * @returns {Category} The processed category object
- * @private
+ * @param rawCategoryData - The raw category data
+ * @param statPeriod - The period to use for stats ('week', 'month', or 'all')
+ * @internal
*/
- static _buildCategoryResult(rawCategoryData, statPeriod) {
+ static _buildCategoryResult(
+ rawCategoryData: CategoryListCategory,
+ statPeriod: string
+ ) {
if (rawCategoryData.topics?.length) {
rawCategoryData.topics = rawCategoryData.topics.map((t) =>
- Topic.create(t)
+ Topic.create(t as TopicCreateAttrs<Topic>)
);
}
- const stat = rawCategoryData[`topics_${statPeriod}`];
+ const stat =
+ rawCategoryData[
+ `topics_${statPeriod}` as
+ | "topics_week"
+ | "topics_month"
+ | "topics_all_time"
+ ]!;
const isTimedPeriod = statPeriod === "week" || statPeriod === "month";
if (isTimedPeriod && stat > 0) {
const unit = i18n(`categories.topic_stat_unit.${statPeriod}`);
@@ -86,17 +143,17 @@ export default class CategoryList extends LegacyArrayLikeObject {
rawCategoryData.pickAll = false;
} else {
- rawCategoryData.stat = `<span class="value">${number(rawCategoryData.topics_all_time)}</span>`;
+ rawCategoryData.stat = `<span class="value">${number(rawCategoryData.topics_all_time!)}</span>`;
rawCategoryData.statTitle = i18n("categories.topic_sentence", {
- count: rawCategoryData.topics_all_time,
+ count: rawCategoryData.topics_all_time!,
});
rawCategoryData.pickAll = true;
}
if (Site.current().mobileView) {
rawCategoryData.statTotal = i18n("categories.topic_stat_all_time", {
- count: rawCategoryData.topics_all_time,
- number: `<span class="value">${number(rawCategoryData.topics_all_time)}</span>`,
+ count: rawCategoryData.topics_all_time!,
+ number: `<span class="value">${number(rawCategoryData.topics_all_time!)}</span>`,
});
}
@@ -108,7 +165,10 @@ export default class CategoryList extends LegacyArrayLikeObject {
/**
* @deprecated Use list() instead
*/
- static listForParent(store, parentCategory) {
+ static listForParent(
+ store: StoreService,
+ parentCategory: Pick<Category, "id"> | null
+ ) {
deprecated(
"The listForParent method of CategoryList is deprecated. Use list instead",
{ id: "discourse.category-list.listForParent" }
@@ -120,15 +180,18 @@ export default class CategoryList extends LegacyArrayLikeObject {
/**
* Fetches and creates a list of categories
*
- * @param {import("discourse/services/store").default} store - The store instance
- * @param {import("discourse/models/category").default | null} [parentCategory] - Optional parent category to filter by
- * @returns {Promise<CategoryList>} A promise that resolves to the CategoryList
+ * @param store - The store instance
+ * @param parentCategory - Optional parent category to filter by
*/
- static async list(store, parentCategory = null) {
- const result = await PreloadStore.getAndRemove(
+ static async list(
+ store: StoreService,
+ parentCategory: Pick<Category, "id"> | null = null
+ ) {
+ // TODO(typescript-pending): remove this payload assertion when PreloadStore and ajax preserve response types.
+ const result = (await PreloadStore.getAndRemove(
"categories_list",
async () => {
- const data = {};
+ const data: { parent_category_id?: number } = {};
if (parentCategory) {
data.parent_category_id = parentCategory.id;
}
@@ -138,7 +201,7 @@ export default class CategoryList extends LegacyArrayLikeObject {
}),
});
}
- );
+ )) as CategoryListEnvelope | null | undefined;
const categoryList = result?.category_list || {};
return CategoryList.create(
@@ -160,25 +223,28 @@ export default class CategoryList extends LegacyArrayLikeObject {
/**
* Creates a new CategoryList instance
*
- * @param {Record<string, unknown>} [attrs] - The attributes to initialize with
- * @returns {CategoryList} A new CategoryList instance
+ * @param attrs - The attributes to initialize with
*/
- static create(attrs = {}) {
+ static create<M extends LegacyArrayLikeObject>(
+ this: new (...args: never[]) => M,
+ attrs?: CategoryListCreateAttrs<M>
+ ): M;
+
+ static create(attrs: Partial<CategoryList> & Record<string, unknown> = {}) {
const { categories, ...properties } = attrs;
return super.create({ content: categories, ...properties });
}
- @tracked can_create_category;
- @tracked can_create_topic;
+ @tracked can_create_category?: boolean;
+ @tracked can_create_topic?: boolean;
@tracked fetchedLastPage = false;
@tracked isLoading = false;
@tracked page = 1;
- @tracked parentCategory;
- @autoTrackedArray topics;
- store;
+ @tracked parentCategory?: Category | null;
+ @autoTrackedArray topics?: Topic[];
+ store!: StoreService;
/**
- * @returns {Proxy} The proxied content for compatibility
* @deprecated use the category list instance instead
*/
get categories() {
@@ -191,7 +257,6 @@ export default class CategoryList extends LegacyArrayLikeObject {
/**
* Loads more categories from the server
- * @returns {Promise<void>}
*/
@bind
async loadMore() {
@@ -210,7 +275,10 @@ export default class CategoryList extends LegacyArrayLikeObject {
}),
};
- const result = await ajax("/categories.json", { data });
+ // TODO(typescript-pending): ajax does not publish response types; remove the assertion when its response is generic.
+ const result = (await ajax("/categories.json", {
+ data,
+ })) as CategoryListEnvelope;
this.page = nextPage;
diff --git a/frontend/discourse/app/models/category.ts b/frontend/discourse/app/models/category.ts
index 325708e4991..dae0180105f 100644
--- a/frontend/discourse/app/models/category.ts
+++ b/frontend/discourse/app/models/category.ts
@@ -22,9 +22,11 @@ import { NotificationLevels } from "discourse/lib/notification-levels";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { applyValueTransformer } from "discourse/lib/transformer";
import { removeAccents } from "discourse/lib/utilities";
+import type { CategoryListCategory } from "discourse/models/category-list";
import PermissionType from "discourse/models/permission-type";
import RestModel from "discourse/models/rest";
import Site from "discourse/models/site";
+import type { TopicCreateAttrs } from "discourse/models/topic";
import type User from "discourse/models/user";
import type StoreService from "discourse/services/store";
import Topic from "./topic.ts";
@@ -161,7 +163,7 @@ export interface CategoryFields {
has_children?: boolean | null;
subcategory_count?: number | null;
subcategory_ids?: number[] | null;
- subcategory_list?: object[];
+ subcategory_list?: CategoryListCategory[];
subcategory_list_style?: string | null;
sort_order?: string | null;
sort_ascending?: boolean | null;
@@ -206,7 +208,7 @@ export interface CategoryFields {
category_type_settings?: Record<string, unknown>;
category_type_site_settings?: Record<string, unknown>;
site_texts?: Record<string, string>;
- topics?: object[];
+ topics?: (TopicCreateAttrs<Topic> | Topic)[];
topics_day?: number;
topics_week?: number;
topics_month?: number;
@@ -846,17 +848,12 @@ export default class Category extends RestModel {
@computed("subcategory_list")
get serializedSubcategories() {
- // TODO(typescript-pending): serialized subcategories include topic payloads; remove when typed at the source.
- return (
- this.subcategory_list as
- | (Omit<CategoryFields, "topics"> & {
- topics?: Record<string, unknown>[];
- })[]
- | undefined
- )?.map((c) => {
+ return this.subcategory_list?.map((c) => {
const subcategory = Category.create({
...c,
- topics: c.topics?.map((t) => Topic.create(t)),
+ topics: c.topics?.map((t) =>
+ Topic.create(t as TopicCreateAttrs<Topic>)
+ ),
});
return subcategory;
});
diff --git a/frontend/discourse/app/models/nav-item.js b/frontend/discourse/app/models/nav-item.ts
similarity index 50%
rename from frontend/discourse/app/models/nav-item.js
rename to frontend/discourse/app/models/nav-item.ts
index 41fa56703d3..7b8d6b6da5b 100644
--- a/frontend/discourse/app/models/nav-item.js
+++ b/frontend/discourse/app/models/nav-item.ts
@@ -1,6 +1,7 @@
import { tracked } from "@glimmer/tracking";
import EmberObject, { computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
+import type RouterService from "@ember/routing/router-service";
import { service } from "@ember/service";
import deprecated from "discourse/lib/deprecated";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
@@ -12,16 +13,128 @@ import {
isTrackedTopic,
} from "discourse/lib/topic-list-tracked-filter";
import Category from "discourse/models/category";
+import type { RestModelStoreAttrs } from "discourse/models/rest";
import Site from "discourse/models/site";
+import type TopicTrackingState from "discourse/models/topic-tracking-state";
import User from "discourse/models/user";
+import type SiteSettingsService from "discourse/services/site-settings";
+import type StoreService from "discourse/services/store";
import { i18n } from "discourse-i18n";
+export interface NavItemContext {
+ category?: Category;
+ tag?: { id?: number; slug?: string };
+ noSubcategories?: boolean;
+}
+
+/** Build options preserve filterType and filterMode as distinct inputs. */
+export interface NavItemOptions extends NavItemContext {
+ tagId?: number;
+ currentRouteQueryParams?: Record<string, unknown>;
+ /** TODO(typescript-pending): the site-settings factory has no typed setting keys; remove the extension when it declares top_menu. */
+ siteSettings?: {
+ [K in keyof ReturnType<typeof SiteSettingsService.create>]: unknown;
+ } & {
+ top_menu: string;
+ };
+ filterType?: string;
+ filterMode?: string;
+ skipCategoriesNavItem?: boolean;
+}
+
+/** Creation-only state; getters and tracked fields are declared on the class. */
+export interface NavItemFields
+ extends
+ RestModelStoreAttrs,
+ Omit<
+ NavItemOptions,
+ | "tag"
+ | "siteSettings"
+ | "filterMode"
+ | "filterType"
+ | "skipCategoriesNavItem"
+ > {
+ active?: boolean;
+ hasIcon?: boolean;
+ includeCategoryId?: boolean;
+ classNames?: string;
+}
+
+/** Filter callbacks are tested for truthiness; existing extensions also return user objects. */
+export type ExtraNavItemFilter = (
+ category: Category | null | undefined,
+ args: NavItemOptions
+) => unknown;
+
+/** Direct registrations receive two context arguments; init receives the item first. */
+export interface NavItemDescriptor extends Partial<NavItemFields> {
+ name: string;
+ displayName?: string;
+ title?: string;
+ href?: string;
+ count?: number;
+ before?: string;
+ customFilter?: ExtraNavItemFilter | null;
+ customHref?: (
+ category: Category | null | undefined,
+ args: NavItemOptions
+ ) => string | undefined;
+ forceActive?: ExtraNavItemFilter;
+ init?: (
+ item: ExtraNavItem,
+ category: Category | null | undefined,
+ args: NavItemOptions
+ ) => void;
+}
+
+/** The plugin API appends the router before registering the descriptor. */
+export interface NavigationBarItem extends Omit<
+ NavItemDescriptor,
+ "customFilter" | "customHref" | "forceActive" | "init"
+> {
+ customFilter?: (
+ category: Category | null | undefined,
+ args: NavItemOptions,
+ router: RouterService
+ ) => unknown;
+ customHref?: (
+ category: Category | null | undefined,
+ args: NavItemOptions,
+ router: RouterService
+ ) => string | undefined;
+ forceActive?: (
+ category: Category | null | undefined,
+ args: NavItemOptions,
+ router: RouterService
+ ) => unknown;
+ init?: (
+ item: ExtraNavItem,
+ category: Category | null | undefined,
+ args: NavItemOptions,
+ router: RouterService
+ ) => void;
+}
+
+export type ExtraNavItemPropertiesCallback = (
+ this: typeof NavItem,
+ filterType: string,
+ opts: NavItemOptions
+) => Partial<NavItem>;
+export type CustomNavItemHrefCallback = (
+ this: NavItem,
+ item: NavItem
+) => string | null | undefined;
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface NavItem extends NavItemFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export default class NavItem extends EmberObject {
- static extraArgsCallbacks = [];
- static customNavItemHrefs = [];
- static extraNavItemDescriptors = [];
+ static extraArgsCallbacks: ExtraNavItemPropertiesCallback[] = [];
+ static customNavItemHrefs: CustomNavItemHrefCallback[] = [];
+ static extraNavItemDescriptors: NavItemDescriptor[] = [];
- static pathFor(filterType, context) {
+ static pathFor(filterType: string, context: NavItemContext): string {
let path = getURL("");
let includesCategoryContext = false;
let includesTagContext = false;
@@ -53,7 +166,7 @@ export default class NavItem extends EmberObject {
if (includesTagContext) {
// use canonical URL format with slug/id when id is available
- path += tag.id ? `/${tag.slug}/${tag.id}` : `/${tag.slug}`;
+ path += tag!.id ? `/${tag!.slug}/${tag!.id}` : `/${tag!.slug}`;
}
if (includesTagContext || includesCategoryContext) {
@@ -68,9 +181,8 @@ export default class NavItem extends EmberObject {
return path;
}
- // Create a nav item given a filterType. It returns null if there is not
- // valid nav item. The name is a historical artifact.
- static fromText(filterType, opts) {
+ /** Create a nav item given a filterType, or null if unavailable. The name is a historical artifact. */
+ static fromText(filterType: string, opts?: NavItemOptions): NavItem | null {
const anonymous = !User.current();
opts = opts || {};
@@ -85,11 +197,15 @@ export default class NavItem extends EmberObject {
if (!Category.list() && filterType === "categories") {
return null;
}
- if (!Site.currentProp("top_menu_items").includes(filterType)) {
+ if (!Site.currentProp("top_menu_items")!.includes(filterType)) {
return null;
}
- let args = { name: filterType, hasIcon: filterType === "unread" };
+ // eslint-disable-next-line prefer-const -- Preserve the original declaration in this types-only port.
+ let args: Partial<NavItem> = {
+ name: filterType,
+ hasIcon: filterType === "unread",
+ };
if (opts.category) {
args.category = opts.category;
}
@@ -106,11 +222,16 @@ export default class NavItem extends EmberObject {
deepMerge(args, cb.call(this, filterType, opts))
);
+ // TODO(typescript-pending): remove the store assertion when getOwnerWithFallback publishes typed service lookups.
+ // eslint-disable-next-line prefer-const -- Preserve the original declaration in this types-only port.
let store = getOwnerWithFallback(this).lookup("service:store");
- return store.createRecord("nav-item", args);
+ return (store as StoreService).createRecord("nav-item", args);
}
- static buildList(category, args) {
+ static buildList(
+ category: Category | undefined,
+ args?: NavItemOptions
+ ): NavItem[] {
args = args || {};
if (category) {
@@ -126,19 +247,20 @@ export default class NavItem extends EmberObject {
"service:site-settings"
);
}
- let items = args.siteSettings.top_menu.split("|");
+ let items: (string | NavItem | null)[] =
+ args.siteSettings!.top_menu.split("|");
const user = getOwnerWithFallback(this).lookup("service:current-user");
if (user?.unified_new_enabled) {
items = items.filter((item) => item !== "unread");
}
- const filterType = (args.filterMode || "").split("/").pop();
+ const filterType = (args.filterMode || "").split("/").pop()!;
if (!items.some((i) => filterType === i)) {
items.push(filterType);
}
- items = items
+ items = (items as string[])
.map((i) => NavItem.fromText(i, args))
.filter((i) => {
if (i === null) {
@@ -162,9 +284,12 @@ export default class NavItem extends EmberObject {
noSubcategories: args.noSubcategories,
};
+ // TODO(typescript-pending): remove the descriptor assertion when deepMerge preserves its input shapes.
const extraItems = NavItem.extraNavItemDescriptors
.map((descriptor) =>
- ExtraNavItem.create(deepMerge({}, context, descriptor))
+ ExtraNavItem.create(
+ deepMerge({}, context, descriptor) as NavItemDescriptor
+ )
)
.filter((item) => {
if (!item.customFilter) {
@@ -184,7 +309,7 @@ export default class NavItem extends EmberObject {
if (before) {
let i;
for (i = 0; i < items.length; i++) {
- if (items[i].name === before) {
+ if ((items[i] as NavItem).name === before) {
break;
}
}
@@ -194,7 +319,8 @@ export default class NavItem extends EmberObject {
}
if (item.customHref) {
- item.href = item.customHref(category, args);
+ // The public href contract is string; an untyped extension can still return undefined.
+ item.href = item.customHref(category, args) as string;
} else if (item.href) {
item.href = getURL(item.href);
}
@@ -209,24 +335,24 @@ export default class NavItem extends EmberObject {
if (forceActive) {
items.forEach((i) => {
- if (i.active === undefined) {
- i.active = false;
+ if ((i as NavItem).active === undefined) {
+ (i as NavItem).active = false;
}
});
}
- return items;
+ return items as NavItem[];
}
- @service topicTrackingState;
- @service currentUser;
+ @service declare topicTrackingState: TopicTrackingState;
+ @service declare currentUser: User | null;
- @tracked name;
- @tracked tag;
+ @tracked name!: string;
+ @tracked tag?: NavItemContext["tag"];
- @tracked _title;
- @tracked _displayName;
+ @tracked _title?: string;
+ @tracked _displayName?: string;
- @tracked _filterTypeOverride;
+ @tracked _filterTypeOverride?: string;
@dependentKeyCompat
get filterType() {
@@ -236,7 +362,7 @@ export default class NavItem extends EmberObject {
return this.name;
}
- set filterType(value) {
+ set filterType(value: string) {
this._filterTypeOverride = value;
}
@@ -255,7 +381,7 @@ export default class NavItem extends EmberObject {
return i18n("filters." + nameKey + ".help", {});
}
- set title(value) {
+ set title(value: string) {
this._title = value;
}
@@ -274,6 +400,7 @@ export default class NavItem extends EmberObject {
count = 0;
}
+ // eslint-disable-next-line prefer-const -- Preserve the original declaration in this types-only port.
let extra = { count };
const titleKey = count === 0 ? ".title" : ".title_with_count";
@@ -282,15 +409,15 @@ export default class NavItem extends EmberObject {
);
}
- set displayName(value) {
+ set displayName(value: string) {
this._displayName = value;
}
@computed("filterType", "category", "noSubcategories", "tag")
- get href() {
- let customHref = null;
+ get href(): string {
+ let customHref: string | null | undefined = null;
- NavItem.customNavItemHrefs.forEach(function (cb) {
+ NavItem.customNavItemHrefs.forEach(function (this: NavItem, cb) {
customHref = cb.call(this, this);
if (customHref) {
return false;
@@ -331,7 +458,7 @@ export default class NavItem extends EmberObject {
"currentRouteQueryParams",
"topicTrackingState.messageCount"
)
- get count() {
+ get count(): number | undefined {
return this.topicTrackingState?.lookupCount({
type: this.name,
category: this.category,
@@ -344,19 +471,50 @@ export default class NavItem extends EmberObject {
}
}
-export class ExtraNavItem extends NavItem {
- @tracked href;
+/** Erased constructor view permits the writable tracked overrides of computed accessors. */
+type WritableNavItemBase = Omit<typeof NavItem, "prototype"> & {
+ new (...args: ConstructorParameters<typeof NavItem>): Omit<
+ NavItem,
+ "href" | "count" | "init"
+ > & {
+ init(properties?: object): void;
+ };
+};
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export interface ExtraNavItem extends Pick<
+ NavItemDescriptor,
+ "before" | "customHref" | "forceActive"
+> {
+ init: {
+ (properties?: object): void;
+ (
+ item: ExtraNavItem,
+ category: Category | undefined,
+ args: NavItemOptions
+ ): void;
+ };
+}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export class ExtraNavItem extends (NavItem as WritableNavItemBase) {
+ declare static create: <C extends new (...args: never[]) => ExtraNavItem>(
+ this: C,
+ attrs?: Partial<Omit<InstanceType<C>, "init">> &
+ Pick<NavItemDescriptor, "init">
+ ) => InstanceType<C>;
+
+ @tracked href!: string;
@tracked count = 0;
- /** @type {((category: Category | null | undefined, args: Record<string, unknown>) => boolean) | null} */
- customFilter = null;
+ customFilter: ExtraNavItemFilter | null = null;
}
-export function extraNavItemProperties(cb) {
+export function extraNavItemProperties(cb: ExtraNavItemPropertiesCallback) {
NavItem.extraArgsCallbacks.push(cb);
}
-export function customNavItemHref(cb) {
+export function customNavItemHref(cb: CustomNavItemHrefCallback) {
NavItem.customNavItemHrefs.push(cb);
}
@@ -366,6 +524,6 @@ export function clearNavItems() {
NavItem.extraNavItemDescriptors.length = 0;
}
-export function addNavItem(item) {
+export function addNavItem(item: NavItemDescriptor) {
NavItem.extraNavItemDescriptors.push(item);
}
diff --git a/frontend/discourse/app/models/topic-list.js b/frontend/discourse/app/models/topic-list.js
deleted file mode 100644
index 23fea414aa7..00000000000
--- a/frontend/discourse/app/models/topic-list.js
+++ /dev/null
@@ -1,259 +0,0 @@
-import { tracked } from "@glimmer/tracking";
-import EmberObject, { action, computed } from "@ember/object";
-import { service } from "@ember/service";
-import { isEmpty } from "@ember/utils";
-import { Promise } from "rsvp";
-import { ajax } from "discourse/lib/ajax";
-import { removeValuesFromArray } from "discourse/lib/array-tools";
-import deprecated from "discourse/lib/deprecated";
-import { getOwnerWithFallback } from "discourse/lib/get-owner";
-import { autoTrackedArray } from "discourse/lib/tracked-tools";
-import { applyValueTransformer } from "discourse/lib/transformer";
-import RestModel from "discourse/models/rest";
-import Site from "discourse/models/site";
-import User from "discourse/models/user";
-import Topic from "./topic.ts";
-
-function extractByKey(collection, klass) {
- const retval = {};
- if (isEmpty(collection)) {
- return retval;
- }
-
- collection.forEach(function (item) {
- retval[item.id] = klass.create(item);
- });
- return retval;
-}
-
-// Whether to show the category badge in topic lists
-function displayCategoryInList(site, category) {
- if (category) {
- if (category.has_children) {
- return true;
- }
-
- const draftCategoryId = site.shared_drafts_category_id;
- if (draftCategoryId && category.id === draftCategoryId) {
- return true;
- }
-
- return false;
- }
-
- return true;
-}
-
-export default class TopicList extends RestModel {
- static topicsFrom(store, result, opts) {
- if (!result) {
- return;
- }
-
- opts = opts || {};
- let listKey = opts.listKey || "topics";
-
- // Stitch together our side loaded data
-
- const users = extractByKey(result.users, User);
- const groups = extractByKey(result.primary_groups, EmberObject);
-
- if (result.topic_list.categories) {
- result.topic_list.categories.forEach((c) => {
- Site.current().updateCategory(c);
- });
- }
-
- const topics = result.topic_list[listKey].map((t) => {
- t.posters.forEach((p) => {
- p.user = users[p.user_id];
- p.extraClasses = p.extras;
- if (p.primary_group_id) {
- p.primary_group = groups[p.primary_group_id];
- if (p.primary_group) {
- p.extraClasses = `${p.extraClasses || ""} group-${
- p.primary_group.name
- }`;
- }
- }
- });
-
- if (t.participants) {
- t.participants.forEach((p) => (p.user = users[p.user_id]));
- }
-
- return store.createRecord("topic", t);
- });
-
- return applyValueTransformer("topic-list-topics-from", topics, {
- store,
- result,
- opts,
- });
- }
-
- static munge(json, store) {
- json.inserted = json.inserted || [];
- json.can_create_topic = json.topic_list.can_create_topic;
- json.more_topics_url = json.topic_list.more_topics_url;
- json.for_period = json.topic_list.for_period;
- json.loaded = true;
- json.per_page = json.topic_list.per_page;
- json.topics = this.topicsFrom(store, json);
-
- if (json.topic_list.shared_drafts) {
- json.sharedDrafts = this.topicsFrom(store, json, {
- listKey: "shared_drafts",
- });
- }
-
- return json;
- }
-
- static find(filter, params) {
- deprecated(
- `TopicList.find is deprecated. Use \`findFiltered("topicList")\` on the \`store\` service instead.`,
- {
- id: "discourse.topic-list-find",
- since: "3.1.0.beta5",
- }
- );
-
- const store = getOwnerWithFallback(this).lookup("service:store");
- return store.findFiltered("topicList", { filter, params });
- }
-
- // hide the category when it has no children
- static hideUniformCategory(list, category) {
- list.set("hideCategory", !displayCategoryInList(list.site, category));
- }
-
- @service session;
-
- @tracked loadingBefore = false;
- @autoTrackedArray topics;
-
- @computed("more_topics_url")
- get canLoadMore() {
- return !isEmpty(this.more_topics_url);
- }
-
- forEachNew(topics, callback) {
- const topicIds = new Set();
- this.topics.forEach((topic) => topicIds.add(topic.id));
-
- topics.forEach((topic) => {
- if (!topicIds.has(topic.id)) {
- callback(topic);
- }
- });
- }
-
- updateSortParams(order, ascending) {
- let params = { ...(this.params || {}) };
-
- if (params.q) {
- // search is unique, nothing else allowed with it
- params = { q: params.q };
- } else {
- params.order = order || params.order;
- params.ascending = ascending;
- }
-
- this.set("params", params);
- }
-
- updateNewListSubsetParam(subset) {
- let params = { ...(this.params || {}) };
-
- if (params.q) {
- params = { q: params.q };
- } else {
- params.subset = subset;
- }
-
- this.set("params", params);
- }
-
- @action
- loadMore() {
- if (this.loadingMore) {
- return Promise.resolve();
- }
-
- let moreUrl = this.more_topics_url;
- if (moreUrl) {
- let [url, params] = moreUrl.split("?");
-
- // ensure we postfix with .json so username paths work
- // correctly
- if (!url.match(/\.json$/)) {
- url += ".json";
- }
-
- moreUrl = url;
- if (params) {
- moreUrl += "?" + params;
- }
-
- this.set("loadingMore", true);
-
- return ajax({ url: moreUrl }).then(async (result) => {
- let topicsAdded = 0;
-
- if (result) {
- // the new topics loaded from the server
- const newTopics = TopicList.topicsFrom(this.store, result);
- await Topic.applyTransformations(newTopics);
-
- this.forEachNew(newTopics, (t) => {
- t.set("highlight", topicsAdded++ === 0);
- this.topics.push(t);
- });
-
- this.setProperties({
- loadingMore: false,
- more_topics_url: result.topic_list.more_topics_url,
- });
-
- this.session.set("topicList", this);
- return { moreTopicsUrl: this.more_topics_url, newTopics };
- }
- });
- } else {
- // Return a promise indicating no more results
- return Promise.resolve();
- }
- }
-
- // loads topics with these ids "before" the current topics
- async loadBefore(topic_ids, storeInSession) {
- this.loadingBefore = topic_ids.length;
-
- try {
- const url = `/${this.filter}.json?topic_ids=${topic_ids.join(",")}`;
-
- const result = await ajax({ url, data: this.params });
-
- // refresh dupes
- removeValuesFromArray(
- this.topics,
- this.topics.filter((topic) => topic_ids.includes(topic.id))
- );
-
- let i = 0;
- this.forEachNew(TopicList.topicsFrom(this.store, result), (t) => {
- // highlight the first of the new topics so we can get a visual feedback
- t.set("highlight", true);
- this.topics.splice(i, 0, t);
- i++;
- });
-
- if (storeInSession) {
- this.session.set("topicList", this);
- }
- } finally {
- this.loadingBefore = false;
- }
- }
-}
diff --git a/frontend/discourse/app/models/topic-list.ts b/frontend/discourse/app/models/topic-list.ts
new file mode 100644
index 00000000000..65ef2dbc1c9
--- /dev/null
+++ b/frontend/discourse/app/models/topic-list.ts
@@ -0,0 +1,414 @@
+import { tracked } from "@glimmer/tracking";
+import EmberObject, { action, computed } from "@ember/object";
+import { service } from "@ember/service";
+import type { TrustedHTML } from "@ember/template";
+import { isEmpty } from "@ember/utils";
+import { Promise } from "rsvp";
+import { ajax } from "discourse/lib/ajax";
+import { removeValuesFromArray } from "discourse/lib/array-tools";
+import deprecated from "discourse/lib/deprecated";
+import { getOwnerWithFallback } from "discourse/lib/get-owner";
+import { autoTrackedArray } from "discourse/lib/tracked-tools";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import type {
+ CategoryFields,
+ default as Category,
+} from "discourse/models/category";
+import RestModel, { type RestPayload } from "discourse/models/rest";
+import type SessionService from "discourse/models/session";
+import Site from "discourse/models/site";
+import type {
+ TopicBasicUser,
+ TopicCreateAttrs,
+ TopicPoster,
+ TopicTag,
+} from "discourse/models/topic";
+import User, { type UserCreateAttrs } from "discourse/models/user";
+import type StoreService from "discourse/services/store";
+import Topic from "./topic.ts";
+
+/** Primary groups are hydrated as plain EmberObjects, rather than Group models. */
+export interface TopicListPrimaryGroup {
+ id: number;
+ name: string;
+}
+
+export interface TopicListFlairGroup extends TopicListPrimaryGroup {
+ flair_url: string | null;
+ flair_bg_color: string | null;
+ flair_color: string | null;
+}
+
+/** Tag lists include details absent from the top-tags summary. */
+export interface TopicListTag extends TopicTag {
+ topic_count: number;
+ staff: boolean;
+ description: string | null;
+ description_cooked: string | null;
+ localizations?: {
+ id: number;
+ tag_id: number;
+ locale: string;
+ name: string | null;
+ description: string | null;
+ description_cooked: string | null;
+ }[];
+}
+
+export interface TopicListFilterOption {
+ name: string;
+ description: string;
+ type?: string;
+ priority?: number;
+ alias?: string;
+ prefixes?: { name: string; description: string }[];
+ delimiters?: { name: string; description: string }[];
+}
+
+/** List items have posters even when the array is empty. Hydration mutates these references. */
+export type TopicListItem = TopicCreateAttrs<Topic> & {
+ posters: TopicPoster[];
+};
+
+export interface TopicListData {
+ topics: TopicListItem[];
+ can_create_topic: boolean;
+ filter: string;
+ per_page: number;
+ more_topics_url?: string;
+ for_period?: string;
+ shared_drafts?: TopicListItem[];
+ categories?: CategoryFields[];
+ top_tags?: TopicTag[];
+ tags?: TopicListTag[];
+ filter_option_info?: TopicListFilterOption[];
+ filter_new_topic_ids?: number[];
+}
+
+/** The side-loaded roots may be omitted for empty lists. They remain on the model. */
+export type TopicListUser = UserCreateAttrs &
+ TopicBasicUser & { trust_level: number };
+
+export interface TopicListEnvelope {
+ topic_list: TopicListData;
+ users?: TopicListUser[];
+ primary_groups?: TopicListPrimaryGroup[];
+ flair_groups?: TopicListFlairGroup[];
+}
+
+export interface TopicListParams {
+ q?: string;
+ order?: string;
+ ascending?: boolean | string;
+ subset?: string;
+ [key: string]:
+ | string
+ | number
+ | boolean
+ | (string | number)[]
+ | null
+ | undefined;
+}
+
+/** Core client state and retained response data; plugins can augment this interface. */
+export interface TopicListFields extends TopicListEnvelope {
+ filter: string;
+ params?: TopicListParams;
+ listParams?: TopicListParams;
+ loaded: boolean;
+ can_create_topic: boolean;
+ per_page: number;
+ more_topics_url?: string;
+ for_period?: string;
+ sharedDrafts?: Topic[];
+ inserted: unknown[];
+ loadingMore?: boolean;
+ hideCategory?: boolean;
+ emptyState?: { title: string; body: string | TrustedHTML };
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface TopicList extends TopicListFields {}
+
+function extractByKey<A extends { id: number }, M>(
+ collection: A[] | undefined,
+ klass: { create(attrs: A): M }
+): Record<number, M | undefined> {
+ const retval: Record<number, M | undefined> = {};
+ if (isEmpty(collection)) {
+ return retval;
+ }
+
+ collection!.forEach(function (item) {
+ retval[item.id] = klass.create(item);
+ });
+ return retval;
+}
+
+/** Whether to show the category badge in topic lists. */
+function displayCategoryInList(site: Site, category: Category | undefined) {
+ if (category) {
+ if (category.has_children) {
+ return true;
+ }
+
+ const draftCategoryId = site.shared_drafts_category_id;
+ if (draftCategoryId && category.id === draftCategoryId) {
+ return true;
+ }
+
+ return false;
+ }
+
+ return true;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class TopicList extends RestModel {
+ static topicsFrom(
+ store: StoreService,
+ result: TopicListEnvelope | null | undefined,
+ opts?: { listKey?: "topics" | "shared_drafts" }
+ ): Topic[] | undefined;
+
+ static topicsFrom(
+ store: StoreService,
+ result: TopicListEnvelope | null | undefined,
+ opts: { listKey?: "topics" | "shared_drafts" } | undefined
+ ) {
+ if (!result) {
+ return;
+ }
+
+ opts = opts || {};
+ // eslint-disable-next-line prefer-const -- Preserve the original declaration in this types-only port.
+ let listKey = opts.listKey || "topics";
+
+ // Stitch together our side loaded data
+
+ const users = extractByKey(result.users, User);
+ const groups = extractByKey<
+ TopicListPrimaryGroup,
+ EmberObject & TopicListPrimaryGroup
+ >(result.primary_groups, EmberObject);
+
+ if (result.topic_list.categories) {
+ result.topic_list.categories.forEach((c) => {
+ Site.current().updateCategory(c);
+ });
+ }
+
+ const topics = result.topic_list[listKey]!.map((t) => {
+ t.posters.forEach((p) => {
+ p.user = users[p.user_id];
+ p.extraClasses = p.extras;
+ if (p.primary_group_id) {
+ p.primary_group = groups[p.primary_group_id];
+ if (p.primary_group) {
+ p.extraClasses = `${p.extraClasses || ""} group-${
+ p.primary_group.name
+ }`;
+ }
+ }
+ });
+
+ if (t.participants) {
+ t.participants.forEach((p) => (p.user = users[p.user_id]));
+ }
+
+ return store.createRecord("topic", t);
+ });
+
+ return applyValueTransformer("topic-list-topics-from", topics, {
+ store,
+ result,
+ opts,
+ });
+ }
+
+ static munge(json: RestPayload, store?: StoreService): RestPayload;
+ static munge(
+ json: RestPayload & TopicListEnvelope & Partial<TopicListFields>,
+ store: StoreService
+ ) {
+ json.inserted = json.inserted || [];
+ json.can_create_topic = json.topic_list.can_create_topic;
+ json.more_topics_url = json.topic_list.more_topics_url;
+ json.for_period = json.topic_list.for_period;
+ json.loaded = true;
+ json.per_page = json.topic_list.per_page;
+ json.topics = this.topicsFrom(store, json)!;
+
+ if (json.topic_list.shared_drafts) {
+ json.sharedDrafts = this.topicsFrom(store, json, {
+ listKey: "shared_drafts",
+ });
+ }
+
+ return json;
+ }
+
+ static find(
+ filter: string,
+ params: TopicListParams
+ ): globalThis.Promise<TopicList> {
+ deprecated(
+ `TopicList.find is deprecated. Use \`findFiltered("topicList")\` on the \`store\` service instead.`,
+ {
+ id: "discourse.topic-list-find",
+ since: "3.1.0.beta5",
+ }
+ );
+
+ // TODO(typescript-pending): remove this lookup assertion when getOwnerWithFallback publishes typed service lookups.
+ const store = getOwnerWithFallback(this).lookup("service:store");
+ return (store as StoreService).findFiltered("topicList", {
+ filter,
+ params,
+ });
+ }
+
+ /** Hide the category when it has no children. */
+ static hideUniformCategory(list: TopicList, category: Category | undefined) {
+ list.set("hideCategory", !displayCategoryInList(list.site, category));
+ }
+
+ @service declare session: SessionService;
+
+ @tracked loadingBefore: false | number = false;
+ @autoTrackedArray topics!: Topic[];
+
+ @computed("more_topics_url")
+ get canLoadMore() {
+ return !isEmpty(this.more_topics_url);
+ }
+
+ forEachNew(topics: Topic[], callback: (topic: Topic) => void) {
+ const topicIds = new Set();
+ this.topics.forEach((topic) => topicIds.add(topic.id));
+
+ topics.forEach((topic) => {
+ if (!topicIds.has(topic.id)) {
+ callback(topic);
+ }
+ });
+ }
+
+ updateSortParams(order: string | undefined, ascending: boolean) {
+ let params = { ...(this.params || {}) };
+
+ if (params.q) {
+ // search is unique, nothing else allowed with it
+ params = { q: params.q };
+ } else {
+ params.order = order || params.order;
+ params.ascending = ascending;
+ }
+
+ this.set("params", params);
+ }
+
+ updateNewListSubsetParam(subset: string) {
+ let params = { ...(this.params || {}) };
+
+ if (params.q) {
+ params = { q: params.q };
+ } else {
+ params.subset = subset;
+ }
+
+ this.set("params", params);
+ }
+
+ @action
+ loadMore(): globalThis.Promise<
+ { moreTopicsUrl: string | undefined; newTopics: Topic[] } | undefined
+ > {
+ if (this.loadingMore) {
+ return Promise.resolve();
+ }
+
+ let moreUrl = this.more_topics_url;
+ if (moreUrl) {
+ // eslint-disable-next-line prefer-const -- Preserve the original destructuring declaration in this types-only port.
+ let [url, params] = moreUrl.split("?");
+
+ // ensure we postfix with .json so username paths work
+ // correctly
+ if (!url!.match(/\.json$/)) {
+ url += ".json";
+ }
+
+ moreUrl = url;
+ if (params) {
+ moreUrl += "?" + params;
+ }
+
+ this.set("loadingMore", true);
+
+ // TODO(typescript-pending): ajax does not publish response types; remove the payload annotation when its response is generic.
+ return ajax({ url: moreUrl }).then(
+ async (result: TopicListEnvelope | undefined) => {
+ let topicsAdded = 0;
+
+ if (result) {
+ // the new topics loaded from the server
+ const newTopics = TopicList.topicsFrom(this.store, result)!;
+ await Topic.applyTransformations(newTopics);
+
+ this.forEachNew(newTopics, (t) => {
+ t.set("highlight", topicsAdded++ === 0);
+ this.topics.push(t);
+ });
+
+ this.setProperties({
+ loadingMore: false,
+ more_topics_url: result.topic_list.more_topics_url,
+ });
+
+ this.session.set("topicList", this);
+ return { moreTopicsUrl: this.more_topics_url, newTopics };
+ }
+ }
+ );
+ } else {
+ // Return a promise indicating no more results
+ return Promise.resolve();
+ }
+ }
+
+ /** Loads topics with these IDs before the current topics. */
+ async loadBefore(topic_ids: number[], storeInSession?: boolean) {
+ this.loadingBefore = topic_ids.length;
+
+ try {
+ const url = `/${this.filter}.json?topic_ids=${topic_ids.join(",")}`;
+
+ // TODO(typescript-pending): ajax does not publish response types; remove the assertion when its response is generic.
+ const result = (await ajax({
+ url,
+ data: this.params,
+ })) as TopicListEnvelope;
+
+ // refresh dupes
+ removeValuesFromArray(
+ this.topics,
+ this.topics.filter((topic) => topic_ids.includes(topic.id))
+ );
+
+ let i = 0;
+ this.forEachNew(TopicList.topicsFrom(this.store, result)!, (t) => {
+ // highlight the first of the new topics so we can get a visual feedback
+ t.set("highlight", true);
+ this.topics.splice(i, 0, t);
+ i++;
+ });
+
+ if (storeInSession) {
+ this.session.set("topicList", this);
+ }
+ } finally {
+ this.loadingBefore = false;
+ }
+ }
+}
diff --git a/frontend/discourse/app/models/topic.ts b/frontend/discourse/app/models/topic.ts
index e8d8fdf94a9..fa5e87648c8 100644
--- a/frontend/discourse/app/models/topic.ts
+++ b/frontend/discourse/app/models/topic.ts
@@ -184,7 +184,7 @@ export interface TopicFields {
op_liked?: boolean;
participant_count?: number | null;
participant_groups?: string[];
- participants?: object[];
+ participants?: TopicParticipant[];
pending_posts?: TopicPendingPost[];
pinned?: boolean;
pinned_at?: string | null;
@@ -193,7 +193,10 @@ export interface TopicFields {
pm_with_non_human_user?: boolean;
post_stream?: object;
posted?: boolean;
- posters?: object[];
+ posters?: TopicPoster[] & {
+ /** Present on legacy array wrappers; plain arrays do not supply this property. */
+ firstObject?: TopicPoster;
+ };
posts_count?: number;
published_page?: TopicPublishedPage;
queued_posts_count?: number;
@@ -245,14 +248,39 @@ export interface TopicFields {
topic_status_update?: TopicTimerValue;
}
-/** Poster fields read before their payload model is typed. */
-type TopicPoster = {
- user?: TopicBasicUser;
- primary_group?: object | null;
- extras?: string;
- user_id?: number;
- moreCount?: string;
-};
+/** A poster reference, with optional list-hydrated user and primary group. */
+export interface TopicPoster {
+ user_id: number;
+ extras: string | null;
+ description: string | null;
+ primary_group_id: number | null;
+ flair_group_id: number | null;
+ user?: User;
+ primary_group?: EmberObject & { id: number; name: string };
+ extraClasses?: string | null;
+}
+
+/** Participants receive users, but do not receive poster group or CSS hydration. */
+export type TopicParticipant = Pick<
+ TopicPoster,
+ | "user_id"
+ | "extras"
+ | "description"
+ | "primary_group_id"
+ | "flair_group_id"
+ | "user"
+>;
+
+/** featuredUsers mutates the posters array, inserting participants and a count marker. */
+export type TopicFeaturedUser =
+ | (TopicParticipant &
+ Partial<Pick<TopicPoster, "primary_group" | "extraClasses">>)
+ | {
+ moreCount: string;
+ user?: undefined;
+ user_id?: undefined;
+ extras?: undefined;
+ };
type TopicTagInput =
| string
@@ -829,38 +857,23 @@ export default class Topic extends RestModel {
@computed("posters.firstObject")
get creator(): TopicBasicUser | undefined {
- // TODO(typescript-pending): poster payloads and firstObject are untyped; remove when posters are typed.
- return (
- (
- this.posters as
- | (TopicPoster[] & { firstObject?: TopicPoster })
- | undefined
- )?.firstObject &&
- (
- this.posters as
- | (TopicPoster[] & { firstObject?: TopicPoster })
- | undefined
- )?.firstObject?.user
- );
+ return this.posters?.firstObject && this.posters?.firstObject?.user;
}
@computed("posters.[]")
get lastPoster(): TopicPoster | undefined {
- // TODO(typescript-pending): poster payloads and firstObject are untyped; remove when posters are typed.
if (this.posters && this.posters?.length > 0) {
- const latest = this.posters?.filter((p: TopicPoster) =>
+ const latest = this.posters?.filter((p) =>
p.extras?.includes("latest")
)[0];
- return (latest ||
- (this.posters as TopicPoster[] & { firstObject?: TopicPoster })
- ?.firstObject) as TopicPoster | undefined;
+ return latest || this.posters?.firstObject;
}
}
@computed("posters.[]", "participants.[]", "allowed_user_count")
- get featuredUsers(): object[] {
- // TODO(typescript-pending): posters and participants have no payload types; remove when posters are typed.
- const users = this.posters as TopicPoster[];
+ get featuredUsers(): TopicFeaturedUser[] {
+ // This aliases posters: participant insertion and the count marker mutate that same array.
+ const users = this.posters as TopicFeaturedUser[];
const maxUserCount = 5;
const posterCount = users.length;
@@ -877,11 +890,11 @@ export default class Topic extends RestModel {
}
}
- const poster_ids = (this.posters as TopicPoster[])
+ const poster_ids = this.posters
?.map((p) => p.user && p.user.id)
?.filter((id) => id);
- (this.participants as TopicPoster[])?.some((p) => {
- if (!poster_ids.includes(p.user_id)) {
+ this.participants?.some((p) => {
+ if (!poster_ids!.includes(p.user_id)) {
users.splice(users.length - pushOffset, 0, p);
if (users.length === maxUserCount) {
return true;
diff --git a/frontend/discourse/app/services/store.ts b/frontend/discourse/app/services/store.ts
index a76bd3c4bdb..c662104c671 100644
--- a/frontend/discourse/app/services/store.ts
+++ b/frontend/discourse/app/services/store.ts
@@ -11,6 +11,7 @@ import WeakValueMap from "discourse/lib/weak-value-map";
import type Category from "discourse/models/category";
import type Composer from "discourse/models/composer";
import type Group from "discourse/models/group";
+import type NavItem from "discourse/models/nav-item";
import type PendingPost from "discourse/models/pending-post";
import type { default as Post, PostCreateAttrs } from "discourse/models/post";
import type PostStream from "discourse/models/post-stream";
@@ -28,6 +29,7 @@ import type {
default as Topic,
TopicCreateAttrs,
} from "discourse/models/topic";
+import type TopicList from "discourse/models/topic-list";
import type { default as User, UserCreateAttrs } from "discourse/models/user";
import type UserDraft from "discourse/models/user-draft";
@@ -36,12 +38,14 @@ export interface ModelRegistry {
category: Category;
composer: Composer;
group: Group;
+ "nav-item": NavItem;
"pending-post": PendingPost;
post: Post;
"post-stream": PostStream;
"published-page": PublishedPage;
site: Site;
topic: Topic;
+ "topic-list": TopicList;
user: User;
"user-draft": UserDraft;
}
diff --git a/frontend/discourse/type-tests/models/category-test.ts b/frontend/discourse/type-tests/models/category-test.ts
index 338974e527b..e09f70e0b14 100644
--- a/frontend/discourse/type-tests/models/category-test.ts
+++ b/frontend/discourse/type-tests/models/category-test.ts
@@ -13,6 +13,10 @@ import Category, {
type CategoryUpload,
} from "discourse/models/category";
import type RestModel from "discourse/models/rest";
+import type {
+ default as Topic,
+ TopicCreateAttrs,
+} from "discourse/models/topic";
import type {
default as StoreService,
ModelFor,
@@ -117,7 +121,7 @@ interface ExpectedCategoryFields {
has_children?: boolean | null;
subcategory_count?: number | null;
subcategory_ids?: number[] | null;
- subcategory_list?: object[];
+ subcategory_list?: ExpectedCategoryListCategory[];
subcategory_list_style?: string | null;
sort_order?: string | null;
sort_ascending?: boolean | null;
@@ -162,7 +166,7 @@ interface ExpectedCategoryFields {
category_type_settings?: Record<string, unknown>;
category_type_site_settings?: Record<string, unknown>;
site_texts?: Record<string, string>;
- topics?: object[];
+ topics?: (TopicCreateAttrs<Topic> | Topic)[];
topics_day?: number;
topics_week?: number;
topics_month?: number;
@@ -174,6 +178,15 @@ interface ExpectedCategoryFields {
statTotal?: string;
}
+/** Category pages recursively include listable topic payloads before hydration. */
+interface ExpectedCategoryListCategory extends Omit<
+ ExpectedCategoryFields,
+ "subcategory_list"
+> {
+ type_test_plugin_flag?: boolean;
+ subcategory_list?: ExpectedCategoryListCategory[];
+}
+
declare module "discourse/models/category" {
interface CategoryFields {
type_test_plugin_flag?: boolean;
diff --git a/frontend/discourse/type-tests/models/discovery-test.ts b/frontend/discourse/type-tests/models/discovery-test.ts
new file mode 100644
index 00000000000..dae02db2c02
--- /dev/null
+++ b/frontend/discourse/type-tests/models/discovery-test.ts
@@ -0,0 +1,379 @@
+import type EmberObject from "@ember/object";
+import type RouterService from "@ember/routing/router-service";
+import type { TrustedHTML } from "@ember/template";
+import { expectTypeOf } from "expect-type";
+import type LegacyArrayLikeObject from "discourse/lib/legacy-array-like-object";
+import type { withPluginApi } from "discourse/lib/plugin-api";
+import type Category from "discourse/models/category";
+import CategoryList from "discourse/models/category-list";
+import NavItem, {
+ addNavItem,
+ clearNavItems,
+ customNavItemHref,
+ ExtraNavItem,
+ extraNavItemProperties,
+ type NavigationBarItem,
+ type NavItemOptions,
+} from "discourse/models/nav-item";
+import type RestModel from "discourse/models/rest";
+import type {
+ default as Topic,
+ TopicFeaturedUser,
+ TopicParticipant,
+ TopicPoster,
+} from "discourse/models/topic";
+import TopicList, { type TopicListEnvelope } from "discourse/models/topic-list";
+import type User from "discourse/models/user";
+import type {
+ default as StoreService,
+ ModelFor,
+} from "discourse/services/store";
+
+declare const store: StoreService;
+declare const list: TopicList;
+declare const topic: Topic;
+declare const category: Category;
+declare const navItem: NavItem;
+declare const extra: ExtraNavItem;
+declare const categoryList: CategoryList;
+declare const html: TrustedHTML;
+declare const user: User;
+declare const options: NavItemOptions;
+declare const api: Parameters<Parameters<typeof withPluginApi>[0]>[0];
+
+/* Store registration: every spelling callers use resolves to the class. */
+
+expectTypeOf<ModelFor<"topic-list">>().toEqualTypeOf<TopicList>();
+expectTypeOf<ModelFor<"topicList">>().toEqualTypeOf<TopicList>();
+expectTypeOf<ModelFor<"nav-item">>().toEqualTypeOf<NavItem>();
+expectTypeOf(
+ store.findFiltered("topicList", { filter: "latest", params: {} })
+).resolves.toEqualTypeOf<TopicList>();
+expectTypeOf(
+ store.createRecord("nav-item", { name: "latest", hasIcon: false })
+).toEqualTypeOf<NavItem>();
+
+/* TopicList: hydrated state. */
+
+expectTypeOf(list).toExtend<RestModel>();
+expectTypeOf(list).not.toBeAny();
+expectTypeOf(list.topics).toEqualTypeOf<Topic[]>();
+expectTypeOf(list.sharedDrafts).toEqualTypeOf<Topic[] | undefined>();
+// Holds the number of topics being reloaded while a reload runs.
+expectTypeOf(list.loadingBefore).toEqualTypeOf<false | number>();
+expectTypeOf(list.canLoadMore).toEqualTypeOf<boolean>();
+// Omitted when there is no next page.
+expectTypeOf(list.more_topics_url).toEqualTypeOf<string | undefined>();
+expectTypeOf(list.for_period).toEqualTypeOf<string | undefined>();
+expectTypeOf(list.per_page).toEqualTypeOf<number>();
+expectTypeOf(list.can_create_topic).toEqualTypeOf<boolean>();
+expectTypeOf(list.filter).toEqualTypeOf<string>();
+expectTypeOf(list.loaded).toEqualTypeOf<boolean>();
+expectTypeOf(list.params).not.toBeAny();
+list.loadingMore = true;
+list.hideCategory = false;
+list.emptyState = { title: "Nothing here", body: "Come back later" };
+list.emptyState = { title: "Nothing here", body: html };
+
+/* TopicList: the raw envelope stays available. */
+
+expectTypeOf(list.topic_list.filter_new_topic_ids).toEqualTypeOf<
+ number[] | undefined
+>();
+expectTypeOf(list.topic_list.top_tags).toEqualTypeOf<
+ { id: number; name: string; slug: string }[] | undefined
+>();
+expectTypeOf(list.topic_list.filter_option_info).not.toBeAny();
+expectTypeOf<
+ NonNullable<TopicList["topic_list"]["tags"]>[number]["description"]
+>().toEqualTypeOf<string | null>();
+expectTypeOf(list.users).not.toBeAny();
+expectTypeOf(list.primary_groups).toEqualTypeOf<
+ { id: number; name: string }[] | undefined
+>();
+
+/* TopicList: methods. */
+
+expectTypeOf(list.loadMore()).resolves.toEqualTypeOf<
+ { moreTopicsUrl: string | undefined; newTopics: Topic[] } | undefined
+>();
+expectTypeOf(list.loadBefore([1, 2], true)).resolves.toEqualTypeOf<void>();
+list.loadBefore([1]);
+list.updateSortParams("posts", true);
+list.updateSortParams(undefined, false);
+list.updateNewListSubsetParam("topics");
+list.forEachNew([topic], (t) => expectTypeOf(t).toEqualTypeOf<Topic>());
+
+/* TopicList: statics. */
+
+expectTypeOf(TopicList.topicsFrom(store, list)).toEqualTypeOf<
+ Topic[] | undefined
+>();
+TopicList.topicsFrom(store, list, { listKey: "shared_drafts" });
+TopicList.hideUniformCategory(list, category);
+TopicList.hideUniformCategory(list, undefined);
+expectTypeOf(TopicList.find("latest", {})).resolves.toEqualTypeOf<TopicList>();
+
+/* Topic posters and participants are hydrated by the list. */
+
+type Poster = NonNullable<Topic["posters"]>[number];
+expectTypeOf<Poster["user_id"]>().toEqualTypeOf<number>();
+expectTypeOf<Poster["extras"]>().toEqualTypeOf<string | null>();
+expectTypeOf<Poster["description"]>().toEqualTypeOf<string | null>();
+expectTypeOf<Poster["primary_group_id"]>().toEqualTypeOf<number | null>();
+expectTypeOf<Poster["user"]>().toEqualTypeOf<User | undefined>();
+expectTypeOf<
+ NonNullable<Poster["primary_group"]>["name"]
+>().toEqualTypeOf<string>();
+type Participant = NonNullable<Topic["participants"]>[number];
+expectTypeOf<Participant["user"]>().toEqualTypeOf<User | undefined>();
+expectTypeOf(topic.lastPoster?.extras).toEqualTypeOf<
+ string | null | undefined
+>();
+expectTypeOf(topic.featuredUsers).not.toBeAny();
+
+/* NavItem. */
+
+expectTypeOf(navItem).toExtend<EmberObject>();
+expectTypeOf(
+ NavItem.fromText("latest", { category })
+).toEqualTypeOf<NavItem | null>();
+NavItem.fromText("latest");
+expectTypeOf(
+ NavItem.buildList(category, { noSubcategories: true })
+).toEqualTypeOf<NavItem[]>();
+NavItem.buildList(undefined);
+expectTypeOf(
+ NavItem.pathFor("latest", { category, noSubcategories: true })
+).toEqualTypeOf<string>();
+NavItem.pathFor("latest", { tag: { id: 1, slug: "support" } });
+expectTypeOf(navItem.name).toEqualTypeOf<string>();
+expectTypeOf(navItem.filterType).toEqualTypeOf<string>();
+navItem.filterType = "new";
+expectTypeOf(navItem.title).toEqualTypeOf<string>();
+navItem.title = "Custom title";
+expectTypeOf(navItem.displayName).toEqualTypeOf<string>();
+navItem.displayName = "Custom name";
+expectTypeOf(navItem.href).toEqualTypeOf<string>();
+expectTypeOf(navItem.filterMode).toEqualTypeOf<string>();
+// Tracking has no count for some filters.
+expectTypeOf(navItem.count).toEqualTypeOf<number | undefined>();
+expectTypeOf(navItem.category).toEqualTypeOf<Category | undefined>();
+expectTypeOf(navItem.noSubcategories).toEqualTypeOf<boolean | undefined>();
+// The current-user service is registered as null for anonymous visitors.
+expectTypeOf(navItem.currentUser).toEqualTypeOf<User | null>();
+
+/* ExtraNavItem: plugins write href and count directly. */
+
+expectTypeOf(extra).toExtend<NavItem>();
+expectTypeOf(
+ ExtraNavItem.create({ name: "votes" })
+).toEqualTypeOf<ExtraNavItem>();
+extra.href = "/latest?order=votes";
+extra.count = 2;
+expectTypeOf(extra.count).toEqualTypeOf<number>();
+extra.customFilter = (filterCategory) => !filterCategory;
+extra.customFilter = null;
+
+/* Navigation registration APIs. */
+
+addNavItem({
+ name: "votes",
+ before: "top",
+ customFilter: (filterCategory, args) => !!filterCategory || !!args,
+ customHref: (filterCategory) => (filterCategory ? "/c/votes" : "/votes"),
+ forceActive: () => false,
+});
+addNavItem({ name: "subscribe", displayName: "Subscribe", href: "/s" });
+extraNavItemProperties((filterType) => ({ hasIcon: filterType === "new" }));
+customNavItemHref((item) => {
+ expectTypeOf(item).toEqualTypeOf<NavItem>();
+ return item.name === "latest" ? "/custom" : undefined;
+});
+clearNavItems();
+
+/* CategoryList. */
+
+expectTypeOf(categoryList).toExtend<LegacyArrayLikeObject<Category>>();
+expectTypeOf(categoryList.content).toEqualTypeOf<Category[]>();
+expectTypeOf(
+ CategoryList.create({
+ store,
+ categories: [category],
+ parentCategory: null,
+ can_create_category: true,
+ can_create_topic: true,
+ })
+).toEqualTypeOf<CategoryList>();
+expectTypeOf(CategoryList.create()).toEqualTypeOf<CategoryList>();
+// @ts-expect-error categories hold Category records
+CategoryList.create({ categories: ["x"] });
+expectTypeOf(
+ CategoryList.categoriesFrom(store, {}, category)
+).toEqualTypeOf<CategoryList>();
+CategoryList.categoriesFrom(store, undefined);
+expectTypeOf(CategoryList.list(store)).resolves.toEqualTypeOf<CategoryList>();
+CategoryList.list(store, category);
+expectTypeOf(categoryList.can_create_category).toEqualTypeOf<
+ boolean | undefined
+>();
+expectTypeOf(categoryList.page).toEqualTypeOf<number>();
+expectTypeOf(categoryList.isLoading).toEqualTypeOf<boolean>();
+expectTypeOf(categoryList.fetchedLastPage).toEqualTypeOf<boolean>();
+expectTypeOf(categoryList.parentCategory).toEqualTypeOf<
+ Category | null | undefined
+>();
+// Only the combined categories-and-topics page supplies topics.
+expectTypeOf(categoryList.topics).toEqualTypeOf<Topic[] | undefined>();
+expectTypeOf(categoryList.categories).toEqualTypeOf<Category[]>();
+expectTypeOf(categoryList.loadMore()).resolves.toEqualTypeOf<void>();
+
+/* Subclasses keep their own factories. */
+
+expectTypeOf<typeof TopicList>().toExtend<typeof RestModel>();
+expectTypeOf<typeof CategoryList>().toExtend<
+ typeof LegacyArrayLikeObject<Category>
+>();
+expectTypeOf<typeof ExtraNavItem>().toExtend<typeof NavItem>();
+
+class SpecializedCategoryList extends CategoryList {
+ declare clientLabel: string;
+}
+class SpecializedExtraNavItem extends ExtraNavItem {
+ declare clientLabel: string;
+}
+class SpecializedTopicList extends TopicList {
+ declare clientLabel: string;
+}
+expectTypeOf(
+ SpecializedCategoryList.create({ categories: [category], clientLabel: "x" })
+).toEqualTypeOf<SpecializedCategoryList>();
+expectTypeOf(
+ SpecializedExtraNavItem.create({ name: "x", clientLabel: "x" })
+).toEqualTypeOf<SpecializedExtraNavItem>();
+expectTypeOf(
+ SpecializedTopicList.create()
+).toEqualTypeOf<SpecializedTopicList>();
+
+/* Envelopes and hydrated references. */
+
+// Empty lists omit side-loaded roots. Shared drafts use the same topic item contract.
+const empty: TopicListEnvelope = {
+ topic_list: {
+ topics: [],
+ filter: "latest",
+ can_create_topic: false,
+ per_page: 30,
+ },
+};
+expectTypeOf(empty.users).not.toBeAny();
+expectTypeOf<TopicListEnvelope["flair_groups"]>().toEqualTypeOf<
+ | {
+ id: number;
+ name: string;
+ flair_url: string | null;
+ flair_color: string | null;
+ flair_bg_color: string | null;
+ }[]
+ | undefined
+>();
+expectTypeOf<
+ NonNullable<TopicListEnvelope["users"]>[number]["id"]
+>().toEqualTypeOf<number>();
+
+const participant: TopicParticipant = {
+ user_id: 1,
+ extras: null,
+ description: null,
+ primary_group_id: null,
+ flair_group_id: null,
+};
+const poster: TopicPoster = { ...participant, user };
+const featured: TopicFeaturedUser[] = [
+ poster,
+ participant,
+ { moreCount: "+2" },
+];
+expectTypeOf(featured).not.toBeAny();
+expectTypeOf<TopicParticipant>().not.toHaveProperty("primary_group");
+expectTypeOf<TopicPoster["primary_group"]>().toEqualTypeOf<
+ (EmberObject & { id: number; name: string }) | undefined
+>();
+
+/* Navigation callbacks. */
+
+// Existing callbacks use truthiness and may omit a custom URL.
+addNavItem({
+ name: "x",
+ customFilter: () => user,
+ customHref: () => undefined,
+});
+ExtraNavItem.create({
+ name: "x",
+ init(item, filterCategory, args) {
+ expectTypeOf(item).toEqualTypeOf<ExtraNavItem>();
+ expectTypeOf(filterCategory).toEqualTypeOf<Category | null | undefined>();
+ expectTypeOf(args).toEqualTypeOf<NavItemOptions>();
+ },
+});
+extraNavItemProperties(function (filterType, opts) {
+ expectTypeOf(this).toEqualTypeOf<typeof NavItem>();
+ expectTypeOf(filterType).toEqualTypeOf<string>();
+ expectTypeOf(opts).toEqualTypeOf<NavItemOptions>();
+ return { hasIcon: true };
+});
+customNavItemHref(function (item) {
+ expectTypeOf(this).toEqualTypeOf<NavItem>();
+ expectTypeOf(item).toEqualTypeOf<NavItem>();
+ return undefined;
+});
+const descriptor: NavigationBarItem = {
+ name: "x",
+ customFilter(_category, args, router) {
+ expectTypeOf(args).toEqualTypeOf<NavItemOptions>();
+ expectTypeOf(router).toEqualTypeOf<RouterService>();
+ return user;
+ },
+ init(item, _category, args, router) {
+ expectTypeOf(item).toEqualTypeOf<ExtraNavItem>();
+ expectTypeOf(args).toEqualTypeOf<NavItemOptions>();
+ expectTypeOf(router).toEqualTypeOf<RouterService>();
+ },
+};
+api.addNavigationBarItem(descriptor);
+NavItem.buildList(category, options);
+
+/* No any leaks. */
+
+// Factory-returning services must not leak any through the navigation options.
+expectTypeOf(options.siteSettings).not.toBeAny();
+expectTypeOf(options.siteSettings?.top_menu).toEqualTypeOf<
+ string | undefined
+>();
+
+type AnyKeys<T> = {
+ [K in keyof T]-?: 0 extends 1 & T[K] ? K : never;
+}[keyof T];
+type AnyReturnKeys<T> = {
+ [K in keyof T]-?: T[K] extends (...args: never) => infer R
+ ? 0 extends 1 & R
+ ? K
+ : never
+ : never;
+}[keyof T];
+type OwnAnyKeys<T, Base> = Exclude<
+ AnyKeys<T> | AnyReturnKeys<T>,
+ AnyKeys<Base> | AnyReturnKeys<Base>
+>;
+expectTypeOf<OwnAnyKeys<TopicList, EmberObject>>().toEqualTypeOf<never>();
+expectTypeOf<OwnAnyKeys<NavItem, EmberObject>>().toEqualTypeOf<never>();
+expectTypeOf<OwnAnyKeys<ExtraNavItem, EmberObject>>().toEqualTypeOf<never>();
+expectTypeOf<OwnAnyKeys<CategoryList, EmberObject>>().toEqualTypeOf<never>();
+
+/* ID-only parents. */
+
+// Existing JS fixtures and factories use ID-only parent contexts.
+CategoryList.categoriesFrom(store, {}, { id: 1 });
+CategoryList.list(store, { id: 1 });
+CategoryList.listForParent(store, { id: 1 });
+CategoryList.create({ parentCategory: { id: 1 } });
diff --git a/frontend/discourse/type-tests/models/topic-test.ts b/frontend/discourse/type-tests/models/topic-test.ts
index dd7e04a8f98..6e3deaf5ec2 100644
--- a/frontend/discourse/type-tests/models/topic-test.ts
+++ b/frontend/discourse/type-tests/models/topic-test.ts
@@ -106,6 +106,33 @@ interface ExpectedBasicUser {
avatar_template: string;
}
+/** List hydration adds a User and a plain EmberObject primary group. */
+interface ExpectedPoster {
+ user_id: number;
+ extras: string | null;
+ description: string | null;
+ primary_group_id: number | null;
+ flair_group_id: number | null;
+ user?: User;
+ primary_group?: EmberObject & { id: number; name: string };
+ extraClasses?: string | null;
+}
+
+type ExpectedParticipant = Omit<
+ ExpectedPoster,
+ "primary_group" | "extraClasses"
+>;
+
+type ExpectedFeaturedUser =
+ | (ExpectedParticipant &
+ Partial<Pick<ExpectedPoster, "primary_group" | "extraClasses">>)
+ | {
+ moreCount: string;
+ user?: undefined;
+ user_id?: undefined;
+ extras?: undefined;
+ };
+
type ExpectedTimerValue = ExpectedTimer | EmberObject | null;
expectTypeOf<TopicTag>().toEqualTypeOf<ExpectedTag>();
@@ -186,7 +213,7 @@ interface ExpectedTopicFields {
op_liked?: boolean;
participant_count?: number | null;
participant_groups?: string[];
- participants?: object[];
+ participants?: ExpectedParticipant[];
pending_posts?: ExpectedPendingPost[];
pinned?: boolean;
pinned_at?: string | null;
@@ -195,7 +222,7 @@ interface ExpectedTopicFields {
pm_with_non_human_user?: boolean;
post_stream?: object;
posted?: boolean;
- posters?: object[];
+ posters?: ExpectedPoster[] & { firstObject?: ExpectedPoster };
posts_count?: number;
published_page?: ExpectedPublishedPage;
queued_posts_count?: number;
@@ -351,8 +378,8 @@ expectTypeOf(topic.summaryUrl).toEqualTypeOf<string>();
expectTypeOf(topic.lastPosterUrl).toEqualTypeOf<string>();
expectTypeOf(topic.urlForPostNumber(3)).toEqualTypeOf<string>();
-// Poster entries stay untyped until their payload is, but never `any`.
-expectTypeOf(topic.featuredUsers).toEqualTypeOf<object[]>();
+// The list supplies hydrated references, while featuredUsers can append a count marker.
+expectTypeOf(topic.featuredUsers).toEqualTypeOf<ExpectedFeaturedUser[]>();
expectTypeOf(topic.creator).not.toBeAny();
expectTypeOf(topic.lastPoster).not.toBeAny();
expectTypeOf(topic.lastPosterUser).not.toBeAny();