Skip to content

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

DEV: Convert the topic and post side models to TypeScript (#45170)

Sérgio Saquetim85f82a2ebdf3
diff --git a/frontend/discourse/app/models/action-summary.js b/frontend/discourse/app/models/action-summary.js
deleted file mode 100644
index a628420481b..00000000000
--- a/frontend/discourse/app/models/action-summary.js
+++ /dev/null
@@ -1,97 +0,0 @@
-import { computed } from "@ember/object";
-import { ajax } from "discourse/lib/ajax";
-import { popupAjaxError } from "discourse/lib/ajax-error";
-import RestModel from "discourse/models/rest";
-
-export default class ActionSummary extends RestModel {
- // Remove it
- @computed("can_undo", "can_act")
- get canToggle() {
- return this.can_undo || this.can_act;
- }
-
- removeAction() {
- this.setProperties({
- acted: false,
- count: this.count - 1,
- can_act: true,
- can_undo: false,
- });
- }
-
- togglePromise(post) {
- return this.acted ? this.undo(post) : this.act(post);
- }
-
- toggle(post) {
- if (!this.acted) {
- this.act(post);
- return true;
- } else {
- this.undo(post);
- return false;
- }
- }
-
- // Perform this action
- act(post, opts) {
- if (!opts) {
- opts = {};
- }
-
- // Mark it as acted
- this.setProperties({
- acted: true,
- count: this.count + 1,
- can_act: false,
- can_undo: true,
- });
-
- // Create our post action
- return ajax("/post_actions", {
- type: "POST",
- data: {
- id: this.flagTopic ? this.get("flagTopic.id") : post.get("id"),
- post_action_type_id: this.id,
- message: opts.message,
- is_warning: opts.isWarning,
- take_action: opts.takeAction,
- queue_for_review: opts.queue_for_review,
- flag_topic: this.flagTopic ? true : false,
- },
- returnXHR: true,
- })
- .then((data) => {
- if (!this.flagTopic) {
- post.updateActionsSummary(data.result);
- }
- const remaining = parseInt(
- data.xhr.getResponseHeader("Discourse-Actions-Remaining") || 0,
- 10
- );
- const max = parseInt(
- data.xhr.getResponseHeader("Discourse-Actions-Max") || 0,
- 10
- );
- return { acted: true, remaining, max };
- })
- .catch((error) => {
- popupAjaxError(error);
- this.removeAction(post);
- });
- }
-
- // Undo this action
- undo(post) {
- this.removeAction(post);
-
- // Remove our post action
- return ajax("/post_actions/" + post.get("id"), {
- type: "DELETE",
- data: { post_action_type_id: this.id },
- }).then((result) => {
- post.updateActionsSummary(result);
- return { acted: false };
- });
- }
-}
diff --git a/frontend/discourse/app/models/action-summary.ts b/frontend/discourse/app/models/action-summary.ts
new file mode 100644
index 00000000000..1b8bab0c270
--- /dev/null
+++ b/frontend/discourse/app/models/action-summary.ts
@@ -0,0 +1,136 @@
+import { computed } from "@ember/object";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import type Post from "discourse/models/post";
+import type PostActionType from "discourse/models/post-action-type";
+import RestModel from "discourse/models/rest";
+import type Topic from "discourse/models/topic";
+
+/** Server summary fields and references assigned while hydrating post/topic actions. */
+export interface ActionSummaryFields {
+ id: number;
+ count: number;
+ acted?: boolean;
+ can_act?: boolean;
+ can_undo?: boolean;
+ hidden?: boolean;
+ actionType?: PostActionType;
+ post?: Topic;
+ /** Topic flag actions accept this topic in place of a post. */
+ flagTopic?: Topic;
+}
+
+/** Options forwarded when creating a post or topic action. */
+export interface ActionSummaryOptions {
+ message?: string;
+ isWarning?: boolean;
+ takeAction?: boolean;
+ queue_for_review?: boolean;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface ActionSummary extends ActionSummaryFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class ActionSummary extends RestModel {
+ @computed("can_undo", "can_act")
+ get canToggle() {
+ return this.can_undo || this.can_act;
+ }
+
+ /** Reverts the local summary; the legacy post argument is ignored. */
+ removeAction(post?: Post | Topic): void;
+ removeAction() {
+ this.setProperties({
+ acted: false,
+ count: this.count - 1,
+ can_act: true,
+ can_undo: false,
+ });
+ }
+
+ togglePromise(post: Post) {
+ return this.acted ? this.undo(post) : this.act(post);
+ }
+
+ toggle(post: Post) {
+ if (!this.acted) {
+ this.act(post);
+ return true;
+ } else {
+ this.undo(post);
+ return false;
+ }
+ }
+
+ /** Performs this action, rolling back the optimistic state if the request fails. */
+ act(post: Post | Topic, opts?: ActionSummaryOptions) {
+ if (!opts) {
+ opts = {};
+ }
+
+ // Mark it as acted
+ this.setProperties({
+ acted: true,
+ count: this.count + 1,
+ can_act: false,
+ can_undo: true,
+ });
+
+ // Create our post action
+ // TODO(typescript-pending): ajax has no typed returnXHR response; remove when it does.
+ return (
+ ajax("/post_actions", {
+ type: "POST",
+ data: {
+ id: this.flagTopic ? this.get("flagTopic.id") : post.get("id"),
+ post_action_type_id: this.id,
+ message: opts.message,
+ is_warning: opts.isWarning,
+ take_action: opts.takeAction,
+ queue_for_review: opts.queue_for_review,
+ flag_topic: this.flagTopic ? true : false,
+ },
+ returnXHR: true,
+ }) as Promise<{
+ result: unknown;
+ xhr: Pick<XMLHttpRequest, "getResponseHeader">;
+ }>
+ )
+ .then((data): { acted: true; remaining: number; max: number } => {
+ if (!this.flagTopic) {
+ // Topic flag actions skip this post-only refresh.
+ (post as Post).updateActionsSummary(data.result);
+ }
+ // The `|| 0` fallback is a number, which parseInt coerces.
+ const remaining = parseInt(
+ (data.xhr.getResponseHeader("Discourse-Actions-Remaining") ||
+ 0) as string,
+ 10
+ );
+ const max = parseInt(
+ (data.xhr.getResponseHeader("Discourse-Actions-Max") || 0) as string,
+ 10
+ );
+ return { acted: true, remaining, max };
+ })
+ .catch((error: unknown): undefined => {
+ popupAjaxError(error);
+ this.removeAction(post);
+ });
+ }
+
+ /** Undoes this action and refreshes the post summary from the response. */
+ undo(post: Post) {
+ this.removeAction(post);
+
+ // Remove our post action
+ return ajax("/post_actions/" + post.get("id"), {
+ type: "DELETE",
+ data: { post_action_type_id: this.id },
+ }).then((result: unknown): { acted: false } => {
+ post.updateActionsSummary(result);
+ return { acted: false };
+ });
+ }
+}
diff --git a/frontend/discourse/app/models/pending-post.js b/frontend/discourse/app/models/pending-post.js
deleted file mode 100644
index 5bb6118b5e6..00000000000
--- a/frontend/discourse/app/models/pending-post.js
+++ /dev/null
@@ -1,44 +0,0 @@
-import { tracked } from "@glimmer/tracking";
-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.ts";
-
-export default class PendingPost extends RestModel {
- /** @type {string | import("@ember/template").TrustedHTML | null} */
- expandedExcerpt = null;
-
- truncated = false;
-
- @tracked _postUrlOverride;
-
- init() {
- super.init(...arguments);
- cook(this.raw_text).then((cooked) => {
- this.set("expandedExcerpt", cooked);
- });
- }
-
- @computed("topic_url")
- get postUrl() {
- if (this._postUrlOverride !== undefined) {
- return this._postUrlOverride;
- }
- return this.topic_url;
- }
-
- set postUrl(value) {
- this._postUrlOverride = value;
- }
-
- @computed("username")
- get userUrl() {
- return userPath(this.username.toLowerCase());
- }
-
- @computed("category_id")
- get category() {
- return Category.findById(this.category_id);
- }
-}
diff --git a/frontend/discourse/app/models/pending-post.ts b/frontend/discourse/app/models/pending-post.ts
new file mode 100644
index 00000000000..9b68c4f79b5
--- /dev/null
+++ b/frontend/discourse/app/models/pending-post.ts
@@ -0,0 +1,64 @@
+import { tracked } from "@glimmer/tracking";
+import { computed } from "@ember/object";
+import type { TrustedHTML } from "@ember/template";
+import { cook } from "discourse/lib/text";
+import { userPath } from "discourse/lib/url";
+import RestModel from "discourse/models/rest";
+import Category from "./category.ts";
+
+/** Queued activity records from the pending-post serializer, not topic pending_posts. */
+export interface PendingPostFields {
+ id: number;
+ created_at: string;
+ category_id: number | null;
+ topic_id: number | null;
+ created_by_id: number | null;
+ avatar_template: string | null;
+ username: string | null;
+ name: string | null;
+ topic_url: string | null;
+ raw_text: string | null;
+ title: string | null;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface PendingPost extends PendingPostFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class PendingPost extends RestModel {
+ expandedExcerpt: string | TrustedHTML | null = null;
+
+ truncated = false;
+
+ @tracked _postUrlOverride: string | null | undefined;
+
+ init(...args: Parameters<RestModel["init"]>) {
+ super.init(...args);
+ cook(this.raw_text).then((cooked) => {
+ this.set("expandedExcerpt", cooked);
+ });
+ }
+
+ @computed("topic_url")
+ get postUrl() {
+ if (this._postUrlOverride !== undefined) {
+ return this._postUrlOverride;
+ }
+ return this.topic_url;
+ }
+
+ set postUrl(value: string | null | undefined) {
+ this._postUrlOverride = value;
+ }
+
+ @computed("username")
+ get userUrl(): string {
+ // The activity UI assumes a user is present, even though deleted users serialize null.
+ return userPath(this.username!.toLowerCase());
+ }
+
+ @computed("category_id")
+ get category() {
+ return Category.findById(this.category_id);
+ }
+}
diff --git a/frontend/discourse/app/models/post-action-type.js b/frontend/discourse/app/models/post-action-type.js
deleted file mode 100644
index f87c3120c9a..00000000000
--- a/frontend/discourse/app/models/post-action-type.js
+++ /dev/null
@@ -1,22 +0,0 @@
-import { computed } from "@ember/object";
-import RestModel from "discourse/models/rest";
-import { i18n } from "discourse-i18n";
-
-export const MAX_MESSAGE_LENGTH = 500;
-
-export default class PostActionType extends RestModel {
- @computed("name_key")
- get isIllegal() {
- return this.name_key === "illegal";
- }
-
- @computed()
- get translatedDescription() {
- if (this.system) {
- return i18n(`post.actions.by_you.${this.name_key}`);
- }
- return i18n(`post.actions.by_you.custom`, {
- custom: this.name,
- });
- }
-}
diff --git a/frontend/discourse/app/models/post-action-type.ts b/frontend/discourse/app/models/post-action-type.ts
new file mode 100644
index 00000000000..c2f9dc93a5b
--- /dev/null
+++ b/frontend/discourse/app/models/post-action-type.ts
@@ -0,0 +1,45 @@
+import { computed } from "@ember/object";
+import RestModel from "discourse/models/rest";
+import { i18n } from "discourse-i18n";
+
+export const MAX_MESSAGE_LENGTH = 500;
+
+/** Fields shared by site action types and admin flags, including the legacy serializer. */
+export interface PostActionTypeFields {
+ id: number;
+ name: string;
+ name_key: string;
+ description: string;
+ short_description: string;
+ applies_to: string[];
+ require_message: boolean;
+ enabled: boolean;
+ is_flag: boolean;
+ is_used: boolean;
+ system: boolean;
+ /** Omitted by the legacy flag-settings serializer. */
+ position?: number;
+ /** Omitted by the legacy flag-settings serializer. */
+ auto_action_type?: boolean;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface PostActionType extends PostActionTypeFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class PostActionType extends RestModel {
+ @computed("name_key")
+ get isIllegal() {
+ return this.name_key === "illegal";
+ }
+
+ @computed()
+ get translatedDescription(): string {
+ if (this.system) {
+ return i18n(`post.actions.by_you.${this.name_key}`);
+ }
+ return i18n(`post.actions.by_you.custom`, {
+ custom: this.name,
+ });
+ }
+}
diff --git a/frontend/discourse/app/models/post-localization.js b/frontend/discourse/app/models/post-localization.js
deleted file mode 100644
index 76432db062f..00000000000
--- a/frontend/discourse/app/models/post-localization.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import { ajax } from "discourse/lib/ajax";
-import RestModel from "discourse/models/rest";
-
-export default class PostLocalization extends RestModel {
- static find(postId) {
- return ajax(`/post_localizations/${postId}`, {
- type: "GET",
- data: {
- post_id: postId,
- },
- });
- }
-
- static createOrUpdate(postId, locale, raw) {
- return ajax("/post_localizations/create_or_update", {
- type: "POST",
- data: {
- post_id: postId,
- locale,
- raw,
- },
- });
- }
-
- static updateLocale(postId, locale) {
- return ajax(`/post_localizations/${postId}/locale`, {
- type: "PUT",
- data: { locale: locale ?? "" },
- });
- }
-
- static destroy(postId, locale) {
- return ajax("/post_localizations/destroy", {
- type: "DELETE",
- data: {
- post_id: postId,
- locale,
- },
- });
- }
-}
diff --git a/frontend/discourse/app/models/post-localization.ts b/frontend/discourse/app/models/post-localization.ts
new file mode 100644
index 00000000000..e290f3cc7a8
--- /dev/null
+++ b/frontend/discourse/app/models/post-localization.ts
@@ -0,0 +1,62 @@
+import { ajax } from "discourse/lib/ajax";
+import RestModel from "discourse/models/rest";
+import type { TopicLocalizationData } from "discourse/models/topic-localization";
+
+/** Plain localization responses; these helpers do not instantiate model records. */
+export interface PostLocalizationData {
+ id: number;
+ post_id: number;
+ post_version: number;
+ locale: string;
+ raw: string;
+ /** Included only when a first post has a matching topic locale. */
+ topic_localization?: TopicLocalizationData;
+}
+
+export default class PostLocalization extends RestModel {
+ static find(
+ postId: number
+ ): Promise<{ post_localizations: PostLocalizationData[] }> {
+ return ajax(`/post_localizations/${postId}`, {
+ type: "GET",
+ data: {
+ post_id: postId,
+ },
+ });
+ }
+
+ static createOrUpdate(
+ postId: number,
+ locale: string,
+ raw: string
+ ): Promise<{ success: "OK" }> {
+ return ajax("/post_localizations/create_or_update", {
+ type: "POST",
+ data: {
+ post_id: postId,
+ locale,
+ raw,
+ },
+ });
+ }
+
+ static updateLocale(
+ postId: number,
+ locale: string | null | undefined
+ ): Promise<{ locale: string | null }> {
+ return ajax(`/post_localizations/${postId}/locale`, {
+ type: "PUT",
+ data: { locale: locale ?? "" },
+ });
+ }
+
+ static destroy(postId: number, locale: string): Promise<void> {
+ return ajax("/post_localizations/destroy", {
+ type: "DELETE",
+ data: {
+ post_id: postId,
+ locale,
+ },
+ });
+ }
+}
diff --git a/frontend/discourse/app/models/published-page.js b/frontend/discourse/app/models/published-page.js
deleted file mode 100644
index 63a455f6a80..00000000000
--- a/frontend/discourse/app/models/published-page.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import { computed } from "@ember/object";
-import { getAbsoluteURL } from "discourse/lib/get-url";
-import RestModel from "discourse/models/rest";
-
-export default class PublishedPage extends RestModel {
- @computed("slug")
- get url() {
- return getAbsoluteURL(`/pub/${this.slug}`);
- }
-}
diff --git a/frontend/discourse/app/models/published-page.ts b/frontend/discourse/app/models/published-page.ts
new file mode 100644
index 00000000000..6999ad06689
--- /dev/null
+++ b/frontend/discourse/app/models/published-page.ts
@@ -0,0 +1,22 @@
+import { computed } from "@ember/object";
+import { getAbsoluteURL } from "discourse/lib/get-url";
+import RestModel from "discourse/models/rest";
+
+/** Publication data; id identifies the topic rather than the publication row. */
+export interface PublishedPageFields {
+ id: number;
+ slug: string;
+ /** Local drafts copy a topic that may not have a public property. */
+ public?: boolean;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface PublishedPage extends PublishedPageFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class PublishedPage extends RestModel {
+ @computed("slug")
+ get url(): string {
+ return getAbsoluteURL(`/pub/${this.slug}`);
+ }
+}
diff --git a/frontend/discourse/app/models/site.ts b/frontend/discourse/app/models/site.ts
index 1a03d13f454..07a1fd351d9 100644
--- a/frontend/discourse/app/models/site.ts
+++ b/frontend/discourse/app/models/site.ts
@@ -507,12 +507,7 @@ export default class Site extends RestModel {
if (!postActionTypes) {
return [];
}
- // TODO(typescript-pending): PostActionType doesn't type its server fields; remove when it does.
- return trackedArray(
- postActionTypes.filter(
- (type) => (type as PostActionType & { is_flag?: boolean }).is_flag
- )
- );
+ return trackedArray(postActionTypes.filter((type) => type.is_flag));
}
// Sort subcategories under parents
diff --git a/frontend/discourse/app/models/topic-localization.js b/frontend/discourse/app/models/topic-localization.ts
similarity index 51%
rename from frontend/discourse/app/models/topic-localization.js
rename to frontend/discourse/app/models/topic-localization.ts
index d89d1de2358..d2d1ebafef5 100644
--- a/frontend/discourse/app/models/topic-localization.js
+++ b/frontend/discourse/app/models/topic-localization.ts
@@ -1,12 +1,28 @@
import { ajax } from "discourse/lib/ajax";
import RestModel from "discourse/models/rest";
+/** Plain response shared by the topic endpoint and nested post localizations. */
+export interface TopicLocalizationData {
+ id: number;
+ topic_id: number;
+ locale: string;
+ title: string;
+ fancy_title: string;
+}
+
export default class TopicLocalization extends RestModel {
- static fetch(topicId, locale) {
+ static fetch(
+ topicId: number,
+ locale: string
+ ): Promise<TopicLocalizationData> {
return ajax(`/topic_localizations/${topicId}/${locale}`);
}
- static createOrUpdate(topicId, locale, title) {
+ static createOrUpdate(
+ topicId: number,
+ locale: string,
+ title: string
+ ): Promise<{ success: "OK" }> {
return ajax("/topic_localizations/create_or_update", {
type: "POST",
data: {
@@ -17,14 +33,17 @@ export default class TopicLocalization extends RestModel {
});
}
- static updateLocale(topicId, locale) {
+ static updateLocale(
+ topicId: number,
+ locale: string | null | undefined
+ ): Promise<{ locale: string | null }> {
return ajax(`/topic_localizations/${topicId}/locale`, {
type: "PUT",
data: { locale: locale ?? "" },
});
}
- static destroy(topicId, locale) {
+ static destroy(topicId: number, locale: string): Promise<void> {
return ajax("/topic_localizations/destroy", {
type: "DELETE",
data: {
diff --git a/frontend/discourse/app/models/topic-timer.js b/frontend/discourse/app/models/topic-timer.js
deleted file mode 100644
index 618219f36f5..00000000000
--- a/frontend/discourse/app/models/topic-timer.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import { ajax } from "discourse/lib/ajax";
-import RestModel from "discourse/models/rest";
-
-export default class TopicTimer extends RestModel {
- static update(
- topicId,
- time,
- basedOnLastPost,
- statusType,
- categoryId,
- durationMinutes
- ) {
- let data = {
- time,
- status_type: statusType,
- };
-
- if (basedOnLastPost) {
- data.based_on_last_post = basedOnLastPost;
- }
- if (categoryId) {
- data.category_id = categoryId;
- }
- if (durationMinutes) {
- data.duration_minutes = durationMinutes;
- }
-
- return ajax({
- url: `/t/${topicId}/timer`,
- type: "POST",
- data,
- });
- }
-}
diff --git a/frontend/discourse/app/models/topic-timer.ts b/frontend/discourse/app/models/topic-timer.ts
new file mode 100644
index 00000000000..185ad02212e
--- /dev/null
+++ b/frontend/discourse/app/models/topic-timer.ts
@@ -0,0 +1,68 @@
+import { ajax } from "discourse/lib/ajax";
+import RestModel from "discourse/models/rest";
+
+/** The timer modal initially supplies only status_type. */
+export interface TopicTimerFields {
+ status_type: string;
+ /** Whatever the time picker produced, before it is sent to the server. */
+ updateTime?: unknown;
+ id?: number;
+ execute_at?: string | null;
+ duration_minutes?: number | null;
+ based_on_last_post?: boolean;
+ category_id?: number | null;
+}
+
+/** The timer update endpoint returns a status hash, not a serialized timer. */
+export interface TopicTimerUpdateResult {
+ success: "OK";
+ execute_at: string | null;
+ duration_minutes: number | null;
+ based_on_last_post: boolean | null;
+ category_id: number | null;
+ closed: boolean;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface TopicTimer extends TopicTimerFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class TopicTimer extends RestModel {
+ /** Sends `time` as given; the time picker can produce more than formatted dates. */
+ static update(
+ topicId: number,
+ time: unknown,
+ basedOnLastPost: boolean | null | undefined,
+ statusType: string,
+ categoryId: number | null | undefined,
+ durationMinutes: number | null | undefined
+ ): Promise<TopicTimerUpdateResult> {
+ // eslint-disable-next-line prefer-const -- Preserve the original Babel output.
+ let data: {
+ time: unknown;
+ status_type: string;
+ based_on_last_post?: boolean;
+ category_id?: number;
+ duration_minutes?: number;
+ } = {
+ time,
+ status_type: statusType,
+ };
+
+ if (basedOnLastPost) {
+ data.based_on_last_post = basedOnLastPost;
+ }
+ if (categoryId) {
+ data.category_id = categoryId;
+ }
+ if (durationMinutes) {
+ data.duration_minutes = durationMinutes;
+ }
+
+ return ajax({
+ url: `/t/${topicId}/timer`,
+ type: "POST",
+ data,
+ });
+ }
+}
diff --git a/frontend/discourse/app/models/topic.ts b/frontend/discourse/app/models/topic.ts
index 5329c52c688..bcf6368f9f1 100644
--- a/frontend/discourse/app/models/topic.ts
+++ b/frontend/discourse/app/models/topic.ts
@@ -29,7 +29,9 @@ import {
applyValueTransformer,
} from "discourse/lib/transformer";
import DiscourseURL, { userPath } from "discourse/lib/url";
-import ActionSummary from "discourse/models/action-summary";
+import ActionSummary, {
+ type ActionSummaryFields,
+} from "discourse/models/action-summary";
import type Archetype from "discourse/models/archetype";
import Bookmark from "discourse/models/bookmark";
import type Post from "discourse/models/post";
@@ -351,24 +353,17 @@ export default class Topic extends RestModel {
static createActionSummary(result: Topic): void {
if (result.actions_summary) {
const lookup = EmberObject.create();
- // TODO(typescript-pending): ActionSummary omits create-assigned fields; remove when ActionSummary is typed.
- result.actions_summary = (
- result.actions_summary as (TopicActionSummaryData & {
- post: Topic;
- actionType: NonNullable<ReturnType<Site["postActionTypeById"]>> & {
- name_key: string;
- };
- })[]
- ).map((a) => {
- a.post = result;
- // TODO(typescript-pending): PostActionType omits name_key; remove when PostActionType is typed.
- a.actionType = Site.current().postActionTypeById(
- a.id
- ) as typeof a.actionType;
- const actionSummary = ActionSummary.create(a as typeof a & RestPayload);
- lookup.set(a.actionType.get("name_key"), actionSummary);
- return actionSummary;
- });
+ result.actions_summary = result.actions_summary.map(
+ (a: ActionSummaryFields) => {
+ a.post = result;
+ a.actionType = Site.current().postActionTypeById(a.id)!;
+ const actionSummary = ActionSummary.create(
+ a as typeof a & RestPayload
+ );
+ lookup.set(a.actionType.get("name_key"), actionSummary);
+ return actionSummary;
+ }
+ );
result.set("actionByName", lookup);
}
}
@@ -1413,13 +1408,12 @@ export default class Topic extends RestModel {
removeValuesFromArray(keys, ["details", "post_stream"]);
if (json.published_page) {
- // TODO(typescript-pending): store has no published-page registry entry; remove when PublishedPage is typed.
this.set(
"publishedPage",
this.store.createRecord(
"published-page",
json.published_page as TopicPublishedPage & RestPayload
- ) as PublishedPage
+ )
);
}
}
diff --git a/frontend/discourse/app/services/store.ts b/frontend/discourse/app/services/store.ts
index 6e5de75c9dc..dc77233c566 100644
--- a/frontend/discourse/app/services/store.ts
+++ b/frontend/discourse/app/services/store.ts
@@ -9,6 +9,8 @@ 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 type PendingPost from "discourse/models/pending-post";
+import type PublishedPage from "discourse/models/published-page";
import RestModel, {
type RestModelAttrs,
type RestModelClass,
@@ -27,6 +29,8 @@ 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;
+ "pending-post": PendingPost;
+ "published-page": PublishedPage;
site: Site;
topic: Topic;
"user-draft": UserDraft;
diff --git a/frontend/discourse/type-tests/models/action-summary-test.ts b/frontend/discourse/type-tests/models/action-summary-test.ts
new file mode 100644
index 00000000000..3f388a3dde4
--- /dev/null
+++ b/frontend/discourse/type-tests/models/action-summary-test.ts
@@ -0,0 +1,70 @@
+import { expectTypeOf } from "expect-type";
+import ActionSummary from "discourse/models/action-summary";
+import type Post from "discourse/models/post";
+import PostActionType from "discourse/models/post-action-type";
+import type RestModel from "discourse/models/rest";
+import type Topic from "discourse/models/topic";
+
+declare const post: Post;
+declare const topic: Topic;
+declare const summary: ActionSummary;
+
+expectTypeOf(summary).toExtend<RestModel>();
+expectTypeOf(summary.id).toEqualTypeOf<number>();
+// Every construction path supplies a count: posts default it to 0 before
+// `create`, and topic entries always send 0.
+expectTypeOf(summary.count).toEqualTypeOf<number>();
+// The server sends these only as `true`, but the client writes `false`.
+expectTypeOf(summary.acted).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(summary.can_act).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(summary.can_undo).toEqualTypeOf<boolean | undefined>();
+// Only topic-level entries carry `hidden`.
+expectTypeOf(summary.hidden).toEqualTypeOf<boolean | undefined>();
+// Client-assigned before `create`; the site lookup can miss.
+expectTypeOf(summary.actionType).toEqualTypeOf<PostActionType | undefined>();
+expectTypeOf(summary.post).toEqualTypeOf<Topic | undefined>();
+expectTypeOf(summary.flagTopic).toEqualTypeOf<Topic | undefined>();
+expectTypeOf(summary.canToggle).toEqualTypeOf<boolean | undefined>();
+
+expectTypeOf(summary.toggle(post)).toEqualTypeOf<boolean>();
+expectTypeOf(summary.undo(post)).resolves.toEqualTypeOf<{ acted: false }>();
+expectTypeOf(summary.act(post)).resolves.toEqualTypeOf<
+ { acted: true; remaining: number; max: number } | undefined
+>();
+// Either branch can run, so the result is the union of both.
+expectTypeOf<
+ Awaited<ReturnType<ActionSummary["togglePromise"]>>
+>().toEqualTypeOf<
+ { acted: false } | { acted: true; remaining: number; max: number } | undefined
+>();
+summary.act(post, {
+ message: "x",
+ isWarning: true,
+ takeAction: false,
+ queue_for_review: true,
+});
+// Topic flags pass the topic itself.
+summary.act(topic, { message: "A topic flag" });
+// @ts-expect-error act options are checked
+summary.act(post, { isWarning: "yes" });
+// The failure path passes the post through; the parameter stays optional.
+summary.removeAction();
+summary.removeAction(post);
+
+// The shapes core passes to `create`.
+ActionSummary.create({
+ id: 2,
+ count: 0,
+ acted: true,
+ can_undo: true,
+ actionType: PostActionType.create({ id: 2 }),
+});
+ActionSummary.create({
+ id: 4,
+ count: 0,
+ hidden: false,
+ can_act: false,
+ post: topic,
+});
+// @ts-expect-error count is a number
+ActionSummary.create({ id: 2, count: "1" });
diff --git a/frontend/discourse/type-tests/models/pending-post-test.ts b/frontend/discourse/type-tests/models/pending-post-test.ts
new file mode 100644
index 00000000000..7c78acf538e
--- /dev/null
+++ b/frontend/discourse/type-tests/models/pending-post-test.ts
@@ -0,0 +1,35 @@
+import type { TrustedHTML } from "@ember/template";
+import { expectTypeOf } from "expect-type";
+import type Category from "discourse/models/category";
+import type PendingPost from "discourse/models/pending-post";
+import StoreService, { ModelFor } from "discourse/services/store";
+
+declare const store: StoreService;
+declare const pending: PendingPost;
+
+expectTypeOf(pending.id).toEqualTypeOf<number>();
+expectTypeOf(pending.created_at).toEqualTypeOf<string>();
+expectTypeOf(pending.category_id).toEqualTypeOf<number | null>();
+expectTypeOf(pending.topic_id).toEqualTypeOf<number | null>();
+expectTypeOf(pending.created_by_id).toEqualTypeOf<number | null>();
+expectTypeOf(pending.avatar_template).toEqualTypeOf<string | null>();
+expectTypeOf(pending.username).toEqualTypeOf<string | null>();
+expectTypeOf(pending.name).toEqualTypeOf<string | null>();
+expectTypeOf(pending.topic_url).toEqualTypeOf<string | null>();
+expectTypeOf(pending.raw_text).toEqualTypeOf<string | null>();
+expectTypeOf(pending.title).toEqualTypeOf<string | null>();
+expectTypeOf(pending.truncated).toEqualTypeOf<boolean>();
+expectTypeOf(pending.expandedExcerpt).toEqualTypeOf<
+ string | TrustedHTML | null
+>();
+expectTypeOf(pending.postUrl).toEqualTypeOf<string | null | undefined>();
+pending.postUrl = "/t/x/1";
+pending.postUrl = null;
+pending.postUrl = undefined;
+expectTypeOf(pending.userUrl).toEqualTypeOf<string>();
+expectTypeOf(pending.category).toEqualTypeOf<Category | undefined>();
+
+expectTypeOf<ModelFor<"pending-post">>().toEqualTypeOf<PendingPost>();
+expectTypeOf(
+ store.findAll("pending-post", { username: "x" })
+).resolves.not.toBeAny();
diff --git a/frontend/discourse/type-tests/models/post-action-type-test.ts b/frontend/discourse/type-tests/models/post-action-type-test.ts
new file mode 100644
index 00000000000..00518801a55
--- /dev/null
+++ b/frontend/discourse/type-tests/models/post-action-type-test.ts
@@ -0,0 +1,22 @@
+import { expectTypeOf } from "expect-type";
+import type PostActionType from "discourse/models/post-action-type";
+
+declare const flag: PostActionType;
+
+expectTypeOf(flag.id).toEqualTypeOf<number>();
+expectTypeOf(flag.name).toEqualTypeOf<string>();
+// A save callback always sets it, so it is never null in a payload.
+expectTypeOf(flag.name_key).toEqualTypeOf<string>();
+expectTypeOf(flag.description).toEqualTypeOf<string>();
+expectTypeOf(flag.short_description).toEqualTypeOf<string>();
+expectTypeOf(flag.applies_to).toEqualTypeOf<string[]>();
+expectTypeOf(flag.require_message).toEqualTypeOf<boolean>();
+expectTypeOf(flag.enabled).toEqualTypeOf<boolean>();
+expectTypeOf(flag.is_flag).toEqualTypeOf<boolean>();
+expectTypeOf(flag.is_used).toEqualTypeOf<boolean>();
+expectTypeOf(flag.system).toEqualTypeOf<boolean>();
+// The legacy flag-settings serializer omits these two.
+expectTypeOf(flag.position).toEqualTypeOf<number | undefined>();
+expectTypeOf(flag.auto_action_type).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(flag.isIllegal).toEqualTypeOf<boolean>();
+expectTypeOf(flag.translatedDescription).toEqualTypeOf<string>();
diff --git a/frontend/discourse/type-tests/models/post-localization-test.ts b/frontend/discourse/type-tests/models/post-localization-test.ts
new file mode 100644
index 00000000000..3f62ea0aec4
--- /dev/null
+++ b/frontend/discourse/type-tests/models/post-localization-test.ts
@@ -0,0 +1,30 @@
+import { expectTypeOf } from "expect-type";
+import PostLocalization from "discourse/models/post-localization";
+
+expectTypeOf(PostLocalization.find).returns.resolves.toEqualTypeOf<{
+ post_localizations: {
+ id: number;
+ post_id: number;
+ post_version: number;
+ locale: string;
+ raw: string;
+ topic_localization?: {
+ id: number;
+ topic_id: number;
+ locale: string;
+ title: string;
+ fancy_title: string;
+ };
+ }[];
+}>();
+expectTypeOf(PostLocalization.updateLocale).returns.resolves.toEqualTypeOf<{
+ locale: string | null;
+}>();
+expectTypeOf(PostLocalization.createOrUpdate).returns.resolves.toEqualTypeOf<{
+ success: "OK";
+}>();
+expectTypeOf(PostLocalization.destroy).returns.resolves.toEqualTypeOf<void>();
+
+PostLocalization.updateLocale(1, null);
+PostLocalization.createOrUpdate(1, "ja", "raw");
+PostLocalization.destroy(1, "ja");
diff --git a/frontend/discourse/type-tests/models/published-page-test.ts b/frontend/discourse/type-tests/models/published-page-test.ts
new file mode 100644
index 00000000000..3937fbc0277
--- /dev/null
+++ b/frontend/discourse/type-tests/models/published-page-test.ts
@@ -0,0 +1,21 @@
+import { expectTypeOf } from "expect-type";
+import type PublishedPage from "discourse/models/published-page";
+import StoreService, { ModelFor } from "discourse/services/store";
+
+declare const store: StoreService;
+declare const page: PublishedPage;
+
+expectTypeOf(page.id).toEqualTypeOf<number>();
+expectTypeOf(page.slug).toEqualTypeOf<string>();
+// A new page starts from the topic's properties, which can lack `public`.
+expectTypeOf(page.public).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(page.url).toEqualTypeOf<string>();
+
+expectTypeOf<ModelFor<"published-page">>().toEqualTypeOf<PublishedPage>();
+expectTypeOf<ModelFor<"published_page">>().toEqualTypeOf<PublishedPage>();
+expectTypeOf(
+ store.createRecord("published_page", { id: 1, slug: "s", public: false })
+).toEqualTypeOf<PublishedPage>();
+expectTypeOf(
+ store.find("published_page", 1)
+).resolves.toEqualTypeOf<PublishedPage>();
diff --git a/frontend/discourse/type-tests/models/topic-localization-test.ts b/frontend/discourse/type-tests/models/topic-localization-test.ts
new file mode 100644
index 00000000000..4b3ef91319d
--- /dev/null
+++ b/frontend/discourse/type-tests/models/topic-localization-test.ts
@@ -0,0 +1,21 @@
+import { expectTypeOf } from "expect-type";
+import TopicLocalization from "discourse/models/topic-localization";
+
+expectTypeOf(TopicLocalization.fetch).returns.resolves.toEqualTypeOf<{
+ id: number;
+ topic_id: number;
+ locale: string;
+ title: string;
+ fancy_title: string;
+}>();
+expectTypeOf(TopicLocalization.updateLocale).returns.resolves.toEqualTypeOf<{
+ locale: string | null;
+}>();
+expectTypeOf(TopicLocalization.createOrUpdate).returns.resolves.toEqualTypeOf<{
+ success: "OK";
+}>();
+expectTypeOf(TopicLocalization.destroy).returns.resolves.toEqualTypeOf<void>();
+
+TopicLocalization.updateLocale(1, undefined);
+TopicLocalization.createOrUpdate(1, "ja", "title");
+TopicLocalization.destroy(1, "ja");
diff --git a/frontend/discourse/type-tests/models/topic-timer-test.ts b/frontend/discourse/type-tests/models/topic-timer-test.ts
new file mode 100644
index 00000000000..339c649134e
--- /dev/null
+++ b/frontend/discourse/type-tests/models/topic-timer-test.ts
@@ -0,0 +1,27 @@
+import { expectTypeOf } from "expect-type";
+import TopicTimer from "discourse/models/topic-timer";
+
+declare const timer: TopicTimer;
+
+// The modal creates it with only a status type.
+expectTypeOf(timer.status_type).toEqualTypeOf<string>();
+expectTypeOf(timer.id).toEqualTypeOf<number | undefined>();
+expectTypeOf(timer.execute_at).toEqualTypeOf<string | null | undefined>();
+expectTypeOf(timer.duration_minutes).toEqualTypeOf<number | null | undefined>();
+expectTypeOf(timer.based_on_last_post).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(timer.category_id).toEqualTypeOf<number | null | undefined>();
+TopicTimer.create({ status_type: "close" });
+
+// `POST /t/:id/timer` answers with this hash, not a serialized timer.
+expectTypeOf(TopicTimer.update).returns.resolves.toEqualTypeOf<{
+ success: "OK";
+ execute_at: string | null;
+ duration_minutes: number | null;
+ based_on_last_post: boolean | null;
+ category_id: number | null;
+ closed: boolean;
+}>();
+TopicTimer.update(1, "2026-10-28 08:00", false, "close", null, null);
+TopicTimer.update(1, 24, true, "open", 5, 60);
+// Clearing a timer sends no time.
+TopicTimer.update(1, null, false, "close", null, null);