Skip to content

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

DEV: Convert admin site setting and theme models to TypeScript (#45203)

Sérgio Saquetim5ea11fd6e0c6
diff --git a/frontend/discourse/admin/models/site-setting.js b/frontend/discourse/admin/models/site-setting.js
deleted file mode 100644
index e20a833bb08..00000000000
--- a/frontend/discourse/admin/models/site-setting.js
+++ /dev/null
@@ -1,253 +0,0 @@
-import { tracked } from "@glimmer/tracking";
-import EmberObject, { computed, set } from "@ember/object";
-import { trustHTML } from "@ember/template";
-import {
- DEFAULT_USER_PREFERENCES,
- SITE_SETTING_REQUIRES_CONFIRMATION_TYPES,
-} from "discourse/admin/lib/constants";
-import SettingObjectHelper from "discourse/admin/lib/setting-object-helper";
-import { ajax } from "discourse/lib/ajax";
-import BufferedProxy from "discourse/lib/buffered-proxy";
-import { bind } from "discourse/lib/decorators";
-import { deepEqual } from "discourse/lib/object";
-import { applyValueTransformer } from "discourse/lib/transformer";
-import { i18n } from "discourse-i18n";
-
-/**
- * `true` when a value is the *enabled* state of a bool site setting: boolean
- * `true`, the string `"true"`, or any value whose `String()` is exactly `"true"`.
- * This is not general JS truthiness: `"false"` is not enabled, and is safe
- * for `null` / `undefined` (unlike calling `.toString()` on the value).
- */
-export function isSettingValueTrue(value) {
- return String(value) === "true";
-}
-
-const AUTO_REFRESH_ON_SAVE = [
- "logo",
- "mobile_logo",
- "base_font",
- "heading_font",
- "default_text_size",
-];
-
-export default class SiteSetting extends EmberObject {
- static async findAll(params = {}) {
- let settings = await ajax("/admin/site_settings", { data: params });
- const categories = {};
- settings.site_settings.forEach(function (s) {
- if (!categories[s.category]) {
- categories[s.category] = [];
- }
- categories[s.category].push(SiteSetting.create(s));
- });
- return Object.keys(categories).map(function (n) {
- return {
- nameKey: n,
- name: i18n("admin.site_settings.categories." + n),
- siteSettings: categories[n],
- };
- });
- }
-
- static findByName(name) {
- return ajax("/admin/site_settings", {
- data: {
- names: [name],
- },
- }).then(function (settings) {
- const setting = settings.site_settings.find((s) => s.setting === name);
- return SiteSetting.create(setting);
- });
- }
-
- static update(key, value, opts = {}) {
- const data = {};
- data[key] = value;
-
- if (opts["updateExistingUsers"] === true) {
- data["update_existing_user"] = true;
- }
-
- return ajax(`/admin/site_settings/${key}`, { type: "PUT", data });
- }
-
- static bulkUpdate(settings) {
- return ajax(`/admin/site_settings/bulk_update.json`, {
- type: "PUT",
- data: { settings },
- });
- }
-
- @tracked isSaving = false;
-
- /** @type {string | import("@ember/template").TrustedHTML | null} */
- @tracked validationMessage = null;
- updateExistingUsers = false;
-
- settingObjectHelper = new SettingObjectHelper(this);
-
- constructor() {
- super(...arguments);
- this.buffered = /** @type {BufferedProxy} */ (
- BufferedProxy.create({ content: this })
- );
- }
-
- @computed("settingObjectHelper.overridden")
- get overridden() {
- return this.settingObjectHelper?.overridden;
- }
-
- set overridden(value) {
- set(this, "settingObjectHelper.overridden", value);
- }
-
- @computed("settingObjectHelper.computedValueProperty")
- get computedValueProperty() {
- return this.settingObjectHelper?.computedValueProperty;
- }
-
- set computedValueProperty(value) {
- set(this, "settingObjectHelper.computedValueProperty", value);
- }
-
- @computed("settingObjectHelper.computedNameProperty")
- get computedNameProperty() {
- return this.settingObjectHelper?.computedNameProperty;
- }
-
- set computedNameProperty(value) {
- set(this, "settingObjectHelper.computedNameProperty", value);
- }
-
- @computed("settingObjectHelper.validValues")
- get validValues() {
- return this.settingObjectHelper?.validValues;
- }
-
- set validValues(value) {
- set(this, "settingObjectHelper.validValues", value);
- }
-
- @computed("settingObjectHelper.allowsNone")
- get allowsNone() {
- return applyValueTransformer(
- "site-setting-allows-none",
- this.settingObjectHelper?.allowsNone,
- { siteSetting: this }
- );
- }
-
- set allowsNone(value) {
- set(this, "settingObjectHelper.allowsNone", value);
- }
-
- @computed("settingObjectHelper.anyValue")
- get anyValue() {
- return this.settingObjectHelper?.anyValue;
- }
-
- set anyValue(value) {
- set(this, "settingObjectHelper.anyValue", value);
- }
-
- @computed("setting")
- get staffLogFilter() {
- if (!this.setting) {
- return;
- }
-
- return {
- subject: this.setting,
- action_name: "change_site_setting",
- };
- }
-
- get settingSubtype() {
- if (this.list_type) {
- return;
- }
-
- if (this.textarea) {
- return "textarea";
- }
-
- if (this.secret) {
- return "password";
- }
- }
-
- get definition() {
- return {
- key: this.setting,
- label: this.humanized_name || this.setting,
- description: trustHTML(this.description),
- type: this.type,
- list_type: this.list_type,
- subtype: this.settingSubtype,
- min: this.min,
- max: this.max,
- choices: this.choices,
- valid_values: this.validValues,
- allows_none: !!this.allowsNone,
- allow_any: this.allow_any,
- mandatory_values: this.mandatory_values,
- disallowed_groups: this.disallowed_groups,
- currentSavedValue: this.value,
- };
- }
-
- get pendingValue() {
- return this.buffered.get("value");
- }
-
- get hasPendingChanges() {
- const pending = this.pendingValue ?? "";
- const saved = this.value ?? "";
-
- if (this.json_schema || this.schema || this.objects_schema) {
- return !deepEqual(pending, saved);
- }
- return pending.toString() !== saved.toString();
- }
-
- get requiresConfirmation() {
- switch (this.requires_confirmation) {
- case SITE_SETTING_REQUIRES_CONFIRMATION_TYPES.simple:
- return true;
- case SITE_SETTING_REQUIRES_CONFIRMATION_TYPES.simple_on_enable: {
- const val = this.buffered?.get("value");
- return isSettingValueTrue(val);
- }
- case SITE_SETTING_REQUIRES_CONFIRMATION_TYPES.simple_on_disable: {
- const val = this.buffered?.get("value");
- return !isSettingValueTrue(val);
- }
- default:
- return false;
- }
- }
-
- get requiresReload() {
- return AUTO_REFRESH_ON_SAVE.includes(this.setting);
- }
-
- get affectsExistingUsers() {
- return DEFAULT_USER_PREFERENCES.includes(this.setting);
- }
-
- commit() {
- this.validationMessage = null;
- this.buffered.applyChanges();
- }
-
- rollback() {
- this.buffered.discardChanges();
- }
-
- @bind
- setUpdateExistingUsers(value) {
- this.updateExistingUsers = value;
- }
-}
diff --git a/frontend/discourse/admin/models/site-setting.ts b/frontend/discourse/admin/models/site-setting.ts
new file mode 100644
index 00000000000..54447876de4
--- /dev/null
+++ b/frontend/discourse/admin/models/site-setting.ts
@@ -0,0 +1,417 @@
+import { tracked } from "@glimmer/tracking";
+import EmberObject, { computed, set } from "@ember/object";
+import type ObjectProxy from "@ember/object/proxy";
+import { type TrustedHTML, trustHTML } from "@ember/template";
+import {
+ DEFAULT_USER_PREFERENCES,
+ SITE_SETTING_REQUIRES_CONFIRMATION_TYPES,
+} from "discourse/admin/lib/constants";
+import SettingObjectHelper from "discourse/admin/lib/setting-object-helper";
+import type Theme from "discourse/admin/models/theme";
+import { ajax } from "discourse/lib/ajax";
+import BufferedProxy from "discourse/lib/buffered-proxy";
+import { bind } from "discourse/lib/decorators";
+import { deepEqual } from "discourse/lib/object";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import type { CategoryFields } from "discourse/models/category";
+import { i18n } from "discourse-i18n";
+
+/** JSON-compatible values, including parsed schema edits and theme setting values. */
+export type SettingValue =
+ | string
+ | number
+ | boolean
+ | null
+ | SettingValue[]
+ | { [key: string]: SettingValue };
+
+/** Enum providers may attach additional metadata to their choices. */
+export type SettingChoice =
+ | string
+ | number
+ | boolean
+ | {
+ name?: string;
+ value?: SettingValue;
+ [key: string]: unknown;
+ };
+
+/** Schema keywords are configuration-defined, including nested object schemas. */
+export type SettingSchema = Record<string, unknown>;
+
+/** Shared optional metadata; configuration can attach it independently of the type. */
+export interface SettingTypeMetadata {
+ min?: number;
+ max?: number;
+ choices?: SettingChoice[];
+ valid_values?: SettingChoice[];
+ translate_names?: boolean;
+ list_type?: string | null;
+ textarea?: boolean;
+ allow_any?: boolean;
+ schema?: SettingSchema;
+ json_schema?: SettingSchema;
+ objects_schema?: SettingSchema;
+ authorized_extensions?: string;
+ max_file_size_kb?: number;
+}
+
+/** The admin site-settings endpoint stringifies values even for numeric and boolean types. */
+export interface SiteSettingWireRecord extends SettingTypeMetadata {
+ setting: string;
+ type: string;
+ humanized_name: string;
+ description: string;
+ category: string;
+ value: string;
+ /** Seeded upload defaults can resolve to no upload. */
+ default: string | null;
+ keywords?: string[];
+ primary_area?: string | null;
+ preview?: string | null;
+ secret?: boolean;
+ placeholder?: string | Record<string, unknown> | null;
+ mandatory_values?: string | null;
+ disallowed_groups?: string | null;
+ requires_confirmation?: string | null;
+ themeable?: boolean | null;
+ depends_on?: string[];
+ depends_on_humanized_names?: string[];
+ depends_behavior?: string | null;
+ depends_on_values?: Record<string, SettingValue[]>;
+ dependent_setting_display?: string;
+ upcoming_change?: Record<string, unknown> | null;
+ upcoming_change_default_override_metadata?: {
+ old_default: string;
+ new_default: string;
+ change_setting_name: string;
+ };
+ plugin?: string;
+ upload?: {
+ original_filename: string;
+ human_filesize: string;
+ width: number | null;
+ height: number | null;
+ };
+}
+
+/** Schema editors fill these caches lazily; category entries can also be client models. */
+export interface SettingMetadata {
+ categories?: Record<string, Partial<CategoryFields>>;
+ property_descriptions?: Record<string, string>;
+}
+
+/** Payload metadata plus core client editor state; plugins augment this interface. */
+export interface SiteSettingFields extends Omit<
+ Partial<SiteSettingWireRecord>,
+ "setting" | "type" | "humanized_name" | "value" | "default"
+> {
+ setting: string;
+ type: string;
+ humanized_name: string;
+ /** Client editors and subclasses also hold parsed JSON, booleans and numeric values. */
+ value: SettingValue;
+ default: SettingValue;
+ key?: string;
+ label?: string;
+ valueProperty?: string | null;
+ nameProperty?: string | null;
+ disabled?: boolean;
+ weight?: number;
+ defaultValues?: string;
+ allThemes?: Theme[];
+ setDefaultValuesLabel?: string;
+ metadata?: SettingMetadata;
+ /** Installed by the schema route; subclasses supply theme-specific implementations. */
+ updateSetting?(id: string | number, value: SettingValue): Promise<unknown>;
+}
+
+/** TODO(typescript-pending): remove this projection when SettingObjectHelper types its setting and getters. */
+type TypedSettingObjectHelper = Omit<
+ SettingObjectHelper,
+ | "settingObj"
+ | "computedValueProperty"
+ | "computedNameProperty"
+ | "validValues"
+ | "anyValue"
+> & {
+ settingObj: SiteSetting;
+ computedValueProperty: string | null;
+ computedNameProperty: string | null;
+ validValues: SettingChoice[];
+ anyValue: boolean | undefined;
+};
+
+/** TODO(typescript-pending): use BufferedProxy's content generic once it publishes one. */
+type SettingBufferedProxy = ObjectProxy<SiteSetting> & {
+ buffer: Partial<SiteSetting>;
+ hasBufferedChanges: boolean;
+ initializeBuffer(keys?: string[]): void;
+ unknownProperty(key: string): unknown;
+ setUnknownProperty(key: string, value: unknown): unknown;
+ applyBufferedChanges(keys?: string[]): void;
+ discardBufferedChanges(keys?: string[]): void;
+ applyChanges(keys?: string[]): void;
+ discardChanges(keys?: string[]): void;
+ hasChanged(key: string): boolean;
+ hasChanges: boolean;
+};
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface SiteSetting extends SiteSettingFields {}
+
+/**
+ * `true` when a value is the *enabled* state of a bool site setting: boolean
+ * `true`, the string `"true"`, or any value whose `String()` is exactly `"true"`.
+ * This is not general JS truthiness: `"false"` is not enabled, and is safe
+ * for `null` / `undefined` (unlike calling `.toString()` on the value).
+ */
+export function isSettingValueTrue(value: unknown): boolean {
+ return String(value) === "true";
+}
+
+const AUTO_REFRESH_ON_SAVE = [
+ "logo",
+ "mobile_logo",
+ "base_font",
+ "heading_font",
+ "default_text_size",
+];
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class SiteSetting extends EmberObject {
+ static async findAll(
+ params: object = {}
+ ): Promise<{ nameKey: string; name: string; siteSettings: SiteSetting[] }[]> {
+ // TODO(typescript-pending): ajax returns untyped JSON; remove the assertion when it accepts response types.
+ // eslint-disable-next-line prefer-const
+ let settings = (await ajax("/admin/site_settings", { data: params })) as {
+ site_settings: SiteSettingWireRecord[];
+ };
+ const categories: Record<string, SiteSetting[]> = {};
+ settings.site_settings.forEach(function (s) {
+ if (!categories[s.category]) {
+ categories[s.category] = [];
+ }
+ categories[s.category].push(SiteSetting.create(s));
+ });
+ return Object.keys(categories).map(function (n) {
+ return {
+ nameKey: n,
+ name: i18n("admin.site_settings.categories." + n),
+ siteSettings: categories[n],
+ };
+ });
+ }
+
+ static findByName(name: string): Promise<SiteSetting> {
+ return ajax("/admin/site_settings", {
+ data: {
+ names: [name],
+ },
+ }).then(function (settings: { site_settings: SiteSettingWireRecord[] }) {
+ const setting = settings.site_settings.find((s) => s.setting === name);
+ // The original factory also creates an empty instance when no matching row exists.
+ return SiteSetting.create(setting!);
+ });
+ }
+
+ static update(
+ key: string,
+ value: SettingValue,
+ opts: { updateExistingUsers?: boolean } = {}
+ ): Promise<void> {
+ const data: Record<string, SettingValue> = {};
+ data[key] = value;
+
+ if (opts["updateExistingUsers"] === true) {
+ data["update_existing_user"] = true;
+ }
+
+ return ajax(`/admin/site_settings/${key}`, { type: "PUT", data });
+ }
+
+ static bulkUpdate(
+ settings: Record<string, { value: SettingValue; backfill?: boolean }>
+ ): Promise<void> {
+ return ajax(`/admin/site_settings/bulk_update.json`, {
+ type: "PUT",
+ data: { settings },
+ });
+ }
+
+ @tracked isSaving = false;
+
+ @tracked validationMessage: string | TrustedHTML | null = null;
+ updateExistingUsers = false;
+
+ settingObjectHelper = new SettingObjectHelper(
+ this
+ ) as TypedSettingObjectHelper;
+
+ declare buffered: SettingBufferedProxy;
+
+ constructor(...args: ConstructorParameters<typeof EmberObject>) {
+ super(...args);
+ this.buffered = BufferedProxy.create({
+ content: this,
+ }) as unknown as SettingBufferedProxy;
+ }
+
+ @computed("settingObjectHelper.overridden")
+ get overridden(): boolean {
+ return this.settingObjectHelper?.overridden;
+ }
+
+ set overridden(value: boolean) {
+ set(this, "settingObjectHelper.overridden", value);
+ }
+
+ @computed("settingObjectHelper.computedValueProperty")
+ get computedValueProperty(): string | null {
+ return this.settingObjectHelper?.computedValueProperty;
+ }
+
+ set computedValueProperty(value: string | null) {
+ set(this, "settingObjectHelper.computedValueProperty", value);
+ }
+
+ @computed("settingObjectHelper.computedNameProperty")
+ get computedNameProperty(): string | null {
+ return this.settingObjectHelper?.computedNameProperty;
+ }
+
+ set computedNameProperty(value: string | null) {
+ set(this, "settingObjectHelper.computedNameProperty", value);
+ }
+
+ @computed("settingObjectHelper.validValues")
+ get validValues(): SettingChoice[] {
+ return this.settingObjectHelper?.validValues;
+ }
+
+ set validValues(value: SettingChoice[]) {
+ set(this, "settingObjectHelper.validValues", value);
+ }
+
+ @computed("settingObjectHelper.allowsNone")
+ get allowsNone(): string | undefined {
+ return applyValueTransformer(
+ "site-setting-allows-none",
+ this.settingObjectHelper?.allowsNone,
+ { siteSetting: this }
+ );
+ }
+
+ set allowsNone(value: string | undefined) {
+ set(this, "settingObjectHelper.allowsNone", value);
+ }
+
+ @computed("settingObjectHelper.anyValue")
+ get anyValue(): boolean | undefined {
+ return this.settingObjectHelper?.anyValue;
+ }
+
+ set anyValue(value: boolean | undefined) {
+ set(this, "settingObjectHelper.anyValue", value);
+ }
+
+ @computed("setting")
+ get staffLogFilter() {
+ if (!this.setting) {
+ return;
+ }
+
+ return {
+ subject: this.setting,
+ action_name: "change_site_setting",
+ };
+ }
+
+ get settingSubtype(): "textarea" | "password" | undefined {
+ if (this.list_type) {
+ return;
+ }
+
+ if (this.textarea) {
+ return "textarea";
+ }
+
+ if (this.secret) {
+ return "password";
+ }
+ }
+
+ get definition() {
+ return {
+ key: this.setting,
+ label: this.humanized_name || this.setting,
+ description: trustHTML(this.description!),
+ type: this.type,
+ list_type: this.list_type,
+ subtype: this.settingSubtype,
+ min: this.min,
+ max: this.max,
+ choices: this.choices,
+ valid_values: this.validValues,
+ allows_none: !!this.allowsNone,
+ allow_any: this.allow_any,
+ mandatory_values: this.mandatory_values,
+ disallowed_groups: this.disallowed_groups,
+ currentSavedValue: this.value,
+ };
+ }
+
+ get pendingValue() {
+ return this.buffered.get("value");
+ }
+
+ get hasPendingChanges() {
+ const pending = this.pendingValue ?? "";
+ const saved = this.value ?? "";
+
+ if (this.json_schema || this.schema || this.objects_schema) {
+ return !deepEqual(pending, saved);
+ }
+ return pending.toString() !== saved.toString();
+ }
+
+ get requiresConfirmation() {
+ switch (this.requires_confirmation) {
+ case SITE_SETTING_REQUIRES_CONFIRMATION_TYPES.simple:
+ return true;
+ case SITE_SETTING_REQUIRES_CONFIRMATION_TYPES.simple_on_enable: {
+ const val = this.buffered?.get("value");
+ return isSettingValueTrue(val);
+ }
+ case SITE_SETTING_REQUIRES_CONFIRMATION_TYPES.simple_on_disable: {
+ const val = this.buffered?.get("value");
+ return !isSettingValueTrue(val);
+ }
+ default:
+ return false;
+ }
+ }
+
+ get requiresReload() {
+ return AUTO_REFRESH_ON_SAVE.includes(this.setting);
+ }
+
+ get affectsExistingUsers() {
+ return DEFAULT_USER_PREFERENCES.includes(this.setting);
+ }
+
+ commit() {
+ this.validationMessage = null;
+ this.buffered.applyChanges();
+ }
+
+ rollback() {
+ this.buffered.discardChanges();
+ }
+
+ @bind
+ setUpdateExistingUsers(value: boolean): void {
+ this.updateExistingUsers = value;
+ }
+}
diff --git a/frontend/discourse/admin/models/theme-settings.js b/frontend/discourse/admin/models/theme-settings.js
deleted file mode 100644
index de4efc54828..00000000000
--- a/frontend/discourse/admin/models/theme-settings.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import SiteSetting from "discourse/admin/models/site-setting";
-import { ajax } from "discourse/lib/ajax";
-import { popupAjaxError } from "discourse/lib/ajax-error";
-
-export default class ThemeSettings extends SiteSetting {
- async updateSetting(themeId, newValue) {
- if (this.objects_schema) {
- newValue = JSON.stringify(newValue);
- }
-
- try {
- return ajax(`/admin/themes/${themeId}/setting`, {
- type: "PUT",
- data: {
- name: this.setting,
- value: newValue,
- },
- });
- } catch (error) {
- popupAjaxError(error);
- }
- }
-
- loadMetadata(themeId) {
- return ajax(
- `/admin/themes/${themeId}/objects_setting_metadata/${this.setting}.json`
- )
- .then((result) => this.set("metadata", result))
- .catch(popupAjaxError);
- }
-}
diff --git a/frontend/discourse/admin/models/theme-settings.ts b/frontend/discourse/admin/models/theme-settings.ts
new file mode 100644
index 00000000000..d800113279d
--- /dev/null
+++ b/frontend/discourse/admin/models/theme-settings.ts
@@ -0,0 +1,57 @@
+import SiteSetting, {
+ type SettingMetadata,
+ type SettingValue,
+ type SiteSettingFields,
+} from "discourse/admin/models/site-setting";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+
+/** Theme translations reuse the setting model with only key, value, default and textarea. */
+export interface ThemeSettingsFields extends SiteSettingFields {
+ resolve_group_membership?: boolean;
+}
+
+/** The update endpoint returns a map keyed by the setting name. */
+export type ThemeSettingUpdateResult = Record<string, SettingValue>;
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface ThemeSettings extends ThemeSettingsFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class ThemeSettings extends SiteSetting {
+ /** The catch handles synchronous throws only; request rejections propagate to the caller. */
+ updateSetting(
+ themeId: number,
+ newValue: SettingValue
+ ): Promise<ThemeSettingUpdateResult | undefined>;
+
+ updateSetting(this: never, id: string | number, value: SettingValue): never;
+ async updateSetting(
+ themeId: string | number,
+ newValue: SettingValue
+ ): Promise<ThemeSettingUpdateResult | undefined> {
+ if (this.objects_schema) {
+ newValue = JSON.stringify(newValue);
+ }
+
+ try {
+ return ajax(`/admin/themes/${themeId}/setting`, {
+ type: "PUT",
+ data: {
+ name: this.setting,
+ value: newValue,
+ },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ loadMetadata(themeId: number): Promise<SettingMetadata | void> {
+ return ajax(
+ `/admin/themes/${themeId}/objects_setting_metadata/${this.setting}.json`
+ )
+ .then((result: SettingMetadata) => this.set("metadata", result))
+ .catch(popupAjaxError);
+ }
+}
diff --git a/frontend/discourse/admin/models/theme-site-settings.js b/frontend/discourse/admin/models/theme-site-settings.js
deleted file mode 100644
index 1bc5804bc0d..00000000000
--- a/frontend/discourse/admin/models/theme-site-settings.js
+++ /dev/null
@@ -1,19 +0,0 @@
-import SiteSetting from "discourse/admin/models/site-setting";
-import { ajax } from "discourse/lib/ajax";
-import { popupAjaxError } from "discourse/lib/ajax-error";
-
-export default class ThemeSiteSettings extends SiteSetting {
- async updateSetting(themeId, newValue) {
- try {
- return ajax(`/admin/themes/${themeId}/site-setting`, {
- type: "PUT",
- data: {
- name: this.setting,
- value: newValue,
- },
- });
- } catch (error) {
- popupAjaxError(error);
- }
- }
-}
diff --git a/frontend/discourse/admin/models/theme-site-settings.ts b/frontend/discourse/admin/models/theme-site-settings.ts
new file mode 100644
index 00000000000..1c865cbc83f
--- /dev/null
+++ b/frontend/discourse/admin/models/theme-site-settings.ts
@@ -0,0 +1,51 @@
+import SiteSetting, {
+ type SettingValue,
+ type SiteSettingFields,
+} from "discourse/admin/models/site-setting";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+
+/** Themeable site settings retain the endpoint's string values. */
+export interface ThemeSiteSettingsFields extends SiteSettingFields {
+ value: string;
+ default: string;
+}
+
+/** Resetting an override can return only the success marker. */
+export type ThemeSiteSettingUpdateResult = { success: "OK" } & (
+ | { name: string; value: string | null; theme_id: number }
+ | { name?: never; value?: never; theme_id?: never }
+);
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface ThemeSiteSettings extends ThemeSiteSettingsFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class ThemeSiteSettings extends SiteSetting {
+ declare value: string;
+ declare default: string;
+
+ /** The catch handles synchronous throws only; request rejections propagate to the caller. */
+ updateSetting(
+ themeId: number,
+ newValue: string
+ ): Promise<ThemeSiteSettingUpdateResult | undefined>;
+
+ updateSetting(this: never, id: string | number, value: SettingValue): never;
+ async updateSetting(
+ themeId: string | number,
+ newValue: SettingValue
+ ): Promise<ThemeSiteSettingUpdateResult | undefined> {
+ try {
+ return ajax(`/admin/themes/${themeId}/site-setting`, {
+ type: "PUT",
+ data: {
+ name: this.setting,
+ value: newValue,
+ },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+}
diff --git a/frontend/discourse/admin/models/theme.js b/frontend/discourse/admin/models/theme.js
deleted file mode 100644
index 0d411e179eb..00000000000
--- a/frontend/discourse/admin/models/theme.js
+++ /dev/null
@@ -1,334 +0,0 @@
-import { computed, get } from "@ember/object";
-import { isBlank, isEmpty } from "@ember/utils";
-import ThemeSettings from "discourse/admin/models/theme-settings";
-import ThemeSiteSettings from "discourse/admin/models/theme-site-settings";
-import { popupAjaxError } from "discourse/lib/ajax-error";
-import {
- addUniqueValueToArray,
- removeValueFromArray,
-} from "discourse/lib/array-tools";
-import { autoTrackedArray } from "discourse/lib/tracked-tools";
-import RestModel from "discourse/models/rest";
-import { i18n } from "discourse-i18n";
-
-const THEME_UPLOAD_VAR = 2;
-const FIELDS_IDS = [0, 1, 5, 6];
-
-export const THEMES = "themes";
-export const COMPONENTS = "components";
-const SETTINGS_TYPE_ID = 5;
-
-const JS_FILENAME = "discourse/api-initializers/theme-initializer.gjs";
-
-class Theme extends RestModel {
- static munge(json) {
- if (json.settings) {
- json.settings = json.settings.map((setting) =>
- ThemeSettings.create(setting)
- );
- }
-
- if (json.themeable_site_settings) {
- json.themeable_site_settings = json.themeable_site_settings.map(
- (setting) => ThemeSiteSettings.create(setting)
- );
- }
-
- return json;
- }
-
- @autoTrackedArray childThemes;
- @autoTrackedArray parentThemes;
- @autoTrackedArray theme_fields;
-
- changed = false;
-
- @computed("default", "user_selectable")
- get isActive() {
- return this.default || this.user_selectable;
- }
-
- @computed("remote_theme.commits_behind")
- get isPendingUpdates() {
- return this.remote_theme?.commits_behind > 0;
- }
-
- @computed("editedFields.length")
- get hasEditedFields() {
- return this.editedFields?.length > 0;
- }
-
- @computed("parent_themes.length")
- get hasParents() {
- return this.parent_themes?.length > 0;
- }
-
- @computed("theme_fields.[]")
- get targets() {
- return [
- { id: 0, name: "common" },
- { id: 1, name: "desktop", icon: "desktop" },
- { id: 2, name: "mobile", icon: "mobile-screen-button" },
- ].map((target) => {
- target["edited"] = this.hasEdited(target.name);
- target["error"] = this.hasError(target.name);
- return target;
- });
- }
-
- @computed("theme_fields.[]")
- get fieldNames() {
- const common = [
- "scss",
- "head_tag",
- "header",
- "after_header",
- "body_tag",
- "footer",
- ];
-
- return {
- common: [
- ...common,
- "js",
- "color_definitions",
- "embedded_scss",
- "embedded_header",
- ],
- desktop: common,
- mobile: common,
- };
- }
-
- @computed("fieldNames", "theme_fields.[]", "[email protected]")
- get fields() {
- const hash = {};
- Object.keys(this.fieldNames).forEach((target) => {
- hash[target] = this.fieldNames[target].map((fieldName) => {
- const field = {
- name: fieldName,
- edited: this.hasEdited(target, fieldName),
- error: this.hasError(target, fieldName),
- };
-
- field.translatedName = i18n(`admin.customize.theme.${fieldName}.text`);
- field.title = i18n(`admin.customize.theme.${fieldName}.title`);
-
- if (fieldName.indexOf("_tag") > 0) {
- field.icon = "far-file-lines";
- }
-
- return field;
- });
- });
- return hash;
- }
-
- @computed("theme_fields")
- get themeFields() {
- if (!this.theme_fields) {
- this.set("theme_fields", []); // eslint-disable-line ember/no-side-effects
- return {};
- }
-
- let hash = {};
- this.theme_fields.forEach((field) => {
- if (!field.type_id || FIELDS_IDS.includes(field.type_id)) {
- hash[this.getKey(field)] = field;
- }
- });
- return hash;
- }
-
- @computed("theme_fields", "theme_fields.[]")
- get uploads() {
- if (!this.theme_fields) {
- return [];
- }
- return this.theme_fields.filter(
- (f) => f.target === "common" && f.type_id === THEME_UPLOAD_VAR
- );
- }
-
- @computed("theme_fields", "[email protected]")
- get isBroken() {
- return (
- this.theme_fields &&
- this.theme_fields.some((field) => field.error && field.error.length > 0)
- );
- }
-
- @computed("theme_fields.[]")
- get editedFields() {
- return this.theme_fields?.filter(
- (field) => !isBlank(field.value) && field.type_id !== SETTINGS_TYPE_ID
- );
- }
-
- @computed("remote_theme.last_error_text")
- get remoteError() {
- if (
- this.remote_theme?.last_error_text &&
- this.remote_theme?.last_error_text?.length > 0
- ) {
- return this.remote_theme?.last_error_text;
- }
- }
-
- @computed("childThemes.[]")
- get child_theme_ids() {
- if (this.childThemes) {
- return this.childThemes?.map((theme) => get(theme, "id"));
- }
- }
-
- @computed("component", "enabled", "hasParents")
- get warnUnassignedComponent() {
- return this.component && this.enabled && !this.hasParents;
- }
-
- getKey(field) {
- return `${field.target} ${field.name}`;
- }
-
- hasEdited(target, name) {
- if (name) {
- return !isEmpty(this.getField(target, name));
- } else {
- let fields = this.theme_fields || [];
- return fields.some(
- (field) => field.target === target && !isEmpty(field.value)
- );
- }
- }
-
- hasError(target, name) {
- return this.theme_fields
- .filter((f) => f.target === target && (!name || name === f.name))
- .some((f) => f.error);
- }
-
- getError(target, name) {
- let themeFields = this.themeFields;
- let key = this.getKey({ target, name });
- let field = themeFields[key];
- return field ? field.error : "";
- }
-
- getField(target, name) {
- if (target === "common" && name === "js") {
- target = "extra_js";
- name = JS_FILENAME;
- }
- let themeFields = this.themeFields;
- let key = this.getKey({ target, name });
- let field = themeFields[key];
- return field ? field.value : "";
- }
-
- removeField(field) {
- this.set("changed", true);
-
- field.upload_id = null;
- field.value = null;
-
- return this.saveChanges("theme_fields");
- }
-
- setField(target, name, value, upload_id, type_id) {
- this.set("changed", true);
-
- // Normalize JS field target/name consistently with getField()
- if (target === "common" && name === "js") {
- target = "extra_js";
- name = JS_FILENAME;
- }
-
- let themeFields = this.themeFields;
- let field = { name, target, value, upload_id, type_id };
-
- // slow path for uploads and so on
- if (type_id && type_id > 1) {
- let fields = this.theme_fields;
- let existing = fields.find(
- (f) => f.target === target && f.name === name && f.type_id === type_id
- );
- if (existing) {
- existing.value = value;
- existing.upload_id = upload_id;
- } else {
- fields.push(field);
- }
- return;
- }
-
- // fast path
- let key = this.getKey({ target, name });
- let existingField = themeFields[key];
- if (!existingField) {
- this.theme_fields.push(field);
- themeFields[key] = field;
- } else {
- const changed =
- (isEmpty(existingField.value) && !isEmpty(value)) ||
- (isEmpty(value) && !isEmpty(existingField.value));
-
- existingField.value = value;
- if (changed) {
- // Observing [email protected] is too slow, so manually notify
- // if the value goes to/from blank
- this.notifyPropertyChange("theme_fields.[]");
- }
- }
- }
-
- removeChildTheme(theme) {
- removeValueFromArray(this.childThemes, theme);
- return this.saveChanges("child_theme_ids");
- }
-
- addChildTheme(theme) {
- let childThemes = this.childThemes;
- if (!childThemes) {
- childThemes = [];
- this.set("childThemes", childThemes);
- }
-
- removeValueFromArray(childThemes, theme);
- childThemes.push(theme);
-
- return this.saveChanges("child_theme_ids");
- }
-
- addParentTheme(theme) {
- let parentThemes = this.parentThemes;
- if (!parentThemes) {
- parentThemes = [];
- this.set("parentThemes", parentThemes);
- }
-
- addUniqueValueToArray(parentThemes, theme);
- }
-
- checkForUpdates() {
- return this.save({ remote_check: true }).then(() =>
- this.set("changed", false)
- );
- }
-
- updateToLatest() {
- return this.save({ remote_update: true }).then(() =>
- this.set("changed", false)
- );
- }
-
- saveChanges() {
- const hash = this.getProperties.apply(this, arguments);
- return this.save(hash)
- .then(() => true)
- .finally(() => this.set("changed", false))
- .catch(popupAjaxError);
- }
-}
-
-export default Theme;
diff --git a/frontend/discourse/admin/models/theme.ts b/frontend/discourse/admin/models/theme.ts
new file mode 100644
index 00000000000..ae6500cb6b9
--- /dev/null
+++ b/frontend/discourse/admin/models/theme.ts
@@ -0,0 +1,549 @@
+/* eslint-disable prefer-const -- Preserve the original JavaScript emit for this types-only port. */
+import { computed, get } from "@ember/object";
+import { isBlank, isEmpty } from "@ember/utils";
+import type { SettingValue } from "discourse/admin/models/site-setting";
+import ThemeSettings, {
+ type ThemeSettingsFields,
+} from "discourse/admin/models/theme-settings";
+import ThemeSiteSettings, {
+ type ThemeSiteSettingsFields,
+} from "discourse/admin/models/theme-site-settings";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import {
+ addUniqueValueToArray,
+ removeValueFromArray,
+} from "discourse/lib/array-tools";
+import { autoTrackedArray } from "discourse/lib/tracked-tools";
+import RestModel, {
+ type RestModelClass,
+ type RestModelStoreAttrs,
+ type RestPayload,
+} from "discourse/models/rest";
+import { i18n } from "discourse-i18n";
+
+const THEME_UPLOAD_VAR = 2;
+const FIELDS_IDS = [0, 1, 5, 6];
+
+export const THEMES = "themes" as const;
+export const COMPONENTS = "components" as const;
+const SETTINGS_TYPE_ID = 5;
+
+const JS_FILENAME = "discourse/api-initializers/theme-initializer.gjs";
+
+/** The basic serializer used in raw parent/child relationships. */
+export interface BasicTheme {
+ id: number;
+ name: string;
+ description: string | null;
+ created_at: string;
+ updated_at: string;
+ default?: boolean;
+ component: boolean;
+}
+
+/** Field payload; remote themes omit source values, and deletion clears values/uploads. */
+export interface ThemeField {
+ name: string;
+ target: string | null;
+ type_id: number;
+ value?: string | null;
+ file_path?: string | null;
+ error?: string;
+ upload_id?: number | null;
+ url?: string;
+ filename?: string;
+ migrated?: boolean;
+}
+
+/** Remote metadata is nullable independently of whether the remote record exists. */
+export interface RemoteTheme {
+ id: number;
+ remote_url: string;
+ remote_version: string | null;
+ local_version: string | null;
+ commits_behind: number | null;
+ branch: string | null;
+ local_compat_ref: string | null;
+ remote_compat_ref: string | null;
+ remote_updated_at: string | null;
+ updated_at: string;
+ github_diff_link?: string;
+ last_error_text: string | null;
+ is_git: boolean;
+ license_url: string | null;
+ about_url: string | null;
+ authors: string | null;
+ theme_version: string | null;
+ minimum_discourse_version: string | null;
+ maximum_discourse_version: string | null;
+ has_private_key: boolean;
+}
+
+/** Raw translations become ThemeSettings only when the translations panel loads them. */
+export interface ThemeTranslation {
+ key: string;
+ value: SettingValue;
+ default: SettingValue;
+}
+
+/** Embedded serializer data, not a hydrated ColorScheme model. */
+export interface ThemeColorScheme {
+ id: number;
+ name: string;
+ is_base: boolean | null;
+ base_scheme_id: number | null;
+ theme_id: number | null;
+ theme_name: string | null;
+ user_selectable: boolean;
+ is_builtin_default: boolean | null;
+ is_dark: boolean;
+ colors: {
+ name: string;
+ hex: string;
+ default_hex: string | null;
+ is_advanced: boolean;
+ }[];
+}
+
+/** Embedded user/name/title serializer data. */
+export interface ThemeUser {
+ id: number;
+ username: string;
+ avatar_template: string;
+ name?: string | null;
+ title: string | null;
+}
+
+/** Full editor fields and mutable UI state; index/create payloads can omit editor data. Plugins augment here. */
+export interface ThemeFields extends BasicTheme {
+ color_scheme_id: number | null;
+ dark_color_scheme_id: number | null;
+ remote_theme_id: number | null;
+ user_selectable?: boolean;
+ auto_update?: boolean;
+ supported?: boolean;
+ enabled?: boolean;
+ system?: boolean;
+ only_theme_color_schemes?: boolean;
+ screenshot_light_url?: string | null;
+ screenshot_dark_url?: string | null;
+ settings?: ThemeSettings[] | null;
+ themeable_site_settings?: ThemeSiteSettings[];
+ child_themes?: BasicTheme[];
+ parent_themes?: BasicTheme[];
+ remote_theme?: RemoteTheme | null;
+ color_scheme?: ThemeColorScheme | null;
+ user?: ThemeUser;
+ disabled_by?: ThemeUser | null;
+ disabled_at?: string | null;
+ errors?: string[];
+ translations?: (ThemeTranslation | ThemeSettings)[];
+ loadingTranslations?: boolean;
+ locale?: string;
+ markedToDelete?: boolean;
+ selected?: boolean;
+}
+
+/** munge accepts raw setting records as well as previously hydrated settings. */
+export type ThemeCreateAttrs<M = Theme> = Omit<
+ Partial<M>,
+ "settings" | "themeable_site_settings"
+> &
+ RestModelStoreAttrs &
+ RestPayload & {
+ settings?: Partial<Omit<ThemeSettingsFields, "updateSetting">>[] | null;
+ themeable_site_settings?: Partial<
+ Omit<ThemeSiteSettingsFields, "updateSetting">
+ >[];
+ };
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+interface Theme extends ThemeFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+class Theme extends RestModel {
+ /** Uses RestModel's runtime factory, whose munge hydrates the nested settings. */
+ declare static create: <C extends RestModelClass>(
+ this: C,
+ attrs?: ThemeCreateAttrs<InstanceType<C>>
+ ) => InstanceType<C>;
+
+ static munge(json: ThemeCreateAttrs): RestPayload;
+ static munge(json: RestPayload): RestPayload;
+ static munge(json: ThemeCreateAttrs) {
+ if (json.settings) {
+ json.settings = json.settings.map((setting) =>
+ ThemeSettings.create(setting)
+ );
+ }
+
+ if (json.themeable_site_settings) {
+ json.themeable_site_settings = json.themeable_site_settings.map(
+ (setting) => ThemeSiteSettings.create(setting)
+ );
+ }
+
+ return json;
+ }
+
+ @autoTrackedArray childThemes?: Theme[];
+ @autoTrackedArray parentThemes?: Theme[];
+
+ /** Full editor records supply fields; partial records initialize them lazily in themeFields. */
+ @autoTrackedArray theme_fields!: ThemeField[];
+
+ changed = false;
+
+ @computed("default", "user_selectable")
+ get isActive() {
+ return this.default || this.user_selectable;
+ }
+
+ @computed("remote_theme.commits_behind")
+ get isPendingUpdates() {
+ // Missing counters still participate in the original JavaScript comparison.
+ return (this.remote_theme?.commits_behind as number) > 0;
+ }
+
+ @computed("editedFields.length")
+ get hasEditedFields() {
+ return (this.editedFields?.length as number) > 0;
+ }
+
+ @computed("parent_themes.length")
+ get hasParents() {
+ return (this.parent_themes?.length as number) > 0;
+ }
+
+ @computed("theme_fields.[]")
+ get targets() {
+ return (
+ [
+ { id: 0, name: "common" },
+ { id: 1, name: "desktop", icon: "desktop" },
+ { id: 2, name: "mobile", icon: "mobile-screen-button" },
+ ] as {
+ id: number;
+ name: string;
+ icon?: string;
+ edited?: boolean;
+ error?: boolean;
+ }[]
+ ).map((target) => {
+ target["edited"] = this.hasEdited(target.name);
+ target["error"] = this.hasError(target.name);
+ return target;
+ });
+ }
+
+ @computed("theme_fields.[]")
+ get fieldNames() {
+ const common = [
+ "scss",
+ "head_tag",
+ "header",
+ "after_header",
+ "body_tag",
+ "footer",
+ ];
+
+ return {
+ common: [
+ ...common,
+ "js",
+ "color_definitions",
+ "embedded_scss",
+ "embedded_header",
+ ],
+ desktop: common,
+ mobile: common,
+ };
+ }
+
+ @computed("fieldNames", "theme_fields.[]", "[email protected]")
+ get fields() {
+ const hash: Record<
+ string,
+ {
+ name: string;
+ edited: boolean;
+ error: boolean;
+ translatedName?: string;
+ title?: string;
+ icon?: string;
+ }[]
+ > = {};
+ Object.keys(this.fieldNames).forEach((target) => {
+ hash[target] = this.fieldNames[
+ target as keyof typeof this.fieldNames
+ ].map((fieldName) => {
+ const field: {
+ name: string;
+ edited: boolean;
+ error: boolean;
+ translatedName?: string;
+ title?: string;
+ icon?: string;
+ } = {
+ name: fieldName,
+ edited: this.hasEdited(target, fieldName),
+ error: this.hasError(target, fieldName),
+ };
+
+ field.translatedName = i18n(`admin.customize.theme.${fieldName}.text`);
+ field.title = i18n(`admin.customize.theme.${fieldName}.title`);
+
+ if (fieldName.indexOf("_tag") > 0) {
+ field.icon = "far-file-lines";
+ }
+
+ return field;
+ });
+ });
+ return hash;
+ }
+
+ @computed("theme_fields")
+ get themeFields(): Record<string, ThemeField> {
+ if (!this.theme_fields) {
+ this.set("theme_fields", []); // eslint-disable-line ember/no-side-effects
+ return {};
+ }
+
+ let hash: Record<string, ThemeField> = {};
+ this.theme_fields.forEach((field) => {
+ if (!field.type_id || FIELDS_IDS.includes(field.type_id)) {
+ hash[this.getKey(field)] = field;
+ }
+ });
+ return hash;
+ }
+
+ @computed("theme_fields", "theme_fields.[]")
+ get uploads() {
+ if (!this.theme_fields) {
+ return [];
+ }
+ return this.theme_fields.filter(
+ (f) => f.target === "common" && f.type_id === THEME_UPLOAD_VAR
+ );
+ }
+
+ @computed("theme_fields", "[email protected]")
+ get isBroken(): boolean | undefined {
+ return (
+ this.theme_fields &&
+ this.theme_fields.some((field) => field.error && field.error.length > 0)
+ );
+ }
+
+ @computed("theme_fields.[]")
+ get editedFields(): ThemeField[] | undefined {
+ return this.theme_fields?.filter(
+ (field) => !isBlank(field.value) && field.type_id !== SETTINGS_TYPE_ID
+ );
+ }
+
+ @computed("remote_theme.last_error_text")
+ get remoteError() {
+ if (
+ this.remote_theme?.last_error_text &&
+ this.remote_theme?.last_error_text?.length > 0
+ ) {
+ return this.remote_theme?.last_error_text;
+ }
+ }
+
+ @computed("childThemes.[]")
+ get child_theme_ids() {
+ if (this.childThemes) {
+ return this.childThemes?.map((theme) => get(theme, "id"));
+ }
+ }
+
+ @computed("component", "enabled", "hasParents")
+ get warnUnassignedComponent() {
+ return this.component && this.enabled && !this.hasParents;
+ }
+
+ getKey(field: Pick<ThemeField, "target" | "name">): string {
+ return `${field.target} ${field.name}`;
+ }
+
+ hasEdited(target: string, name?: string): boolean {
+ if (name) {
+ return !isEmpty(this.getField(target, name));
+ } else {
+ let fields = this.theme_fields || [];
+ return fields.some(
+ (field) => field.target === target && !isEmpty(field.value)
+ );
+ }
+ }
+
+ hasError(target: string, name?: string): boolean {
+ return this.theme_fields
+ .filter((f) => f.target === target && (!name || name === f.name))
+ .some((f) => f.error);
+ }
+
+ getError(target: string, name: string): string | undefined {
+ let themeFields = this.themeFields;
+ let key = this.getKey({ target, name });
+ let field = themeFields[key];
+ return field ? field.error : "";
+ }
+
+ /** Source editing uses local payloads, which include field values. */
+ getField(target: string, name: string): string | null {
+ if (target === "common" && name === "js") {
+ target = "extra_js";
+ name = JS_FILENAME;
+ }
+ let themeFields = this.themeFields;
+ let key = this.getKey({ target, name });
+ let field = themeFields[key];
+ return field ? (field.value as string | null) : "";
+ }
+
+ removeField(field: ThemeField) {
+ this.set("changed", true);
+
+ field.upload_id = null;
+ field.value = null;
+
+ return this.saveChanges("theme_fields");
+ }
+
+ setField(target: string, name: string, value: string | null): void;
+ setField(
+ target: string,
+ name: string,
+ value: string | null,
+ upload_id: number | null,
+ type_id: number
+ ): void;
+
+ setField(
+ target: string,
+ name: string,
+ value: string | null,
+ upload_id?: number | null,
+ type_id?: number
+ ): void {
+ this.set("changed", true);
+
+ // Normalize JS field target/name consistently with getField()
+ if (target === "common" && name === "js") {
+ target = "extra_js";
+ name = JS_FILENAME;
+ }
+
+ let themeFields = this.themeFields;
+ // Three-argument editor calls stage fields without type_id until the server saves them.
+ let field = { name, target, value, upload_id, type_id } as ThemeField;
+
+ // slow path for uploads and so on
+ if (type_id && type_id > 1) {
+ let fields = this.theme_fields;
+ let existing = fields.find(
+ (f) => f.target === target && f.name === name && f.type_id === type_id
+ );
+ if (existing) {
+ existing.value = value;
+ existing.upload_id = upload_id;
+ } else {
+ fields.push(field);
+ }
+ return;
+ }
+
+ // fast path
+ let key = this.getKey({ target, name });
+ let existingField = themeFields[key];
+ if (!existingField) {
+ this.theme_fields.push(field);
+ themeFields[key] = field;
+ } else {
+ const changed =
+ (isEmpty(existingField.value) && !isEmpty(value)) ||
+ (isEmpty(value) && !isEmpty(existingField.value));
+
+ existingField.value = value;
+ if (changed) {
+ // Observing [email protected] is too slow, so manually notify
+ // if the value goes to/from blank
+ this.notifyPropertyChange("theme_fields.[]");
+ }
+ }
+ }
+
+ removeChildTheme(theme: Theme) {
+ // Keep the adapter-hydrated relationship precondition; missing children still reach the helper.
+ removeValueFromArray(this.childThemes!, theme);
+ return this.saveChanges("child_theme_ids");
+ }
+
+ addChildTheme(theme: Theme) {
+ let childThemes = this.childThemes;
+ if (!childThemes) {
+ childThemes = [];
+ this.set("childThemes", childThemes);
+ }
+
+ removeValueFromArray(childThemes, theme);
+ childThemes.push(theme);
+
+ return this.saveChanges("child_theme_ids");
+ }
+
+ addParentTheme(theme: Theme) {
+ let parentThemes = this.parentThemes;
+ if (!parentThemes) {
+ parentThemes = [];
+ this.set("parentThemes", parentThemes);
+ }
+
+ addUniqueValueToArray(parentThemes, theme);
+ }
+
+ checkForUpdates() {
+ return this.save({ remote_check: true }).then(() =>
+ this.set("changed", false)
+ );
+ }
+
+ updateToLatest() {
+ return this.save({ remote_update: true }).then(() =>
+ this.set("changed", false)
+ );
+ }
+
+ /** Saves the named properties; the implementation intentionally has zero formal parameters. */
+ saveChanges(...keys: (keyof this & string)[]): Promise<boolean | void>;
+ saveChanges() {
+ // apply consumes the array-like arguments object without changing the method arity.
+ // eslint-disable-next-line prefer-spread
+ const hash = this.getProperties.apply(
+ this,
+ // eslint-disable-next-line prefer-rest-params
+ arguments as unknown as (keyof this & string)[]
+ );
+ return this.save(hash)
+ .then(() => true)
+ .finally(() => this.set("changed", false))
+ .catch(popupAjaxError);
+ }
+}
+
+export default Theme;
+
+declare module "discourse/services/store" {
+ interface ModelRegistry {
+ theme: Theme;
+ }
+
+ interface ModelCreateAttrsRegistry {
+ theme: ThemeCreateAttrs<Theme>;
+ }
+}
diff --git a/frontend/discourse/type-tests/models/admin-settings-test.ts b/frontend/discourse/type-tests/models/admin-settings-test.ts
new file mode 100644
index 00000000000..db0b1b44bb4
--- /dev/null
+++ b/frontend/discourse/type-tests/models/admin-settings-test.ts
@@ -0,0 +1,229 @@
+import type EmberObject from "@ember/object";
+import type { TrustedHTML } from "@ember/template";
+import { expectTypeOf } from "expect-type";
+import SiteSetting, {
+ isSettingValueTrue,
+} from "discourse/admin/models/site-setting";
+import Theme, {
+ COMPONENTS,
+ type ThemeCreateAttrs,
+ type ThemeField,
+ THEMES,
+} from "discourse/admin/models/theme";
+import ThemeSettings from "discourse/admin/models/theme-settings";
+import ThemeSiteSettings from "discourse/admin/models/theme-site-settings";
+import type RestModel from "discourse/models/rest";
+import type {
+ default as StoreService,
+ ModelFor,
+ ResultSetOf,
+} from "discourse/services/store";
+
+declare const store: StoreService;
+
+/* SiteSetting: `/admin/site_settings` rows, where every value is a string. */
+
+expectTypeOf<Awaited<ReturnType<typeof SiteSetting.findAll>>>().toEqualTypeOf<
+ { nameKey: string; name: string; siteSettings: SiteSetting[] }[]
+>();
+SiteSetting.findAll();
+SiteSetting.findAll({ filter_names: ["title"] });
+expectTypeOf(
+ SiteSetting.findByName("title")
+).resolves.toEqualTypeOf<SiteSetting>();
+SiteSetting.update("title", "New title");
+SiteSetting.update("enable_welcome_banner", false);
+SiteSetting.update("default_other_new_topic_duration_minutes", "10", {
+ updateExistingUsers: true,
+});
+SiteSetting.bulkUpdate({ title: { value: "A" } });
+
+declare const setting: SiteSetting;
+expectTypeOf(setting).toExtend<EmberObject>();
+expectTypeOf(setting).not.toBeAny();
+expectTypeOf(setting.setting).toEqualTypeOf<string>();
+expectTypeOf(setting.type).toEqualTypeOf<string>();
+expectTypeOf(setting.humanized_name).toEqualTypeOf<string>();
+expectTypeOf(setting.isSaving).toEqualTypeOf<boolean>();
+expectTypeOf(setting.validationMessage).toEqualTypeOf<
+ string | TrustedHTML | null
+>();
+expectTypeOf(setting.updateExistingUsers).toEqualTypeOf<boolean>();
+// Editors write strings, but plugins and the schema route also store booleans and parsed objects.
+setting.value = "true";
+setting.set("value", false);
+expectTypeOf(setting.overridden).toEqualTypeOf<boolean>();
+expectTypeOf(setting.requiresConfirmation).toEqualTypeOf<boolean>();
+expectTypeOf(setting.requiresReload).toEqualTypeOf<boolean>();
+expectTypeOf(setting.affectsExistingUsers).toEqualTypeOf<boolean>();
+expectTypeOf(setting.hasPendingChanges).toEqualTypeOf<boolean>();
+expectTypeOf(setting.settingSubtype).toEqualTypeOf<
+ "textarea" | "password" | undefined
+>();
+expectTypeOf(setting.staffLogFilter).toEqualTypeOf<
+ { subject: string; action_name: string } | undefined
+>();
+expectTypeOf(setting.buffered).not.toBeAny();
+expectTypeOf(setting.commit()).toEqualTypeOf<void>();
+expectTypeOf(setting.rollback()).toEqualTypeOf<void>();
+setting.setUpdateExistingUsers(true);
+// Optional metadata the controls read.
+expectTypeOf(setting.min).toEqualTypeOf<number | undefined>();
+expectTypeOf(setting.upload).toEqualTypeOf<
+ | {
+ original_filename: string;
+ human_filesize: string;
+ width: number | null;
+ height: number | null;
+ }
+ | undefined
+>();
+expectTypeOf(isSettingValueTrue("true")).toEqualTypeOf<boolean>();
+isSettingValueTrue(true);
+isSettingValueTrue(null);
+// The theme selectors build settings client-side.
+SiteSetting.create({
+ setting: "parent_theme_ids",
+ type: "list",
+ list_type: "compact",
+ allow_any: false,
+ preview: null,
+ value: "",
+ default: "",
+ choices: ["Light", "Dark"],
+});
+
+/* ThemeSettings: a theme's settings, whose values follow the setting type. */
+
+declare const themeSetting: ThemeSettings;
+expectTypeOf(themeSetting).toExtend<SiteSetting>();
+themeSetting.value = 51;
+themeSetting.value = true;
+themeSetting.value = null;
+themeSetting.value = [{ name: "section", links: [] }];
+expectTypeOf(themeSetting.objects_schema).not.toBeAny();
+themeSetting.updateSetting(1, [{ name: "section" }]);
+themeSetting.loadMetadata(1);
+expectTypeOf(themeSetting.metadata?.property_descriptions).toEqualTypeOf<
+ Record<string, string> | undefined
+>();
+// Translations reuse this class without a setting name or type.
+ThemeSettings.create({
+ key: "greeting",
+ value: "Hello",
+ default: "Hello",
+ textarea: true,
+});
+
+/* ThemeSiteSettings: site settings a theme can override; values are strings. */
+
+declare const themeSiteSetting: ThemeSiteSettings;
+expectTypeOf(themeSiteSetting).toExtend<SiteSetting>();
+themeSiteSetting.updateSetting(1, "false");
+
+/* Theme: `/admin/themes` records. */
+
+expectTypeOf(THEMES).toEqualTypeOf<"themes">();
+expectTypeOf(COMPONENTS).toEqualTypeOf<"components">();
+expectTypeOf<ModelFor<"theme">>().toEqualTypeOf<Theme>();
+expectTypeOf(store.findAll("theme")).resolves.toEqualTypeOf<
+ ResultSetOf<Theme> | undefined
+>();
+Theme.create({ id: 1, name: "Light", __type: "theme", __state: "created" });
+
+declare const theme: Theme;
+expectTypeOf(theme).toExtend<RestModel>();
+expectTypeOf(theme.id).toEqualTypeOf<number>();
+expectTypeOf(theme.name).toEqualTypeOf<string>();
+expectTypeOf(theme.description).toEqualTypeOf<string | null>();
+expectTypeOf(theme.component).toEqualTypeOf<boolean>();
+// Only the default theme sends `default`.
+expectTypeOf(theme.default).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(theme.color_scheme_id).toEqualTypeOf<number | null>();
+expectTypeOf(theme.dark_color_scheme_id).toEqualTypeOf<number | null>();
+expectTypeOf(theme.remote_theme_id).toEqualTypeOf<number | null>();
+expectTypeOf(theme.screenshot_light_url).toEqualTypeOf<
+ string | null | undefined
+>();
+// Invalid settings YAML sends null.
+expectTypeOf(theme.settings).toEqualTypeOf<
+ ThemeSettings[] | null | undefined
+>();
+// Components omit themeable site settings.
+expectTypeOf(theme.themeable_site_settings).toEqualTypeOf<
+ ThemeSiteSettings[] | undefined
+>();
+expectTypeOf(theme.remote_theme?.commits_behind).toEqualTypeOf<
+ number | null | undefined
+>();
+expectTypeOf(theme.remote_theme?.branch).toEqualTypeOf<
+ string | null | undefined
+>();
+expectTypeOf(theme.childThemes).toEqualTypeOf<Theme[] | undefined>();
+expectTypeOf(theme.child_themes?.[0]?.name).toEqualTypeOf<string | undefined>();
+expectTypeOf(theme.theme_fields[0].type_id).toEqualTypeOf<number>();
+// Deleting a field clears its value and upload.
+theme.theme_fields[0].value = null;
+theme.theme_fields[0].upload_id = null;
+expectTypeOf(theme.changed).toEqualTypeOf<boolean>();
+expectTypeOf(theme.getField("common", "scss")).toEqualTypeOf<string | null>();
+theme.setField("common", "scss", "body {}");
+theme.setField("common", "logo", "", 7, 2);
+theme.saveChanges("name", "color_scheme_id");
+theme.addChildTheme(theme);
+theme.removeChildTheme(theme);
+// The color palette manager assigns ids or clears them.
+theme.color_scheme_id = 5;
+theme.dark_color_scheme_id = null;
+// The translations panel stores what it loads.
+theme.translations = [{ key: "greeting", value: "Hello", default: "Hello" }];
+
+/* Subclassing, schema-route values and partial payloads. */
+
+expectTypeOf<typeof SiteSetting>().toExtend<typeof EmberObject>();
+expectTypeOf<typeof ThemeSettings>().toExtend<typeof SiteSetting>();
+expectTypeOf<typeof ThemeSiteSettings>().toExtend<typeof SiteSetting>();
+// findByName creates through SiteSetting explicitly, even on a subclass.
+expectTypeOf(
+ ThemeSettings.findByName("title")
+).resolves.toEqualTypeOf<SiteSetting>();
+expectTypeOf(themeSiteSetting.value).toEqualTypeOf<string>();
+expectTypeOf(setting.value).not.toBeAny();
+setting.value = { sections: [{ visible: true, id: 1 }] };
+setting.overridden = false;
+setting.computedValueProperty = "value";
+setting.computedNameProperty = null;
+expectTypeOf<SiteSetting["computedNameProperty"]>().toEqualTypeOf<
+ string | null
+>();
+setting.validValues = ["one", { name: "Two", value: 2 }];
+expectTypeOf(setting.validValues).not.toBeAny();
+setting.allowsNone = "admin.settings.none";
+setting.anyValue = true;
+expectTypeOf(setting.buffered.get("value")).toEqualTypeOf<
+ SiteSetting["value"]
+>();
+SiteSetting.bulkUpdate({ title: { value: "A", backfill: false } });
+expectTypeOf(themeSetting.loadMetadata(1)).not.toBeAny();
+
+expectTypeOf<ModelFor<"Theme">>().toEqualTypeOf<Theme>();
+expectTypeOf<ThemeCreateAttrs["name"]>().toEqualTypeOf<string | undefined>();
+expectTypeOf<ThemeCreateAttrs["color_scheme_id"]>().toEqualTypeOf<
+ number | null | undefined
+>();
+Theme.create({
+ settings: [{ setting: "count", type: "integer", value: 2, default: 1 }],
+});
+Theme.create({ settings: [{ type: "list", resolve_group_membership: true }] });
+Theme.munge({
+ settings: null,
+ themeable_site_settings: [{ setting: "title", value: "A", default: "B" }],
+});
+// The themes index serializer sends partial records.
+Theme.create({ id: 1, name: "Partial index record" });
+expectTypeOf(theme.isActive).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(theme.editedFields).toEqualTypeOf<ThemeField[] | undefined>();
+expectTypeOf(theme.isBroken).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(theme.remoteError).toEqualTypeOf<string | undefined>();
+expectTypeOf(theme.child_theme_ids).toEqualTypeOf<number[] | undefined>();
+expectTypeOf(theme.parentThemes).toEqualTypeOf<Theme[] | undefined>();