A platform for community discussion. Free, open, simple.
DEV: Convert `Category` to TypeScript (#45054)
Sérgio Saquetimc5947e110e8a
diff --git a/frontend/discourse/app/models/bookmark.js b/frontend/discourse/app/models/bookmark.jsindex 977f11ec7b1..ce862637720 100644--- a/frontend/discourse/app/models/bookmark.js+++ b/frontend/discourse/app/models/bookmark.js@@ -20,7 +20,7 @@ import { applyModelTransformations } from "discourse/lib/model-transformers";import Topic from "discourse/models/topic";import User from "discourse/models/user";import { i18n } from "discourse-i18n";-import Category from "./category.js";+import Category from "./category.ts";export const AUTO_DELETE_PREFERENCES = {NEVER: 0,diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.jsdeleted file mode 100644index c83a8678ea2..00000000000--- a/frontend/discourse/app/models/category.js+++ /dev/null@@ -1,1010 +0,0 @@-import { tracked } from "@glimmer/tracking";-import { warn } from "@ember/debug";-import { computed, get } from "@ember/object";-import { dependentKeyCompat } from "@ember/object/compat";-import { trackedObject } from "@ember/reactive/collections";-import { service } from "@ember/service";-import { compare } from "@ember/utils";-import { ajax } from "discourse/lib/ajax";-import {- addUniqueValueToArray,- removeValueFromArray,-} from "discourse/lib/array-tools";-import { AUTO_GROUPS } from "discourse/lib/constants";-import { getOwnerWithFallback } from "discourse/lib/get-owner";-import getURL from "discourse/lib/get-url";-import {- extraSavePropertiesFor,- registerModelSaveProperty,-} from "discourse/lib/model-extensions";-import { MultiCache } from "discourse/lib/multi-cache";-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 PermissionType from "discourse/models/permission-type";-import RestModel from "discourse/models/rest";-import Site from "discourse/models/site";-import Topic from "./topic.js";--const CATEGORY_ASYNC_SEARCH_CACHE = {};-const CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE = {};-const HTTP_NOT_FOUND = 404;--let _uncategorized;--/**- * @internal- * Registers a property to include when saving a category.- *- * Intended to be used only in the plugin API.- *- * @param {string} propertyKey - The key of the property to include.- */-export function _addCategoryPropertyForSave(propertyKey) {- registerModelSaveProperty("category", propertyKey);-}--export default class Category extends RestModel {- // Sort subcategories directly under parents- static sortCategories(categories) {- const children = new Map();-- categories.forEach((category) => {- const parentId = parseInt(category.parent_category_id, 10) || -1;- const group = children.get(parentId) || [];- group.push(category);-- children.set(parentId, group);- });-- const reduce = (values) =>- values.flatMap((c) => [c, reduce(children.get(c.id) || [])]).flat();-- return reduce(children.get(-1) || []);- }-- static isUncategorized(categoryId) {- return categoryId === Site.currentProp("uncategorized_category_id");- }-- static slugEncoded() {- let siteSettings = getOwnerWithFallback(this).lookup(- "service:site-settings"- );- return siteSettings.slug_generation_method === "encoded";- }-- static findUncategorized() {- _uncategorized =- _uncategorized ||- Category.list().find(- (category) =>- category.id === Site.currentProp("uncategorized_category_id")- );- return _uncategorized;- }-- static slugFor(category, separator = "/", depth = 3) {- if (!category) {- return "";- }-- const parentCategory = get(category, "parentCategory");- let result = "";-- if (parentCategory && depth > 1) {- result =- Category.slugFor(parentCategory, separator, depth - 1) + separator;- }-- const id = get(category, "id"),- slug = get(category, "slug");-- return !slug || slug.trim().length === 0- ? `${result}${id}-category`- : result + slug;- }-- static list() {- return Site.currentProp("categoriesList");- }-- static listByActivity() {- return Site.currentProp("sortedCategories");- }-- static _idMap() {- return Site.currentProp("categoriesById");- }-- static findSingleBySlug(slug) {- if (!this.slugEncoded()) {- return Category.list().find((c) => Category.slugFor(c) === slug);- } else {- return Category.list().find(- (c) => Category.slugFor(c) === encodeURI(slug)- );- }- }-- static findById(id) {- if (!id) {- return;- }-- if (typeof id === "string") {- id = parseInt(id, 10);- }-- return Category._idMap().get(id);- }-- static findByIds(ids = []) {- return ids.map((id) => Category.findById(id)).filter(Boolean);- }-- static hasAsyncFoundAll(ids) {- const loadedCategoryIds = Site.current().loadedCategoryIds || new Set();- return ids.every((id) => loadedCategoryIds.has(id));- }-- static async asyncFindByIds(ids = []) {- ids = ids.map((x) => parseInt(x, 10));- const site = Site.current();-- if (!site.lazy_load_categories || this.hasAsyncFoundAll(ids)) {- return this.findByIds(ids);- }-- const result = await categoryMultiCache.fetch(ids);- if (categoryMultiCache.hadTooManyCalls()) {- warn(- "Multiple calls to Category.asyncFindByIds within a second. Could they be combined?",- {- id: "discourse.category.multiple-async-find-by-ids-calls",- }- );- }-- const loadedCategoryIds = site.loadedCategoryIds || new Set();- for (const id of ids) {- const category = result.get(id);- if (category) {- site.updateCategory(category);- } else {- site.removeCategory(id);- }- loadedCategoryIds.add(id);- }- site.set("loadedCategoryIds", loadedCategoryIds);-- return this.findByIds(ids);- }-- static async asyncFindById(id) {- return (await Category.asyncFindByIds([id]))[0];- }-- static findBySlugAndParent(slug, parentCategory) {- if (this.slugEncoded()) {- slug = encodeURI(slug);- }- return Category.list().find((category) => {- return (- category.slug === slug &&- (category.parentCategory || null) === parentCategory- );- });- }-- static findBySlugPath(slugPath) {- let category = null;-- for (const slug of slugPath) {- category = this.findBySlugAndParent(slug, category);-- if (!category) {- return null;- }- }-- return category;- }-- static async asyncFindBySlugPath(slugPath, opts = {}) {- const data = { slug_path: slugPath };- if (opts.includePermissions) {- data.include_permissions = true;- }-- const result = await ajax("/categories/find", { data });-- const categories = result["categories"].map((category) => {- category = Site.current().updateCategory(category);- if (opts.includePermissions) {- category.setupGroupsAndPermissions();- }- return category;- });-- return categories[categories.length - 1];- }-- static async asyncFindBySlugPathWithID(slugPathWithID) {- const result = await ajax("/categories/find", {- data: { slug_path_with_id: slugPathWithID },- });-- const categories = result["categories"].map((category) =>- Site.current().updateCategory(category)- );-- return categories[categories.length - 1];- }-- static findBySlugPathWithID(slugPathWithID) {- let parts = slugPathWithID.split("/").filter(Boolean);- // slugs found by star/glob pathing in ember do not automatically url decode - ensure that these are decoded- if (this.slugEncoded()) {- parts = parts.map((urlPart) => decodeURI(urlPart));- }- let category;-- if (parts.length > 0 && parts[parts.length - 1].match(/^\d+$/)) {- const id = parseInt(parts.pop(), 10);-- category = Category.findById(id);- } else {- category = Category.findBySlugPath(parts);-- if (- !category &&- parts.length > 0 &&- parts[parts.length - 1].match(/^\d+-category/)- ) {- const id = parseInt(parts.pop(), 10);-- category = Category.findById(id);- }- }-- return category;- }-- static findBySlug(slug, parentSlug) {- const categories = Category.list();- let category;-- if (parentSlug) {- const parentCategory = Category.findSingleBySlug(parentSlug);- if (parentCategory) {- if (slug === "none") {- return parentCategory;- }-- category = categories.find((item) => {- return (- item &&- item.get("parentCategory") === parentCategory &&- ((!this.slugEncoded() &&- Category.slugFor(item) === parentSlug + "/" + slug) ||- (this.slugEncoded() &&- Category.slugFor(item) ===- encodeURI(parentSlug) + "/" + encodeURI(slug)))- );- });- }- } else {- category = Category.findSingleBySlug(slug);-- // If we have a parent category, we need to enforce it- if (category && category.get("parentCategory")) {- return;- }- }-- // In case the slug didn't work, try to find it by id instead.- if (!category) {- category = categories.find((c) => c.id === parseInt(slug, 10));- }-- return category;- }-- static fetchVisibleGroups(id) {- return ajax(`/c/${id}/visible_groups.json`);- }-- static reloadById(id) {- return ajax(`/c/${id}/show.json`);- }-- static reloadBySlugPath(slugPath) {- return ajax(`/c/${slugPath}/find_by_slug.json`);- }-- static reloadCategoryWithPermissions(params, store, site) {- return this.reloadBySlugPath(params.slug).then((result) =>- this._includePermissions(result.category, store, site)- );- }-- static _includePermissions(category, store, site) {- const model = site.updateCategory(category);- model.setupGroupsAndPermissions();- model.setupCategoryTypes();- return model;- }-- static search(term, opts) {- let limit = 5;- let parentCategoryId;-- if (opts) {- if (opts.limit === 0) {- return [];- } else if (opts.limit) {- limit = opts.limit;- }- if (opts.parentCategoryId) {- parentCategoryId = opts.parentCategoryId;- }- }-- const emptyTerm = term === "";- let slugTerm = term;-- const normalize = (str) => removeAccents(str.toLowerCase());-- if (!emptyTerm) {- term = normalize(term);- slugTerm = term;- term = term.replace(/-/g, " ");- }-- const categories = Category.listByActivity();- const length = categories.length;- let i;- let data = [];-- const done = () => {- return data.length === limit;- };-- const validCategoryParent = (category) => {- return (- !parentCategoryId ||- category.get("parent_category_id") === parentCategoryId- );- };-- for (i = 0; i < length && !done(); i++) {- const category = categories[i];- if (- ((emptyTerm && !category.get("parent_category_id")) ||- (!emptyTerm &&- (normalize(category.get("name")).startsWith(term) ||- normalize(category.get("slug")).startsWith(slugTerm)))) &&- validCategoryParent(category)- ) {- data.push(category);- }- }-- if (!done()) {- for (i = 0; i < length && !done(); i++) {- const category = categories[i];-- if (- ((!emptyTerm && normalize(category.get("name")).indexOf(term) > 0) ||- normalize(category.get("slug")).indexOf(slugTerm) > 0) &&- validCategoryParent(category)- ) {- if (!data.includes(category)) {- data.push(category);- }- }- }- }-- return data.sort((a, b) => compare(a?.read_restricted, b?.read_restricted));- }-- static async asyncHierarchicalSearch(term, opts) {- opts ||= {};-- const data = {- term,- only: opts.only,- except: opts.except,- page: opts.page,- };-- const cacheKey = JSON.stringify(data);- CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[cacheKey] ||= await ajax(- "/categories/hierarchical_search",- {- method: "GET",- data,- }- );- const result = CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[cacheKey];-- return result["categories"].map((category) =>- Site.current().updateCategory(category)- );- }-- static clearAsyncHierarchicalSearchCache() {- Object.keys(CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE).forEach((key) => {- delete CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[key];- });- }-- static async asyncSearch(term, opts) {- opts ||= {};-- const data = {- term,- parent_category_id: opts.parentCategoryId,- include_uncategorized: opts.includeUncategorized,- select_category_ids: opts.selectCategoryIds,- reject_category_ids: opts.rejectCategoryIds,- include_subcategories: opts.includeSubcategories,- include_ancestors: opts.includeAncestors,- prioritized_category_id: opts.prioritizedCategoryId,- limit: opts.limit,- page: opts.page,- };-- const result = (CATEGORY_ASYNC_SEARCH_CACHE[JSON.stringify(data)] ||=- await ajax("/categories/search", { method: "POST", data }));-- if (opts.includeAncestors) {- return {- ancestors: result["ancestors"].map((category) =>- Site.current().updateCategory(category)- ),- categories: result["categories"].map((category) =>- Site.current().updateCategory(category)- ),- categoriesCount: result["categories_count"],- };- } else {- return result["categories"].map((category) =>- Site.current().updateCategory(category)- );- }- }-- @service currentUser;-- @tracked color;- @tracked emoji;- @tracked icon;- @tracked localizations = this.category_localizations;- @tracked minimum_required_tags;- @tracked styleType = this.style_type;- @tracked allowed_tags;- @tracked categoryTypes;- @autoTrackedArray available_groups;- @autoTrackedArray permissions;- @autoTrackedArray required_tag_groups;-- init() {- super.init(...arguments);- this.setupGroupsAndPermissions();- this.setupCategoryTypes();- }-- @computed("parent_category_id", "site.categories.[]")- get parentCategory() {- if (this.parent_category_id) {- return Category.findById(this.parent_category_id);- }- }-- set parentCategory(newParentCategory) {- this.set("parent_category_id", newParentCategory?.id);- }-- @dependentKeyCompat- get availableGroups() {- return this.available_groups;- }-- get descriptionText() {- return applyValueTransformer(- "category-description-text",- this.get("description_text"),- {- category: this,- }- );- }-- get displayName() {- return applyValueTransformer("category-display-name", this.get("name"), {- category: this,- });- }-- get textColor() {- return applyValueTransformer(- "category-text-color",- this.get("text_color"),- {- category: this,- }- );- }-- get subcategories() {- return applyValueTransformer(- "category-subcategories",- this.site.categoriesByParentId.get(this.id) || [],- { category: this }- );- }-- get unloadedSubcategoryCount() {- return this.subcategory_count - this.subcategories.length;- }-- @computed("subcategory_list")- get serializedSubcategories() {- return this.subcategory_list?.map((c) => {- const subcategory = Category.create({- ...c,- topics: c.topics?.map((t) => Topic.create(t)),- });- return subcategory;- });- }-- @dependentKeyCompat- get minimumRequiredTags() {- if (this.required_tag_groups?.length > 0) {- // it should require the max between the bare minimum set in the category and the sum of the min_count of the- // required_tag_groups- return Math.max(- this.required_tag_groups.reduce((sum, rtg) => sum + rtg.min_count, 0),- this.minimum_required_tags || 0- );- } else {- return this.minimum_required_tags > 0 ? this.minimum_required_tags : null;- }- }-- @computed- get availablePermissions() {- return [- PermissionType.create({ id: PermissionType.FULL }),- PermissionType.create({ id: PermissionType.CREATE_POST }),- PermissionType.create({ id: PermissionType.READONLY }),- ];- }-- @computed("id")- get searchContext() {- return {- type: "category",- id: this.id,- /** @type Category */- category: this,- };- }-- @computed("parentCategory.ancestors")- get ancestors() {- return [...(this.parentCategory?.ancestors || []), this];- }-- @computed("parentCategory", "parentCategory.predecessors")- get predecessors() {- if (this.parentCategory) {- return [- this.parentCategory,- ...(this.parentCategory?.predecessors || []),- ];- } else {- return [];- }- }-- get descendants() {- const descendants = [this];- for (let i = 0; i < descendants.length; i++) {- if (descendants[i].subcategories) {- descendants.push(...descendants[i].subcategories);- }- }- return descendants;- }-- @computed("parentCategory.level")- get level() {- if (!this.parentCategory?.level) {- return this.parentCategory?.level === 0 ? 1 : 0;- } else {- return this.parentCategory?.level + 1;- }- }-- @computed("has_children", "subcategories")- get isParent() {- return (- this.has_children || (this.subcategories && this.subcategories.length > 0)- );- }-- @computed("subcategories")- get isGrandParent() {- return (- this.subcategories &&- this.subcategories.some(- (cat) => cat.subcategories && cat.subcategories.length > 0- )- );- }-- @computed("notification_level")- get isMuted() {- return this.notification_level === NotificationLevels.MUTED;- }-- @computed("isMuted", "subcategories")- get isHidden() {- if (!this.isMuted) {- return false;- } else if (!this.subcategories) {- return true;- }-- if (this.subcategories.some((cat) => !cat.isHidden)) {- return false;- }-- return true;- }-- @computed("isMuted", "subcategories")- get hasMuted() {- if (this.isMuted) {- return true;- } else if (!this.subcategories) {- return false;- }-- if (this.subcategories.some((cat) => cat.hasMuted)) {- return true;- }-- return false;- }-- @computed("notification_level")- get notificationLevelString() {- // Get the key from the value- const notificationLevelString = Object.keys(NotificationLevels).find(- (key) => NotificationLevels[key] === this.notification_level- );- if (notificationLevelString) {- return notificationLevelString.toLowerCase();- }- }-- @computed("name")- get path() {- return `/c/${Category.slugFor(this)}/${this.id}`;- }-- @computed("path")- get url() {- return getURL(this.path);- }-- @computed- get fullSlug() {- return Category.slugFor(this).replace(/\//g, "-");- }-- @computed("name")- get nameLower() {- return this.name.toLowerCase();- }-- @computed("url")- get unreadUrl() {- return `${this.url}/l/unread`;- }-- @computed("url")- get newUrl() {- return `${this.url}/l/new`;- }-- @computed("color", "text_color")- get style() {- return `background-color: #${this.color}; color: #${this.text_color}`;- }-- @computed("topic_count")- get moreTopics() {- return this.topic_count > (this.num_featured_topics || 2);- }-- @computed("topic_count", "subcategories.[]")- get totalTopicCount() {- let topicCount = this.topic_count;- if (this.subcategories) {- this.subcategories.forEach((subcategory) => {- topicCount += subcategory.topic_count;- });- }- return topicCount;- }-- @computed("default_slow_mode_seconds")- get defaultSlowModeMinutes() {- return this.default_slow_mode_seconds- ? this.default_slow_mode_seconds / 60- : null;- }-- @computed("notification_level")- get isTracked() {- return this.notification_level >= NotificationLevels.TRACKING;- }-- get unreadTopicsCount() {- return this.topicTrackingState.countUnread({ categoryId: this.id });- }-- get newTopicsCount() {- return this.topicTrackingState.countNew({ categoryId: this.id });- }-- @computed("topics")- get latestTopic() {- if (this.topics && this.topics.length) {- return this.topics[0];- }- }-- @computed("topics")- get featuredTopics() {- if (this.topics && this.topics.length) {- return this.topics.slice(0, this.num_featured_topics || 2);- }- }-- @computed("id")- get isUncategorizedCategory() {- return Category.isUncategorized(this.id);- }-- get canCreateTopic() {- return this.permission === PermissionType.FULL;- }-- get subcategoryWithCreateTopicPermission() {- return this.subcategories?.find(- (subcategory) => subcategory.canCreateTopic- );- }-- setupCategoryTypes() {- this.categoryTypes = trackedObject(this.category_types);- }-- setupGroupsAndPermissions() {- if (!this.available_groups) {- return;- }-- if (this.group_permissions) {- this.permissions = this.group_permissions.map((elem) => {- removeValueFromArray(this.available_groups, elem.group_name);- return trackedObject(elem);- });- }- }-- /**- * @param {string[]} [categoryTypeIds] - ids of the category's types; when- * omitted, the server leaves the category's types unchanged.- */- save(categoryTypeIds) {- const id = this.id;- const url = id ? `/categories/${id}` : "/categories";-- this.styleType = this.style_type;-- return ajax(url, {- contentType: "application/json",- data: JSON.stringify({- name: this.name,- slug: this.slug,- color: this.color,- text_color: this.text_color,- permissions: this._permissionsForUpdate(),- auto_close_hours: this.auto_close_hours,- auto_close_based_on_last_post: this.get(- "auto_close_based_on_last_post"- ),- default_slow_mode_seconds: this.default_slow_mode_seconds,- position: this.position,- email_in: this.email_in,- email_in_allow_strangers: this.email_in_allow_strangers,- mailinglist_mirror: this.mailinglist_mirror,- parent_category_id: this.parent_category_id,- uploaded_logo_id: this.get("uploaded_logo.id"),- uploaded_logo_dark_id: this.get("uploaded_logo_dark.id"),- uploaded_background_id: this.get("uploaded_background.id"),- uploaded_background_dark_id: this.get("uploaded_background_dark.id"),- allow_badges: this.allow_badges,- category_setting_attributes: this.category_setting,- custom_fields: this.custom_fields,- topic_template: this.topic_template,- topic_title_placeholder: this.topic_title_placeholder,- form_template_ids: this.form_template_ids,- all_topics_wiki: this.all_topics_wiki,- allow_unlimited_owner_edits_on_first_post:- this.allow_unlimited_owner_edits_on_first_post,- allowed_tags: this.allowed_tags?.map((t) =>- typeof t === "object" ? t.name : t- ),- allowed_tag_groups: this.allowed_tag_groups,- allow_global_tags: this.allow_global_tags,- required_tag_groups: this.required_tag_groups,- sort_order: this.sort_order,- sort_ascending: this.sort_ascending,- topic_featured_link_allowed: this.topic_featured_link_allowed,- show_subcategory_list: this.show_subcategory_list,- num_featured_topics: this.num_featured_topics,- default_view: this.default_view,- subcategory_list_style: this.subcategory_list_style,- default_top_period: this.default_top_period,- minimum_required_tags: this.minimum_required_tags,- navigate_to_first_post_after_read: this.get(- "navigate_to_first_post_after_read"- ),- search_priority: this.search_priority,- moderating_group_ids: this.moderating_group_ids,- topic_posting_review_group_ids: this.topic_posting_review_group_ids,- reply_posting_review_group_ids: this.reply_posting_review_group_ids,- read_only_banner: this.read_only_banner,- default_list_filter: this.default_list_filter,- style_type: this.style_type,- emoji: this.emoji,- icon: this.icon,- ...(this.siteSettings.content_localization_enabled && {- locale: this.locale,- category_localizations: this.localizations,- }),- ...this._categoryTypeSaveProperties(id, categoryTypeIds),- ...this._pluginSaveProperties(),- category_types: categoryTypeIds,- }),- type: id ? "PUT" : "POST",- });- }-- destroy() {- return ajax(`/categories/${this.id || this.slug}`, {- type: "DELETE",- });- }-- addPermission(permission) {- addUniqueValueToArray(this.permissions, trackedObject(permission));- removeValueFromArray(this.available_groups, permission.group_name);- }-- removePermission(group_name) {- const permission = this.permissions.find(- (p) => p.group_name === group_name- );-- if (permission) {- removeValueFromArray(this.permissions, permission);- addUniqueValueToArray(this.available_groups, group_name);- }- }-- updatePermission(group_name, type) {- this.permissions.forEach((p, i) => {- if (p.group_name === group_name) {- this.permissions[i].permission_type = type;- }- });- }-- isType(type) {- return Object.keys(this.categoryTypes ?? {}).includes(type);- }-- getType(type) {- return this.categoryTypes?.[type];- }-- removeType(type) {- delete this.categoryTypes[type];- }-- setNotification(notification_level) {- this.currentUser.set(- "muted_category_ids",- this.currentUser.calculateMutedIds(- notification_level,- this.id,- "muted_category_ids"- )- );-- const url = `/category/${this.id}/notifications`;- return ajax(url, { data: { notification_level }, type: "POST" }).then(- (data) => {- this.currentUser.set(- "indirectly_muted_category_ids",- data.indirectly_muted_category_ids- );- this.set("notification_level", notification_level);- this.notifyPropertyChange("notification_level");- }- );- }-- _categoryTypeSaveProperties(id, categoryTypeIds) {- const props = {- category_type_site_settings: this.category_type_site_settings,- category_type_settings: this.category_type_settings,- };-- if (!id && this.categoryTypes) {- const primaryType = Object.keys(this.categoryTypes)[0];- if (categoryTypeIds?.includes(primaryType)) {- props.category_type = primaryType;- }- }-- return props;- }-- _pluginSaveProperties() {- return extraSavePropertiesFor("category", this);- }-- _permissionsForUpdate() {- const permissions = this.permissions;- let rval = {};- if (permissions.length) {- permissions.forEach((p) => (rval[p.group_name] = p.permission_type));- } else {- // empty permissions => staff-only access- rval[Site.currentProp("groupsById")[AUTO_GROUPS.staff.id].name] =- PermissionType.FULL;- }- return rval;- }-}--const categoryMultiCache = new MultiCache(async (ids) => {- try {- const { categories } = await ajax("/categories/find", { data: { ids } });- return new Map(categories.map((category) => [category.id, category]));- } catch (error) {- if (error.jqXHR?.status === HTTP_NOT_FOUND) {- return new Map();- }-- throw error;- }-});--export function resetCategoryCache() {- categoryMultiCache.reset();- _uncategorized = undefined;-}diff --git a/frontend/discourse/app/models/category.ts b/frontend/discourse/app/models/category.tsnew file mode 100644index 00000000000..b65ae613a98--- /dev/null+++ b/frontend/discourse/app/models/category.ts@@ -0,0 +1,1409 @@+import { tracked } from "@glimmer/tracking";+import { warn } from "@ember/debug";+import { computed, get } from "@ember/object";+import { dependentKeyCompat } from "@ember/object/compat";+import { trackedObject } from "@ember/reactive/collections";+import { service } from "@ember/service";+import { compare } from "@ember/utils";+import { ajax } from "discourse/lib/ajax";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";+import { AUTO_GROUPS } from "discourse/lib/constants";+import { getOwnerWithFallback } from "discourse/lib/get-owner";+import getURL from "discourse/lib/get-url";+import {+ extraSavePropertiesFor,+ registerModelSaveProperty,+} from "discourse/lib/model-extensions";+import { MultiCache } from "discourse/lib/multi-cache";+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 PermissionType from "discourse/models/permission-type";+import RestModel from "discourse/models/rest";+import Site from "discourse/models/site";+import type User from "discourse/models/user";+import type StoreService from "discourse/services/store";+import Topic from "./topic.js";++/** Category badge styles. */+export type CategoryStyle = "square" | "icon" | "emoji";++/** Who requires review before posting in a category. */+export type CategoryPostingReviewMode =+ | "no_one"+ | "everyone"+ | "everyone_except"+ | "no_one_except";++/** A group permission on a category, as edited in its settings. */+export interface CategoryPermission {+ group_name: string;+ permission_type: number | null;+ group_id: number;+}++/** A tag allowed in the category. */+export interface CategoryAllowedTag {+ id: number | string;+ name: string;+ slug?: string;+}++/** A tag group requirement on a category. */+export interface CategoryRequiredTagGroup {+ min_count: number;+ name?: string | null;+}++/** An uploaded image, including the empty upload placeholder. */+export type CategoryUpload =+ | { id: number; url: string; width?: number | null; height?: number | null }+ | { id: null; url: null };++/** Optional category settings sent by the server. */+export interface CategorySetting {+ auto_bump_cooldown_days?: number | null;+ num_auto_bump_daily?: number | null;+ require_reply_approval?: boolean;+ require_topic_approval?: boolean;+ nested_replies_default?: boolean;+ topic_posting_review_mode?: CategoryPostingReviewMode;+ reply_posting_review_mode?: CategoryPostingReviewMode;+}++/** A translated category name and description. */+export interface CategoryLocalization {+ id: number;+ locale: string;+ name: string;+ description: string | null;+}++/** A localization being edited; entries added before saving have no id yet. */+export type CategoryEditableLocalization = Omit<CategoryLocalization, "id"> & {+ id?: number;+ category_id?: number;+};++/** Metadata published by a category type, including type-specific additions. */+export interface CategoryTypeMetadata {+ id: string;+ name: string;+ title: string;+ available: boolean;+ visible: boolean;+ description?: string;+ icon?: string | null;+ configuration_schema: Record<string, Record<string, unknown>[]>;+ [key: string]: unknown;+}++/** TODO(typescript-pending): singleton adds these statics at runtime; remove when Site exposes them. */+type CategorySiteClass = typeof Site & {+ current(): Site & {+ lazy_load_categories?: boolean;+ loadedCategoryIds?: Set<number | string>;+ };+ currentProp(key: string): unknown;+};++type CategorySearchOptions = {+ parentCategoryId?: number;+ includeUncategorized?: boolean;+ selectCategoryIds?: number[];+ rejectCategoryIds?: number[];+ includeSubcategories?: boolean;+ includeAncestors?: boolean;+ prioritizedCategoryId?: number;+ limit?: number;+ page?: number;+};++type CategorySearchResponse = {+ categories: CategoryFields[];+ ancestors: CategoryFields[];+ categories_count: number;+};++type CategorySearchResult = {+ ancestors: Category[];+ categories: Category[];+ categoriesCount: number;+};++/** Server payload fields and values assigned by core; plugins can augment this interface. */+export interface CategoryFields {+ id?: number;+ name?: string;+ slug?: string | null;+ color?: string;+ text_color?: string;+ style_type?: CategoryStyle;+ icon?: string | null;+ emoji?: string | null;+ description?: string | null;+ description_text?: string | null;+ description_excerpt?: string | null;+ topic_url?: string | null;+ topic_count?: number;+ post_count?: number;+ position?: number | null;+ read_restricted?: boolean;+ permission?: number | null;+ parent_category_id?: number | null;+ notification_level?: number | null;+ can_edit?: boolean;+ can_delete?: true;+ cannot_delete_reason?: string;+ is_special?: true;+ is_uncategorized?: true;+ topic_template?: string | null;+ topic_title_placeholder?: string | null;+ has_children?: boolean | null;+ subcategory_count?: number | null;+ subcategory_ids?: number[] | null;+ subcategory_list?: object[];+ subcategory_list_style?: string | null;+ sort_order?: string | null;+ sort_ascending?: boolean | null;+ show_subcategory_list?: boolean | null;+ num_featured_topics?: number | null;+ default_view?: string | null;+ default_top_period?: string | null;+ default_list_filter?: string | null;+ minimum_required_tags?: number | null;+ navigate_to_first_post_after_read?: boolean;+ custom_fields?: Record<string, unknown>;+ uploaded_logo?: CategoryUpload | null;+ uploaded_logo_dark?: CategoryUpload | null;+ uploaded_background?: CategoryUpload | null;+ uploaded_background_dark?: CategoryUpload | null;+ allow_global_tags?: boolean;+ read_only_banner?: string | null;+ form_template_ids?: number[];+ category_types?: Record<string, CategoryTypeMetadata>;+ locale?: string | null;+ available_groups?: string[];+ allowed_tags?: (CategoryAllowedTag | string)[];+ allowed_tag_groups?: string[];+ auto_close_hours?: number | null;+ auto_close_based_on_last_post?: boolean | null;+ group_permissions?: CategoryPermission[];+ email_in?: string | null;+ email_in_allow_strangers?: boolean | null;+ mailinglist_mirror?: boolean;+ all_topics_wiki?: boolean;+ allow_unlimited_owner_edits_on_first_post?: boolean;+ allow_badges?: boolean;+ topic_featured_link_allowed?: boolean | null;+ search_priority?: number | null;+ default_slow_mode_seconds?: number | null;+ moderating_group_ids?: number[];+ topic_posting_review_group_ids?: number[];+ reply_posting_review_group_ids?: number[];+ category_setting?: CategorySetting | null;+ category_localizations?: CategoryLocalization[];+ available_category_types?: CategoryTypeMetadata[];+ category_type_settings?: Record<string, unknown>;+ category_type_site_settings?: Record<string, unknown>;+ site_texts?: Record<string, string>;+ topics?: object[];+ topics_day?: number;+ topics_week?: number;+ topics_month?: number;+ topics_year?: number;+ topics_all_time?: number;+ pickAll?: boolean;+ stat?: string;+ statTitle?: string;+ statTotal?: string;+}++const CATEGORY_ASYNC_SEARCH_CACHE: Record<string, CategorySearchResponse> = {};+const CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE: Record<+ string,+ { categories: CategoryFields[] }+> = {};+const HTTP_NOT_FOUND = 404;++let _uncategorized: Category | undefined;++/**+ * @internal+ * Registers a property to include when saving a category.+ *+ * Intended to be used only in the plugin API.+ *+ * @param propertyKey - The key of the property to include.+ */+export function _addCategoryPropertyForSave(propertyKey: string) {+ registerModelSaveProperty("category", propertyKey);+}++// `create()` assigns the server fields at runtime, so the class declares none of+// them. Merging an interface of the same name adds them to the class type, and+// lets plugins add theirs by augmenting `CategoryFields`.+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging+export default interface Category extends CategoryFields {}++// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging+export default class Category extends RestModel {+ // Sort subcategories directly under parents+ static sortCategories<+ T extends Pick<CategoryFields, "id" | "parent_category_id">,+ >(categories: T[]): T[] {+ const children = new Map<number | undefined, T[]>();++ categories.forEach((category) => {+ // parseInt coerces numeric and missing parent IDs at runtime.+ const parentId =+ parseInt(category.parent_category_id as unknown as string, 10) || -1;+ const group = children.get(parentId) || [];+ group.push(category);++ children.set(parentId, group);+ });++ // The flattened entries are category objects, not nested array values.+ const reduce = (values: T[]): T[] =>+ values+ .flatMap((c) => [c, reduce(children.get(c.id) || [])])+ .flat() as T[];++ return reduce(children.get(-1) || []);+ }++ static isUncategorized(categoryId: number | null | undefined): boolean {+ return (+ categoryId ===+ (Site as CategorySiteClass).currentProp("uncategorized_category_id")+ );+ }++ static slugEncoded(): boolean {+ const siteSettings: RestModel["siteSettings"] = getOwnerWithFallback(+ this+ ).lookup("service:site-settings");+ return siteSettings.slug_generation_method === "encoded";+ }++ static findUncategorized(): Category | undefined {+ _uncategorized =+ _uncategorized ||+ Category.list().find(+ (category) =>+ category.id ===+ (Site as CategorySiteClass).currentProp("uncategorized_category_id")+ );+ return _uncategorized;+ }++ static slugFor(+ category:+ | Pick<Category, "id" | "slug" | "parentCategory">+ | null+ | undefined,+ separator = "/",+ depth = 3+ ): string {+ if (!category) {+ return "";+ }++ const parentCategory = get(category, "parentCategory");+ let result = "";++ if (parentCategory && depth > 1) {+ result =+ Category.slugFor(parentCategory, separator, depth - 1) + separator;+ }++ const id = get(category, "id"),+ slug = get(category, "slug");++ return !slug || slug.trim().length === 0+ ? `${result}${id}-category`+ : result + slug;+ }++ static list(): Category[] {+ // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.+ return (Site as CategorySiteClass).currentProp(+ "categoriesList"+ ) as Category[];+ }++ static listByActivity(): Category[] {+ // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.+ return (Site as CategorySiteClass).currentProp(+ "sortedCategories"+ ) as Category[];+ }++ static _idMap(): Map<number, Category> {+ // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.+ return (Site as CategorySiteClass).currentProp("categoriesById") as Map<+ number,+ Category+ >;+ }++ static findSingleBySlug(slug: string): Category | undefined {+ if (!this.slugEncoded()) {+ return Category.list().find((c) => Category.slugFor(c) === slug);+ } else {+ return Category.list().find(+ (c) => Category.slugFor(c) === encodeURI(slug)+ );+ }+ }++ static findById(+ id: number | string | null | undefined+ ): Category | undefined {+ if (!id) {+ return;+ }++ if (typeof id === "string") {+ id = parseInt(id, 10);+ }++ return Category._idMap().get(id);+ }++ static findByIds(ids: (number | string)[] = []): Category[] {+ // Boolean filtering removes missing lookups without changing the predicate.+ return ids.map((id) => Category.findById(id)).filter(Boolean) as Category[];+ }++ static hasAsyncFoundAll(ids: (number | string)[]): boolean {+ const loadedCategoryIds =+ (Site as CategorySiteClass).current().loadedCategoryIds || new Set();+ return ids.every((id) => loadedCategoryIds.has(id));+ }++ static async asyncFindByIds(+ ids: (number | string)[] = []+ ): Promise<Category[]> {+ // parseInt also coerces numeric IDs supplied by callers.+ ids = ids.map((x) => parseInt(x as string, 10));+ const site = (Site as CategorySiteClass).current();++ if (!site.lazy_load_categories || this.hasAsyncFoundAll(ids)) {+ return this.findByIds(ids);+ }++ // TODO(typescript-pending): MultiCache loses its callback's value type; remove when generic.+ const result = (await categoryMultiCache.fetch(ids)) as Map<+ number | string,+ CategoryFields | undefined+ >;+ if (categoryMultiCache.hadTooManyCalls()) {+ warn(+ "Multiple calls to Category.asyncFindByIds within a second. Could they be combined?",+ {+ id: "discourse.category.multiple-async-find-by-ids-calls",+ }+ );+ }++ const loadedCategoryIds = site.loadedCategoryIds || new Set();+ for (const id of ids) {+ const category = result.get(id);+ if (category) {+ site.updateCategory(category);+ } else {+ site.removeCategory(id);+ }+ loadedCategoryIds.add(id);+ }+ site.set("loadedCategoryIds", loadedCategoryIds);++ return this.findByIds(ids);+ }++ static async asyncFindById(+ id: number | string+ ): Promise<Category | undefined> {+ return (await Category.asyncFindByIds([id]))[0];+ }++ static findBySlugAndParent(+ slug: string,+ parentCategory: Category | null | undefined+ ): Category | undefined {+ if (this.slugEncoded()) {+ slug = encodeURI(slug);+ }+ return Category.list().find((category) => {+ return (+ category.slug === slug &&+ (category.parentCategory || null) === parentCategory+ );+ });+ }++ static findBySlugPath(slugPath: string[]): Category | null {+ let category: Category | null | undefined = null;++ for (const slug of slugPath) {+ category = this.findBySlugAndParent(slug, category);++ if (!category) {+ return null;+ }+ }++ return category;+ }++ static async asyncFindBySlugPath(+ slugPath: string,+ opts: { includePermissions?: boolean } = {}+ ): Promise<Category | undefined> {+ const data: { slug_path: string; include_permissions?: boolean } = {+ slug_path: slugPath,+ };+ if (opts.includePermissions) {+ data.include_permissions = true;+ }++ // TODO(typescript-pending): ajax does not type response payloads yet.+ const result = (await ajax("/categories/find", { data })) as {+ categories: CategoryFields[];+ };++ const categories = result["categories"].map(+ (category: CategoryFields | Category) => {+ // TODO(typescript-pending): Site.updateCategory returns the model without types.+ category = (Site as CategorySiteClass)+ .current()+ .updateCategory(category) as Category;+ // `Category` extends `CategoryFields`, so the reassignment above does not+ // narrow the union; `updateCategory` returns the model.+ if (opts.includePermissions) {+ (category as Category).setupGroupsAndPermissions();+ }+ return category as Category;+ }+ );++ return categories[categories.length - 1];+ }++ static async asyncFindBySlugPathWithID(+ slugPathWithID: string+ ): Promise<Category | undefined> {+ // TODO(typescript-pending): ajax does not type response payloads yet.+ const result = (await ajax("/categories/find", {+ data: { slug_path_with_id: slugPathWithID },+ })) as { categories: CategoryFields[] };++ const categories = result["categories"].map(+ (category) =>+ // TODO(typescript-pending): Site.updateCategory returns the model without types.+ (Site as CategorySiteClass)+ .current()+ .updateCategory(category) as Category+ );++ return categories[categories.length - 1];+ }++ static findBySlugPathWithID(+ slugPathWithID: string+ ): Category | null | undefined {+ let parts = slugPathWithID.split("/").filter(Boolean);+ // slugs found by star/glob pathing in ember do not automatically url decode - ensure that these are decoded+ if (this.slugEncoded()) {+ parts = parts.map((urlPart) => decodeURI(urlPart));+ }+ let category;++ if (parts.length > 0 && parts[parts.length - 1].match(/^\d+$/)) {+ // The branch's length check guarantees a final path segment.+ const id = parseInt(parts.pop()!, 10);++ category = Category.findById(id);+ } else {+ category = Category.findBySlugPath(parts);++ if (+ !category &&+ parts.length > 0 &&+ parts[parts.length - 1].match(/^\d+-category/)+ ) {+ // The branch's length check guarantees a final path segment.+ const id = parseInt(parts.pop()!, 10);++ category = Category.findById(id);+ }+ }++ return category;+ }++ static findBySlug(slug: string, parentSlug?: string): Category | undefined {+ const categories = Category.list();+ let category;++ if (parentSlug) {+ const parentCategory = Category.findSingleBySlug(parentSlug);+ if (parentCategory) {+ if (slug === "none") {+ return parentCategory;+ }++ category = categories.find((item) => {+ return (+ item &&+ item.get("parentCategory") === parentCategory &&+ ((!this.slugEncoded() &&+ Category.slugFor(item) === parentSlug + "/" + slug) ||+ (this.slugEncoded() &&+ Category.slugFor(item) ===+ encodeURI(parentSlug) + "/" + encodeURI(slug)))+ );+ });+ }+ } else {+ category = Category.findSingleBySlug(slug);++ // If we have a parent category, we need to enforce it+ if (category && category.get("parentCategory")) {+ return;+ }+ }++ // In case the slug didn't work, try to find it by id instead.+ if (!category) {+ category = categories.find((c) => c.id === parseInt(slug, 10));+ }++ return category;+ }++ static fetchVisibleGroups(id: number): Promise<{ groups: string[] }> {+ return ajax(`/c/${id}/visible_groups.json`);+ }++ static reloadById(+ id: number | string+ ): Promise<{ category: CategoryFields }> {+ return ajax(`/c/${id}/show.json`);+ }++ static reloadBySlugPath(+ slugPath: string+ ): Promise<{ category: CategoryFields }> {+ return ajax(`/c/${slugPath}/find_by_slug.json`);+ }++ static reloadCategoryWithPermissions(+ params: { slug: string },+ store: StoreService,+ site: Site+ ): Promise<Category> {+ return this.reloadBySlugPath(params.slug).then((result) =>+ this._includePermissions(result.category, store, site)+ );+ }++ static _includePermissions(+ category: CategoryFields,+ store: StoreService,+ site: Site+ ): Category {+ // TODO(typescript-pending): Site.updateCategory returns the model without types.+ const model = site.updateCategory(category) as Category;+ model.setupGroupsAndPermissions();+ model.setupCategoryTypes();+ return model;+ }++ static search(+ term: string,+ opts?: Pick<CategorySearchOptions, "limit" | "parentCategoryId">+ ): Category[] {+ let limit = 5;+ let parentCategoryId: number | undefined;++ if (opts) {+ if (opts.limit === 0) {+ return [];+ } else if (opts.limit) {+ limit = opts.limit;+ }+ if (opts.parentCategoryId) {+ parentCategoryId = opts.parentCategoryId;+ }+ }++ const emptyTerm = term === "";+ let slugTerm = term;++ // Search assumes the loaded categories have names and slugs.+ const normalize = (str: string | null | undefined): string =>+ removeAccents(str!.toLowerCase());++ if (!emptyTerm) {+ term = normalize(term);+ slugTerm = term;+ term = term.replace(/-/g, " ");+ }++ const categories = Category.listByActivity();+ const length = categories.length;+ let i;+ const data: Category[] = [];++ const done = () => {+ return data.length === limit;+ };++ const validCategoryParent = (category: Category) => {+ return (+ !parentCategoryId ||+ category.get("parent_category_id") === parentCategoryId+ );+ };++ for (i = 0; i < length && !done(); i++) {+ const category = categories[i];+ if (+ ((emptyTerm && !category.get("parent_category_id")) ||+ (!emptyTerm &&+ (normalize(category.get("name")).startsWith(term) ||+ normalize(category.get("slug")).startsWith(slugTerm)))) &&+ validCategoryParent(category)+ ) {+ data.push(category);+ }+ }++ if (!done()) {+ for (i = 0; i < length && !done(); i++) {+ const category = categories[i];++ if (+ ((!emptyTerm && normalize(category.get("name")).indexOf(term) > 0) ||+ normalize(category.get("slug")).indexOf(slugTerm) > 0) &&+ validCategoryParent(category)+ ) {+ if (!data.includes(category)) {+ data.push(category);+ }+ }+ }+ }++ return data.sort((a, b) => compare(a?.read_restricted, b?.read_restricted));+ }++ static async asyncHierarchicalSearch(+ term: string,+ opts?: { only?: number[]; except?: number[]; page?: number }+ ): Promise<Category[]> {+ opts ||= {};++ const data = {+ term,+ only: opts.only,+ except: opts.except,+ page: opts.page,+ };++ const cacheKey = JSON.stringify(data);+ CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[cacheKey] ||= await ajax(+ "/categories/hierarchical_search",+ {+ method: "GET",+ data,+ }+ );+ const result = CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[cacheKey];++ return result["categories"].map(+ (category) =>+ // TODO(typescript-pending): Site.updateCategory returns the model without types.+ (Site as CategorySiteClass)+ .current()+ .updateCategory(category) as Category+ );+ }++ static clearAsyncHierarchicalSearchCache() {+ Object.keys(CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE).forEach((key) => {+ delete CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE[key];+ });+ }++ static asyncSearch(+ term: string,+ opts: CategorySearchOptions & { includeAncestors: true }+ ): Promise<CategorySearchResult>;++ static asyncSearch(+ term: string,+ opts?: CategorySearchOptions & { includeAncestors?: false }+ ): Promise<Category[]>;++ static asyncSearch(+ term: string,+ opts?: CategorySearchOptions+ ): Promise<Category[] | CategorySearchResult>;++ static async asyncSearch(+ term: string,+ opts?: CategorySearchOptions+ ): Promise<Category[] | CategorySearchResult> {+ opts ||= {};++ const data = {+ term,+ parent_category_id: opts.parentCategoryId,+ include_uncategorized: opts.includeUncategorized,+ select_category_ids: opts.selectCategoryIds,+ reject_category_ids: opts.rejectCategoryIds,+ include_subcategories: opts.includeSubcategories,+ include_ancestors: opts.includeAncestors,+ prioritized_category_id: opts.prioritizedCategoryId,+ limit: opts.limit,+ page: opts.page,+ };++ const result = (CATEGORY_ASYNC_SEARCH_CACHE[JSON.stringify(data)] ||=+ await ajax("/categories/search", { method: "POST", data }));++ if (opts.includeAncestors) {+ return {+ ancestors: result["ancestors"].map(+ (category) =>+ // TODO(typescript-pending): Site.updateCategory returns the model without types.+ (Site as CategorySiteClass)+ .current()+ .updateCategory(category) as Category+ ),+ categories: result["categories"].map(+ (category) =>+ // TODO(typescript-pending): Site.updateCategory returns the model without types.+ (Site as CategorySiteClass)+ .current()+ .updateCategory(category) as Category+ ),+ categoriesCount: result["categories_count"],+ };+ } else {+ return result["categories"].map(+ (category) =>+ // TODO(typescript-pending): Site.updateCategory returns the model without types.+ (Site as CategorySiteClass)+ .current()+ .updateCategory(category) as Category+ );+ }+ }++ @service declare currentUser: User | null;++ @tracked color?: string;+ @tracked emoji?: string | null;+ @tracked icon?: string | null;+ @tracked+ localizations: CategoryEditableLocalization[] | undefined =+ this.category_localizations;+ @tracked minimum_required_tags?: number | null;+ @tracked styleType: CategoryStyle | undefined = this.style_type;+ @tracked allowed_tags?: (CategoryAllowedTag | string)[];+ @tracked categoryTypes!: Record<string, CategoryTypeMetadata>;+ @autoTrackedArray available_groups?: string[];+ @autoTrackedArray permissions?: CategoryPermission[];+ @autoTrackedArray required_tag_groups?: CategoryRequiredTagGroup[];++ init(...args: Parameters<RestModel["init"]>) {+ super.init(...args);+ this.setupGroupsAndPermissions();+ this.setupCategoryTypes();+ }++ @computed("parent_category_id", "site.categories.[]")+ get parentCategory(): Category | undefined {+ if (this.parent_category_id) {+ return Category.findById(this.parent_category_id);+ }+ }++ set parentCategory(newParentCategory: Category | undefined) {+ this.set("parent_category_id", newParentCategory?.id);+ }++ @dependentKeyCompat+ get availableGroups() {+ return this.available_groups;+ }++ get descriptionText() {+ return applyValueTransformer(+ "category-description-text",+ this.get("description_text"),+ {+ category: this,+ }+ );+ }++ get displayName() {+ return applyValueTransformer("category-display-name", this.get("name"), {+ category: this,+ });+ }++ get textColor() {+ return applyValueTransformer(+ "category-text-color",+ this.get("text_color"),+ {+ category: this,+ }+ );+ }++ get subcategories(): Category[] {+ return applyValueTransformer(+ "category-subcategories",+ // TODO(typescript-pending): Site's category collections are untyped; remove when Site is typed.+ (+ this.site.categoriesByParentId as Map<number | undefined, Category[]>+ ).get(this.id) || [],+ { category: this }+ );+ }++ get unloadedSubcategoryCount() {+ // This count is read on payloads that include the subcategory count.+ return this.subcategory_count! - this.subcategories.length;+ }++ @computed("subcategory_list")+ get serializedSubcategories() {+ // TODO(typescript-pending): serialized subcategories include topic payloads; remove when typed at the source.+ return (+ this.subcategory_list as+ | (CategoryFields & { topics?: Record<string, unknown>[] })[]+ | undefined+ )?.map((c) => {+ const subcategory = Category.create({+ ...c,+ // TODO(typescript-pending): Topic.create forwards attrs but its JS signature omits them.+ topics: c.topics?.map((t) =>+ (Topic as typeof Topic & { create(attrs: object): Topic }).create(t)+ ),+ });+ return subcategory;+ });+ }++ @dependentKeyCompat+ get minimumRequiredTags() {+ // An absent group list still follows the original comparison's false branch.+ if ((this.required_tag_groups?.length as number) > 0) {+ // it should require the max between the bare minimum set in the category and the sum of the min_count of the+ // required_tag_groups+ return Math.max(+ // The length comparison above guarantees the group list exists.+ this.required_tag_groups!.reduce((sum, rtg) => sum + rtg.min_count, 0),+ this.minimum_required_tags || 0+ );+ } else {+ // Missing/null minima still compare false without introducing a fallback.+ return this.minimum_required_tags! > 0+ ? this.minimum_required_tags+ : null;+ }+ }++ @computed+ get availablePermissions() {+ // TODO(typescript-pending): PermissionType reads its create-assigned id but does not declare it.+ return [+ PermissionType.create({+ id: PermissionType.FULL,+ } as Partial<PermissionType> & { id: number }),+ PermissionType.create({+ id: PermissionType.CREATE_POST,+ } as Partial<PermissionType> & { id: number }),+ PermissionType.create({+ id: PermissionType.READONLY,+ } as Partial<PermissionType> & { id: number }),+ ];+ }++ @computed("id")+ get searchContext(): {+ type: string;+ id: number | undefined;+ category: Category;+ } {+ return {+ type: "category",+ id: this.id,+ /** The category model. */+ category: this,+ };+ }++ @computed("parentCategory.ancestors")+ get ancestors(): Category[] {+ return [...(this.parentCategory?.ancestors || []), this];+ }++ @computed("parentCategory", "parentCategory.predecessors")+ get predecessors(): Category[] {+ if (this.parentCategory) {+ return [+ this.parentCategory,+ ...(this.parentCategory?.predecessors || []),+ ];+ } else {+ return [];+ }+ }++ get descendants(): Category[] {+ const descendants: Category[] = [this];+ for (let i = 0; i < descendants.length; i++) {+ if (descendants[i].subcategories) {+ descendants.push(...descendants[i].subcategories);+ }+ }+ return descendants;+ }++ @computed("parentCategory.level")+ get level(): number {+ if (!this.parentCategory?.level) {+ return this.parentCategory?.level === 0 ? 1 : 0;+ } else {+ return this.parentCategory?.level + 1;+ }+ }++ @computed("has_children", "subcategories")+ get isParent() {+ return (+ this.has_children || (this.subcategories && this.subcategories.length > 0)+ );+ }++ @computed("subcategories")+ get isGrandParent() {+ return (+ this.subcategories &&+ this.subcategories.some(+ (cat) => cat.subcategories && cat.subcategories.length > 0+ )+ );+ }++ @computed("notification_level")+ get isMuted() {+ return this.notification_level === NotificationLevels.MUTED;+ }++ @computed("isMuted", "subcategories")+ get isHidden(): boolean {+ if (!this.isMuted) {+ return false;+ } else if (!this.subcategories) {+ return true;+ }++ if (this.subcategories.some((cat) => !cat.isHidden)) {+ return false;+ }++ return true;+ }++ @computed("isMuted", "subcategories")+ get hasMuted(): boolean {+ if (this.isMuted) {+ return true;+ } else if (!this.subcategories) {+ return false;+ }++ if (this.subcategories.some((cat) => cat.hasMuted)) {+ return true;+ }++ return false;+ }++ @computed("notification_level")+ get notificationLevelString() {+ // Get the key from the value+ const notificationLevelString = Object.keys(NotificationLevels).find(+ (key) =>+ NotificationLevels[key as keyof typeof NotificationLevels] ===+ this.notification_level+ );+ if (notificationLevelString) {+ return notificationLevelString.toLowerCase();+ }+ }++ @computed("name")+ get path() {+ return `/c/${Category.slugFor(this)}/${this.id}`;+ }++ @computed("path")+ get url(): string {+ return getURL(this.path);+ }++ @computed+ get fullSlug() {+ return Category.slugFor(this).replace(/\//g, "-");+ }++ @computed("name")+ get nameLower() {+ // Name-dependent views assume the category name is loaded.+ return this.name!.toLowerCase();+ }++ @computed("url")+ get unreadUrl() {+ return `${this.url}/l/unread`;+ }++ @computed("url")+ get newUrl() {+ return `${this.url}/l/new`;+ }++ @computed("color", "text_color")+ get style() {+ return `background-color: #${this.color}; color: #${this.text_color}`;+ }++ @computed("topic_count")+ get moreTopics() {+ // The comparison keeps JavaScript's handling of a missing count.+ return this.topic_count! > (this.num_featured_topics || 2);+ }++ @computed("topic_count", "subcategories.[]")+ get totalTopicCount(): number | undefined {+ // Transient preview categories have no topic count; the sum keeps JavaScript's+ // handling of a missing one.+ let topicCount = this.topic_count as number;+ if (this.subcategories) {+ this.subcategories.forEach((subcategory) => {+ topicCount += subcategory.topic_count!;+ });+ }+ return topicCount;+ }++ @computed("default_slow_mode_seconds")+ get defaultSlowModeMinutes() {+ return this.default_slow_mode_seconds+ ? this.default_slow_mode_seconds / 60+ : null;+ }++ @computed("notification_level")+ get isTracked() {+ // Preserve the comparison when notification_level is absent or null.+ return this.notification_level! >= NotificationLevels.TRACKING;+ }++ get unreadTopicsCount(): number {+ return this.topicTrackingState.countUnread({ categoryId: this.id });+ }++ get newTopicsCount(): number {+ return this.topicTrackingState.countNew({ categoryId: this.id });+ }++ @computed("topics")+ get latestTopic() {+ if (this.topics && this.topics.length) {+ return this.topics[0];+ }+ }++ @computed("topics")+ get featuredTopics() {+ if (this.topics && this.topics.length) {+ return this.topics.slice(0, this.num_featured_topics || 2);+ }+ }++ @computed("id")+ get isUncategorizedCategory() {+ return Category.isUncategorized(this.id);+ }++ get canCreateTopic() {+ return this.permission === PermissionType.FULL;+ }++ get subcategoryWithCreateTopicPermission() {+ return this.subcategories?.find(+ (subcategory) => subcategory.canCreateTopic+ );+ }++ setupCategoryTypes() {+ this.categoryTypes = trackedObject(this.category_types);+ }++ setupGroupsAndPermissions() {+ if (!this.available_groups) {+ return;+ }++ if (this.group_permissions) {+ this.permissions = this.group_permissions.map((elem) => {+ // setup requires available_groups; the guard above established it before mapping.+ removeValueFromArray(this.available_groups!, elem.group_name);+ return trackedObject(elem);+ });+ }+ }++ /**+ * @param categoryTypeIds - ids of the category's types; when+ * omitted, the server leaves the category's types unchanged.+ */+ save(categoryTypeIds?: string[]): Promise<{ category: CategoryFields }> {+ const id = this.id;+ const url = id ? `/categories/${id}` : "/categories";++ this.styleType = this.style_type;++ return ajax(url, {+ contentType: "application/json",+ data: JSON.stringify({+ name: this.name,+ slug: this.slug,+ color: this.color,+ text_color: this.text_color,+ permissions: this._permissionsForUpdate(),+ auto_close_hours: this.auto_close_hours,+ auto_close_based_on_last_post: this.get(+ "auto_close_based_on_last_post"+ ),+ default_slow_mode_seconds: this.default_slow_mode_seconds,+ position: this.position,+ email_in: this.email_in,+ email_in_allow_strangers: this.email_in_allow_strangers,+ mailinglist_mirror: this.mailinglist_mirror,+ parent_category_id: this.parent_category_id,+ uploaded_logo_id: this.get("uploaded_logo.id"),+ uploaded_logo_dark_id: this.get("uploaded_logo_dark.id"),+ uploaded_background_id: this.get("uploaded_background.id"),+ uploaded_background_dark_id: this.get("uploaded_background_dark.id"),+ allow_badges: this.allow_badges,+ category_setting_attributes: this.category_setting,+ custom_fields: this.custom_fields,+ topic_template: this.topic_template,+ topic_title_placeholder: this.topic_title_placeholder,+ form_template_ids: this.form_template_ids,+ all_topics_wiki: this.all_topics_wiki,+ allow_unlimited_owner_edits_on_first_post:+ this.allow_unlimited_owner_edits_on_first_post,+ allowed_tags: this.allowed_tags?.map((t) =>+ typeof t === "object" ? t.name : t+ ),+ allowed_tag_groups: this.allowed_tag_groups,+ allow_global_tags: this.allow_global_tags,+ required_tag_groups: this.required_tag_groups,+ sort_order: this.sort_order,+ sort_ascending: this.sort_ascending,+ topic_featured_link_allowed: this.topic_featured_link_allowed,+ show_subcategory_list: this.show_subcategory_list,+ num_featured_topics: this.num_featured_topics,+ default_view: this.default_view,+ subcategory_list_style: this.subcategory_list_style,+ default_top_period: this.default_top_period,+ minimum_required_tags: this.minimum_required_tags,+ navigate_to_first_post_after_read: this.get(+ "navigate_to_first_post_after_read"+ ),+ search_priority: this.search_priority,+ moderating_group_ids: this.moderating_group_ids,+ topic_posting_review_group_ids: this.topic_posting_review_group_ids,+ reply_posting_review_group_ids: this.reply_posting_review_group_ids,+ read_only_banner: this.read_only_banner,+ default_list_filter: this.default_list_filter,+ style_type: this.style_type,+ emoji: this.emoji,+ icon: this.icon,+ // TODO(typescript-pending): the settings factory does not publish property types yet.+ ...((this.siteSettings.content_localization_enabled as boolean) && {+ locale: this.locale,+ category_localizations: this.localizations,+ }),+ ...this._categoryTypeSaveProperties(id, categoryTypeIds),+ ...this._pluginSaveProperties(),+ category_types: categoryTypeIds,+ }),+ type: id ? "PUT" : "POST",+ });+ }++ destroy(this: never, ...args: never[]): never;+ destroy(): Promise<unknown>;+ destroy(): Promise<unknown> {+ return ajax(`/categories/${this.id || this.slug}`, {+ type: "DELETE",+ });+ }++ addPermission(permission: CategoryPermission) {+ // Permission editing requires the edit form's initialized permission/group arrays.+ addUniqueValueToArray(this.permissions!, trackedObject(permission));+ removeValueFromArray(this.available_groups!, permission.group_name);+ }++ removePermission(group_name: string) {+ // Permission editing requires the edit form's initialized permission/group arrays.+ const permission = this.permissions!.find(+ (p) => p.group_name === group_name+ );++ if (permission) {+ removeValueFromArray(this.permissions!, permission);+ addUniqueValueToArray(this.available_groups!, group_name);+ }+ }++ updatePermission(group_name: string, type: number | null) {+ // Permission editing requires the edit form's initialized permission array.+ this.permissions!.forEach((p, i) => {+ if (p.group_name === group_name) {+ this.permissions![i].permission_type = type;+ }+ });+ }++ isType(type: string) {+ return Object.keys(this.categoryTypes ?? {}).includes(type);+ }++ getType(type: string): CategoryTypeMetadata | undefined {+ return this.categoryTypes?.[type];+ }++ removeType(type: string) {+ delete this.categoryTypes[type];+ }++ setNotification(notification_level: number): Promise<void> {+ // Notification changes require a signed-in user.+ this.currentUser!.set(+ "muted_category_ids",+ this.currentUser!.calculateMutedIds(+ notification_level,+ this.id,+ "muted_category_ids"+ )+ );++ const url = `/category/${this.id}/notifications`;+ return ajax(url, { data: { notification_level }, type: "POST" }).then(+ (data) => {+ // Notification changes require a signed-in user through completion.+ this.currentUser!.set(+ "indirectly_muted_category_ids",+ data.indirectly_muted_category_ids+ );+ this.set("notification_level", notification_level);+ this.notifyPropertyChange("notification_level");+ }+ );+ }++ _categoryTypeSaveProperties(+ id: number | undefined,+ categoryTypeIds?: string[]+ ) {+ const props: {+ category_type_site_settings: CategoryFields["category_type_site_settings"];+ category_type_settings: CategoryFields["category_type_settings"];+ category_type?: string;+ } = {+ category_type_site_settings: this.category_type_site_settings,+ category_type_settings: this.category_type_settings,+ };++ if (!id && this.categoryTypes) {+ const primaryType = Object.keys(this.categoryTypes)[0];+ if (categoryTypeIds?.includes(primaryType)) {+ props.category_type = primaryType;+ }+ }++ return props;+ }++ _pluginSaveProperties() {+ return extraSavePropertiesFor("category", this);+ }++ _permissionsForUpdate() {+ // Saving permissions requires the edit form's initialized permission array.+ const permissions = this.permissions!;+ const rval: Record<string, number | null> = {};+ if (permissions.length) {+ permissions.forEach((p) => (rval[p.group_name] = p.permission_type));+ } else {+ // empty permissions => staff-only access+ // TODO(typescript-pending): Site's group map omits its entry types; remove when Site is typed.+ rval[+ (+ (Site as CategorySiteClass).currentProp("groupsById") as Record<+ number,+ { name: string }+ >+ )[AUTO_GROUPS.staff.id].name+ ] = PermissionType.FULL;+ }+ return rval;+ }+}++const categoryMultiCache = new MultiCache(async (ids: number[]) => {+ try {+ // TODO(typescript-pending): ajax does not type response payloads yet.+ const { categories } = (await ajax("/categories/find", {+ data: { ids },+ })) as { categories: CategoryFields[] };+ return new Map(categories.map((category) => [category.id, category]));+ } catch (error) {+ // TODO(typescript-pending): ajax rejects with its jqXHR wrapper; remove when errors are typed.+ if (+ (error as { jqXHR?: { status?: number } }).jqXHR?.status ===+ HTTP_NOT_FOUND+ ) {+ return new Map();+ }++ throw error;+ }+});++export function resetCategoryCache() {+ categoryMultiCache.reset();+ _uncategorized = undefined;+}diff --git a/frontend/discourse/app/models/pending-post.js b/frontend/discourse/app/models/pending-post.jsindex 1b8b44ca5e8..5bb6118b5e6 100644--- a/frontend/discourse/app/models/pending-post.js+++ b/frontend/discourse/app/models/pending-post.js@@ -3,7 +3,7 @@ import { computed } from "@ember/object";import { cook } from "discourse/lib/text";import { userPath } from "discourse/lib/url";import RestModel from "discourse/models/rest";-import Category from "./category.js";+import Category from "./category.ts";export default class PendingPost extends RestModel {/** @type {string | import("@ember/template").TrustedHTML | null} */diff --git a/frontend/discourse/app/models/rest.ts b/frontend/discourse/app/models/rest.tsindex 9860620e961..40a033a2f59 100644--- a/frontend/discourse/app/models/rest.ts+++ b/frontend/discourse/app/models/rest.ts@@ -12,6 +12,9 @@ import {modelNameFor,} from "discourse/lib/model-extensions";import { enumerateTrackedEntries } from "discourse/lib/tracked-tools";+import type Site from "discourse/models/site";+import type TopicTrackingState from "discourse/models/topic-tracking-state";+import type SiteSettingsService from "discourse/services/site-settings";import type StoreService from "discourse/services/store";/** A JSON payload sent to or received from the server. */@@ -114,6 +117,13 @@ export default class RestModel extends EmberObject {primaryKey = "id";declare store: StoreService;+ declare site: Site;++ /** TODO(typescript-pending): the factory returns the settings instance without types; remove the mapped unknown shape when its return is typed. */+ declare siteSettings: {+ [K in keyof ReturnType<typeof SiteSettingsService.create>]: unknown;+ };+ declare topicTrackingState: TopicTrackingState;@tracked __state?: RestModelState;diff --git a/frontend/discourse/app/models/reviewable.js b/frontend/discourse/app/models/reviewable.jsindex 9c428b6aded..b4f320d7529 100644--- a/frontend/discourse/app/models/reviewable.js+++ b/frontend/discourse/app/models/reviewable.js@@ -7,7 +7,7 @@ import { uniqueItemsFromArray } from "discourse/lib/array-tools";import { autoTrackedArray } from "discourse/lib/tracked-tools";import RestModel from "discourse/models/rest";import I18n, { i18n } from "discourse-i18n";-import Category from "./category.js";+import Category from "./category.ts";export const PENDING = 0;export const APPROVED = 1;diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.jsindex 31d964f962d..a24e1988252 100644--- a/frontend/discourse/app/models/topic.js+++ b/frontend/discourse/app/models/topic.js@@ -36,7 +36,7 @@ import Site from "discourse/models/site";import TopicDetails from "discourse/models/topic-details";import { flushMap } from "discourse/services/store";import { i18n } from "discourse-i18n";-import Category from "./category.js";+import Category from "./category.ts";export function _addTrackedTopicProperty(propertyKey) {stampModelClass(Topic, "topic");diff --git a/frontend/discourse/app/models/user-action.js b/frontend/discourse/app/models/user-action.jsindex 0c86b6ad641..0edcaf6735e 100644--- a/frontend/discourse/app/models/user-action.js+++ b/frontend/discourse/app/models/user-action.js@@ -5,7 +5,7 @@ import { userPath } from "discourse/lib/url";import { escapeExpression, postUrl } from "discourse/lib/utilities";import RestModel from "discourse/models/rest";import UserActionGroup from "discourse/models/user-action-group";-import Category from "./category.js";+import Category from "./category.ts";const UserActionTypes = {likes_given: 1,diff --git a/frontend/discourse/app/services/store.ts b/frontend/discourse/app/services/store.tsindex cbc7097ef9e..6e4234bd61c 100644--- a/frontend/discourse/app/services/store.ts+++ b/frontend/discourse/app/services/store.ts@@ -8,6 +8,7 @@ import { ajax } from "discourse/lib/ajax";import { getRegister } from "discourse/lib/get-owner";import { cleanNullQueryParams } from "discourse/lib/utilities";import WeakValueMap from "discourse/lib/weak-value-map";+import type Category from "discourse/models/category";import RestModel, {type RestModelAttrs,type RestModelClass,@@ -20,6 +21,7 @@ import type UserDraft from "discourse/models/user-draft";/** Model instances by store type name. Plugins add theirs through module augmentation. */export interface ModelRegistry {+ category: Category;"user-draft": UserDraft;}diff --git a/frontend/discourse/tests/acceptance/category-edit-test.js b/frontend/discourse/tests/acceptance/category-edit-test.jsindex 2f4d92c5454..ae242c599fd 100644--- a/frontend/discourse/tests/acceptance/category-edit-test.js+++ b/frontend/discourse/tests/acceptance/category-edit-test.js@@ -782,3 +782,36 @@ acceptance("Category Edit - saved value types", function (needs) {);});});++acceptance("Category Edit - deleting", function (needs) {+ needs.user();++ let deleteRequests;++ needs.hooks.beforeEach(() => (deleteRequests = []));++ needs.pretender((server, helper) => {+ server.delete("/categories/:id", (request) => {+ deleteRequests.push(request.params.id);+ return helper.response(200, { success: "OK" });+ });+ });++ test("deletes the category and returns to the categories list", async function (assert) {+ await visit("/c/testing/edit/settings");+ await click(".edit-category__delete-actions .btn-danger");+ await click(".dialog-footer .btn-danger");++ assert.deepEqual(deleteRequests, ["11"], "deletes the category by id");+ assert.strictEqual(currentURL(), "/categories");+ });++ test("cancelling the confirmation keeps the category", async function (assert) {+ await visit("/c/testing/edit/settings");+ await click(".edit-category__delete-actions .btn-danger");+ await click(".dialog-footer .btn-default");++ assert.deepEqual(deleteRequests, [], "does not delete the category");+ assert.strictEqual(currentURL(), "/c/testing/edit/settings");+ });+});diff --git a/frontend/discourse/type-tests/models/category-test.ts b/frontend/discourse/type-tests/models/category-test.tsnew file mode 100644index 00000000000..22367b168c2--- /dev/null+++ b/frontend/discourse/type-tests/models/category-test.ts@@ -0,0 +1,286 @@+import type EmberObject from "@ember/object";+import { expectTypeOf } from "expect-type";+import Category, {+ type CategoryAllowedTag,+ type CategoryFields,+ type CategoryLocalization,+ type CategoryPermission,+ type CategoryPostingReviewMode,+ type CategoryRequiredTagGroup,+ type CategorySetting,+ type CategoryStyle,+ type CategoryTypeMetadata,+ type CategoryUpload,+} from "discourse/models/category";+import type RestModel from "discourse/models/rest";+import type {+ default as StoreService,+ ModelFor,+} from "discourse/services/store";++// Independent of the model's own definitions, so a wrong export cannot hide here.+type ExpectedStyle = "square" | "icon" | "emoji";+type ExpectedReviewMode =+ | "no_one"+ | "everyone"+ | "everyone_except"+ | "no_one_except";++interface ExpectedPermission {+ group_name: string;+ permission_type: number | null;+ group_id: number;+}++interface ExpectedAllowedTag {+ id: number | string;+ name: string;+ slug?: string;+}++interface ExpectedRequiredTagGroup {+ min_count: number;+ name?: string | null;+}++type ExpectedUpload =+ | { id: number; url: string; width?: number | null; height?: number | null }+ | { id: null; url: null };++interface ExpectedSetting {+ auto_bump_cooldown_days?: number | null;+ num_auto_bump_daily?: number | null;+ require_reply_approval?: boolean;+ require_topic_approval?: boolean;+ nested_replies_default?: boolean;+ topic_posting_review_mode?: ExpectedReviewMode;+ reply_posting_review_mode?: ExpectedReviewMode;+}++interface ExpectedLocalization {+ id: number;+ locale: string;+ name: string;+ description: string | null;+}++expectTypeOf<CategoryStyle>().toEqualTypeOf<ExpectedStyle>();+expectTypeOf<CategoryPostingReviewMode>().toEqualTypeOf<ExpectedReviewMode>();+expectTypeOf<CategoryPermission>().toEqualTypeOf<ExpectedPermission>();+expectTypeOf<CategoryAllowedTag>().toEqualTypeOf<ExpectedAllowedTag>();+expectTypeOf<CategoryRequiredTagGroup>().toEqualTypeOf<ExpectedRequiredTagGroup>();+expectTypeOf<CategoryUpload>().toEqualTypeOf<ExpectedUpload>();+expectTypeOf<CategorySetting>().toEqualTypeOf<ExpectedSetting>();+expectTypeOf<CategoryLocalization>().toEqualTypeOf<ExpectedLocalization>();++// Category type metadata, as `Categories::Types::Base#metadata` builds it.+declare const typeMetadata: CategoryTypeMetadata;+expectTypeOf(typeMetadata.id).toEqualTypeOf<string>();+expectTypeOf(typeMetadata.name).toEqualTypeOf<string>();+expectTypeOf(typeMetadata.title).toEqualTypeOf<string>();+expectTypeOf(typeMetadata.available).toEqualTypeOf<boolean>();+expectTypeOf(typeMetadata.visible).toEqualTypeOf<boolean>();+// The new-category route stores a projection without these two.+expectTypeOf(typeMetadata.description).toEqualTypeOf<string | undefined>();+expectTypeOf(typeMetadata.icon).toEqualTypeOf<string | null | undefined>();+expectTypeOf(typeMetadata.configuration_schema).not.toBeAny();+expectTypeOf(typeMetadata["type_specific_extra"]).toEqualTypeOf<unknown>();++// Every data field core sends or assigns, with its presence and nullability.+interface ExpectedCategoryFields {+ id?: number;+ name?: string;+ slug?: string | null;+ color?: string;+ text_color?: string;+ style_type?: ExpectedStyle;+ icon?: string | null;+ emoji?: string | null;+ description?: string | null;+ description_text?: string | null;+ description_excerpt?: string | null;+ topic_url?: string | null;+ topic_count?: number;+ post_count?: number;+ position?: number | null;+ read_restricted?: boolean;+ permission?: number | null;+ parent_category_id?: number | null;+ notification_level?: number | null;+ can_edit?: boolean;+ can_delete?: true;+ cannot_delete_reason?: string;+ is_special?: true;+ is_uncategorized?: true;+ topic_template?: string | null;+ topic_title_placeholder?: string | null;+ has_children?: boolean | null;+ subcategory_count?: number | null;+ subcategory_ids?: number[] | null;+ subcategory_list?: object[];+ subcategory_list_style?: string | null;+ sort_order?: string | null;+ sort_ascending?: boolean | null;+ show_subcategory_list?: boolean | null;+ num_featured_topics?: number | null;+ default_view?: string | null;+ default_top_period?: string | null;+ default_list_filter?: string | null;+ minimum_required_tags?: number | null;+ navigate_to_first_post_after_read?: boolean;+ custom_fields?: Record<string, unknown>;+ uploaded_logo?: ExpectedUpload | null;+ uploaded_logo_dark?: ExpectedUpload | null;+ uploaded_background?: ExpectedUpload | null;+ uploaded_background_dark?: ExpectedUpload | null;+ allow_global_tags?: boolean;+ read_only_banner?: string | null;+ form_template_ids?: number[];+ category_types?: Record<string, CategoryTypeMetadata>;+ locale?: string | null;+ available_groups?: string[];+ allowed_tags?: (ExpectedAllowedTag | string)[];+ allowed_tag_groups?: string[];+ auto_close_hours?: number | null;+ auto_close_based_on_last_post?: boolean | null;+ group_permissions?: ExpectedPermission[];+ email_in?: string | null;+ email_in_allow_strangers?: boolean | null;+ mailinglist_mirror?: boolean;+ all_topics_wiki?: boolean;+ allow_unlimited_owner_edits_on_first_post?: boolean;+ allow_badges?: boolean;+ topic_featured_link_allowed?: boolean | null;+ search_priority?: number | null;+ default_slow_mode_seconds?: number | null;+ moderating_group_ids?: number[];+ topic_posting_review_group_ids?: number[];+ reply_posting_review_group_ids?: number[];+ category_setting?: ExpectedSetting | null;+ category_localizations?: ExpectedLocalization[];+ available_category_types?: CategoryTypeMetadata[];+ category_type_settings?: Record<string, unknown>;+ category_type_site_settings?: Record<string, unknown>;+ site_texts?: Record<string, string>;+ topics?: object[];+ topics_day?: number;+ topics_week?: number;+ topics_month?: number;+ topics_year?: number;+ topics_all_time?: number;+ pickAll?: boolean;+ stat?: string;+ statTitle?: string;+ statTotal?: string;+}++declare module "discourse/models/category" {+ interface CategoryFields {+ type_test_plugin_flag?: boolean;+ }+}++expectTypeOf<+ Omit<CategoryFields, "type_test_plugin_flag">+>().toEqualTypeOf<ExpectedCategoryFields>();++declare const category: Category;++// Data fields reach instances; decorated class fields keep these types.+expectTypeOf<+ Pick<Category, keyof ExpectedCategoryFields>+>().toEqualTypeOf<ExpectedCategoryFields>();+expectTypeOf(category.type_test_plugin_flag).toEqualTypeOf<+ boolean | undefined+>();++// Class fields the model declares itself.+expectTypeOf(category.permissions).toEqualTypeOf<+ ExpectedPermission[] | undefined+>();+expectTypeOf(category.categoryTypes).toEqualTypeOf<+ Record<string, CategoryTypeMetadata>+>();+expectTypeOf(category.styleType).toEqualTypeOf<ExpectedStyle | undefined>();+expectTypeOf(category.localizations).not.toBeAny();++// Category adds no member that is, or returns, `any`, on instances or on the+// class. Ember's own `_super` and `metaForProperty` are excluded.+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<Category, EmberObject>>().toEqualTypeOf<never>();+// The inherited `create` is generic in `this`, and inferring its return through a+// conditional type gives `any` even though calls resolve to Category; its result+// is asserted directly below.+expectTypeOf<+ Exclude<OwnAnyKeys<typeof Category, typeof EmberObject>, "create">+>().toEqualTypeOf<never>();++// Accessors with exact types.+expectTypeOf(category.parentCategory).toEqualTypeOf<Category | undefined>();+expectTypeOf(category.subcategories).toEqualTypeOf<Category[]>();+expectTypeOf(category.ancestors).toEqualTypeOf<Category[]>();+expectTypeOf(category.predecessors).toEqualTypeOf<Category[]>();+expectTypeOf(category.descendants).toEqualTypeOf<Category[]>();+expectTypeOf(category.level).toEqualTypeOf<number>();+expectTypeOf(category.path).toEqualTypeOf<string>();+expectTypeOf(category.url).toEqualTypeOf<string>();+expectTypeOf(category.fullSlug).toEqualTypeOf<string>();+expectTypeOf(category.nameLower).toEqualTypeOf<string>();+expectTypeOf(category.isUncategorizedCategory).toEqualTypeOf<boolean>();+expectTypeOf(category.canCreateTopic).toEqualTypeOf<boolean>();+// Transient preview categories have no topic count.+expectTypeOf(category.totalTopicCount).toEqualTypeOf<number | undefined>();++// Static lookups.+expectTypeOf(Category.findById(1)).toEqualTypeOf<Category | undefined>();+expectTypeOf(Category.findById("1")).toEqualTypeOf<Category | undefined>();+expectTypeOf(Category.list()).toEqualTypeOf<Category[]>();+// The server splits the slug path on "/", so callers pass one string.+expectTypeOf(+ Category.asyncFindBySlugPath("parent/child")+).resolves.toEqualTypeOf<Category | undefined>();+// @ts-expect-error the slug path is a single slash-separated string+Category.asyncFindBySlugPath(["parent", "child"]);+// The result shape follows `includeAncestors`.+expectTypeOf(Category.asyncSearch("x")).resolves.toEqualTypeOf<Category[]>();+expectTypeOf(+ Category.asyncSearch("x", { includeAncestors: true })+).resolves.toEqualTypeOf<{+ ancestors: Category[];+ categories: Category[];+ categoriesCount: number;+}>();++// `destroy` deletes through the API and resolves with its response.+expectTypeOf(category.destroy()).resolves.not.toBeAny();+expectTypeOf(category.destroy).returns.toExtend<Promise<unknown>>();+// Category is a proper RestModel subclass, so the typed `create` applies.+expectTypeOf(category).toExtend<RestModel>();+expectTypeOf(Category.create()).toEqualTypeOf<Category>();+expectTypeOf(+ Category.create({ id: 1, name: "Bugs", extra_server_field: true })+).toEqualTypeOf<Category>();+// @ts-expect-error a declared field keeps its type in create attrs+Category.create({ color: 1 });+// @ts-expect-error can_delete is only ever sent as true+Category.create({ can_delete: false });+// @ts-expect-error style_type is one of the three styles+Category.create({ style_type: "circle" });++// The store registry maps "category" to Category.+declare const store: StoreService;+expectTypeOf<ModelFor<"category">>().toEqualTypeOf<Category>();+expectTypeOf(store.createRecord("category")).toEqualTypeOf<Category>();