Skip to content

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

DEV: Add page-aware plugin APIs for saving user preferences (#36757)

Régis Hanolb66fca70d0e3
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 19b602e05a9..6c6fef4dda3 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -62,7 +62,7 @@ import { registerRichEditorExtension } from "discourse/lib/composer/rich-editor-
import deprecated from "discourse/lib/deprecated";
import { registerDesktopNotificationHandler } from "discourse/lib/desktop-notifications";
import { downloadCalendar } from "discourse/lib/download-calendar";
-import { isTesting } from "discourse/lib/environment";
+import { isDevelopment, isTesting } from "discourse/lib/environment";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
import { registerHashtagType } from "discourse/lib/hashtag-type-registry";
import { makeArray } from "discourse/lib/helpers";
@@ -2081,12 +2081,113 @@ class _PluginApi {
addAdvancedSearchOptions(options);
}
- addSaveableUserField(fieldName) {
+ /**
+ * Registers a user field that can be saved via the user preferences API.
+ * User fields are admin-defined profile fields stored in the user_fields table.
+ *
+ * @param {string} fieldName - The name of the user field to save
+ * @param {Object} [options] - Optional configuration
+ * @param {string} [options.page] - The preferences page where this field should be saved.
+ * Valid pages: "account", "emails", "interface", "navigation-menu", "notifications",
+ * "profile", "tags", "tracking", "users"
+ *
+ * @example
+ * // Register a user field that will be saved on the emails preferences page
+ * api.addSaveableUserField("newsletter_subscribe", { page: "emails" });
+ */
+ addSaveableUserField(fieldName, options = {}) {
addSaveableUserField(fieldName);
+
+ if (options.page) {
+ this.registerValueTransformer(
+ "preferences-save-attributes",
+ ({ value: attrs, context }) => {
+ if (context.page === options.page) {
+ attrs.push(fieldName);
+ }
+ return attrs;
+ }
+ );
+ }
}
- addSaveableUserOptionField(fieldName) {
+ /**
+ * Registers a user option that can be saved via the user preferences API.
+ * User options are preference settings stored in the user_options table.
+ *
+ * @param {string} fieldName - The name of the user option to save
+ * @param {Object} [options] - Optional configuration
+ * @param {string} [options.page] - The preferences page where this option should be saved.
+ * Valid pages: "account", "emails", "interface", "navigation-menu", "notifications",
+ * "profile", "tags", "tracking", "users"
+ *
+ * @example
+ * // Register a user option that will be saved on the emails preferences page
+ * api.addSaveableUserOption("chat_email_frequency", { page: "emails" });
+ *
+ * @example
+ * // Register a user option without specifying a page (for use with custom preference pages)
+ * api.addSaveableUserOption("my_custom_setting");
+ */
+ addSaveableUserOption(fieldName, options = {}) {
addSaveableUserOptionField(fieldName);
+
+ if (options.page) {
+ this.registerValueTransformer(
+ "preferences-save-attributes",
+ ({ value: attrs, context }) => {
+ if (context.page === options.page) {
+ attrs.push(fieldName);
+ }
+ return attrs;
+ }
+ );
+ }
+ }
+
+ /**
+ * @deprecated Use `addSaveableUserOption` instead
+ */
+ addSaveableUserOptionField(fieldName, options = {}) {
+ this.addSaveableUserOption(fieldName, options);
+ }
+
+ /**
+ * Ensures custom_fields are saved on a specific preferences page.
+ * Custom fields are stored in the user_custom_fields table.
+ *
+ * Unlike `addSaveableUserOption` and `addSaveableUserField` which track
+ * individual field names, this method ensures the entire `custom_fields`
+ * object is included in the save payload. Multiple plugins can safely
+ * call this for the same page - `custom_fields` will only be added once.
+ *
+ * @param {string} page - The preferences page where custom_fields should be saved.
+ * Valid pages: "account", "emails", "interface", "navigation-menu", "notifications",
+ * "profile", "tags", "tracking", "users"
+ *
+ * @example
+ * // Ensure custom_fields are saved on the notifications preferences page
+ * api.addSaveableCustomFields("notifications");
+ */
+ addSaveableCustomFields(page) {
+ if (!page) {
+ const message =
+ "addSaveableCustomFields requires a `page` argument to specify which preferences page should save custom_fields";
+ if (isDevelopment() || isTesting()) {
+ throw new Error(message);
+ }
+ return;
+ }
+
+ this.registerValueTransformer(
+ "preferences-save-attributes",
+ ({ value: attrs, context }) => {
+ if (context.page === page && !attrs.includes("custom_fields")) {
+ attrs.push("custom_fields");
+ }
+ return attrs;
+ }
+ );
}
/**
diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js
index a76734b9ded..dfcc2efa623 100644
--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js
+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-user-options.js
@@ -1,35 +1,26 @@
import { withPluginApi } from "discourse/lib/plugin-api";
-const CHAT_ENABLED_FIELD = "chat_enabled";
-const ONLY_CHAT_PUSH_NOTIFICATIONS_FIELD = "only_chat_push_notifications";
-const IGNORE_CHANNEL_WIDE_MENTION = "ignore_channel_wide_mention";
-const SHOW_THREAD_TITLE_PROMPTS = "show_thread_title_prompts";
-const CHAT_SOUND = "chat_sound";
-const CHAT_EMAIL_FREQUENCY = "chat_email_frequency";
-const CHAT_HEADER_INDICATOR_PREFERENCE = "chat_header_indicator_preference";
-const CHAT_SEPARATE_SIDEBAR_MODE = "chat_separate_sidebar_mode";
-const CHAT_SEND_SHORTCUT = "chat_send_shortcut";
-const CHAT_QUICK_REACTION_TYPE = "chat_quick_reaction_type";
-const CHAT_QUICK_REACTIONS_CUSTOM = "chat_quick_reactions_custom";
-
export default {
name: "chat-user-options",
initialize(container) {
withPluginApi((api) => {
- const siteSettings = container.lookup("service:site-settings");
- if (siteSettings.chat_enabled) {
- api.addSaveableUserOptionField(CHAT_ENABLED_FIELD);
- api.addSaveableUserOptionField(ONLY_CHAT_PUSH_NOTIFICATIONS_FIELD);
- api.addSaveableUserOptionField(IGNORE_CHANNEL_WIDE_MENTION);
- api.addSaveableUserOptionField(SHOW_THREAD_TITLE_PROMPTS);
- api.addSaveableUserOptionField(CHAT_SOUND);
- api.addSaveableUserOptionField(CHAT_EMAIL_FREQUENCY);
- api.addSaveableUserOptionField(CHAT_HEADER_INDICATOR_PREFERENCE);
- api.addSaveableUserOptionField(CHAT_SEPARATE_SIDEBAR_MODE);
- api.addSaveableUserOptionField(CHAT_SEND_SHORTCUT);
- api.addSaveableUserOptionField(CHAT_QUICK_REACTION_TYPE);
- api.addSaveableUserOptionField(CHAT_QUICK_REACTIONS_CUSTOM);
+ const { chat_enabled } = container.lookup("service:site-settings");
+
+ if (chat_enabled) {
+ // Chat settings
+ api.addSaveableUserOption("chat_enabled");
+ api.addSaveableUserOption("chat_header_indicator_preference");
+ api.addSaveableUserOption("chat_quick_reaction_type");
+ api.addSaveableUserOption("chat_quick_reactions_custom");
+ api.addSaveableUserOption("chat_send_shortcut");
+ api.addSaveableUserOption("chat_separate_sidebar_mode");
+ api.addSaveableUserOption("chat_sound");
+ api.addSaveableUserOption("ignore_channel_wide_mention");
+ api.addSaveableUserOption("only_chat_push_notifications");
+ api.addSaveableUserOption("show_thread_title_prompts");
+ // Email settings
+ api.addSaveableUserOption("chat_email_frequency", { page: "emails" });
}
});
},
diff --git a/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-user-options.js b/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-user-options.js
deleted file mode 100644
index 0dd00d9b992..00000000000
--- a/plugins/chat/assets/javascripts/discourse/pre-initializers/chat-user-options.js
+++ /dev/null
@@ -1,24 +0,0 @@
-import EmailsController from "discourse/controllers/preferences/emails";
-import { withPluginApi } from "discourse/lib/plugin-api";
-
-const FIELD_NAME = "chat_email_frequency";
-
-export default {
- name: "chat-user-options",
-
- initialize(container) {
- withPluginApi((api) => {
- const siteSettings = container.lookup("service:site-settings");
- if (siteSettings.chat_enabled) {
- api.addSaveableUserOptionField(FIELD_NAME);
- }
- });
-
- EmailsController.reopen({
- init() {
- this._super(...arguments);
- this.saveAttrNames.push(FIELD_NAME);
- },
- });
- },
-};
diff --git a/plugins/chat/test/javascripts/acceptance/chat-email-preferences-test.js b/plugins/chat/test/javascripts/acceptance/chat-email-preferences-test.js
new file mode 100644
index 00000000000..58bbdb80b64
--- /dev/null
+++ b/plugins/chat/test/javascripts/acceptance/chat-email-preferences-test.js
@@ -0,0 +1,44 @@
+import { click, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import {
+ acceptance,
+ updateCurrentUser,
+} from "discourse/tests/helpers/qunit-helpers";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+
+acceptance("Chat | Email Preferences", function (needs) {
+ needs.user();
+ needs.settings({
+ chat_enabled: true,
+ });
+
+ let savedData;
+ needs.pretender((server, helper) => {
+ server.put("/u/eviltrout.json", (request) => {
+ savedData = helper.parsePostData(request.requestBody);
+ return helper.response({ user: {} });
+ });
+ });
+
+ test("saves chat_email_frequency when saving email preferences", async function (assert) {
+ updateCurrentUser({
+ user_option: {
+ chat_email_frequency: "when_away",
+ },
+ });
+
+ await visit("/u/eviltrout/preferences/emails");
+
+ const dropdown = selectKit("#user_chat_email_frequency");
+ await dropdown.expand();
+ await dropdown.selectRowByValue("never");
+
+ await click(".save-changes");
+
+ assert.strictEqual(
+ savedData.chat_email_frequency,
+ "never",
+ "chat_email_frequency is included in saved data"
+ );
+ });
+});
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-search-discoveries.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-search-discoveries.js
index 5c37449751d..ad22297bb34 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-search-discoveries.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-search-discoveries.js
@@ -1,7 +1,5 @@
import { apiInitializer } from "discourse/lib/api";
-const FIELD_NAME = "ai_search_discoveries";
-
export default apiInitializer((api) => {
const currentUser = api.getCurrentUser();
const settings = api.container.lookup("service:site-settings");
@@ -13,17 +11,7 @@ export default apiInitializer((api) => {
return;
}
- api.addSaveableUserOptionField(FIELD_NAME);
-
- api.registerValueTransformer(
- "preferences-save-attributes",
- ({ value: attrs, context }) => {
- if (context.page === "interface") {
- attrs.push(FIELD_NAME);
- }
- return attrs;
- }
- );
+ api.addSaveableUserOption("ai_search_discoveries", { page: "interface" });
const discobotDiscoveries = api.container.lookup(
"service:discobot-discoveries"
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/connectors/user-preferences-tracking-topics/notification-level-when-assigned.gjs b/plugins/discourse-assign/assets/javascripts/discourse/connectors/user-preferences-tracking-topics/notification-level-when-assigned.gjs
index e8db5f052bf..f630c6c32f9 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/connectors/user-preferences-tracking-topics/notification-level-when-assigned.gjs
+++ b/plugins/discourse-assign/assets/javascripts/discourse/connectors/user-preferences-tracking-topics/notification-level-when-assigned.gjs
@@ -7,13 +7,6 @@ import { i18n } from "discourse-i18n";
export default class NotificationLevelWhenAssigned extends Component {
@service siteSettings;
- constructor(owner, args) {
- super(...arguments);
- if (this.siteSettings.assign_enabled) {
- args.outletArgs.customAttrNames.push("notification_level_when_assigned");
- }
- }
-
get notificationLevelsWhenAssigned() {
// The order matches the "notification level when replying" user preference
return [
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js b/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
index e178ca2db37..175054b17a5 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
+++ b/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
@@ -1,4 +1,3 @@
-import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
import { htmlSafe } from "@ember/template";
import { renderAvatar } from "discourse/helpers/user-avatar";
@@ -528,17 +527,7 @@ function initialize(api) {
"group-plus"
);
- api.modifyClass(
- "controller:preferences/notifications",
- (Superclass) =>
- class extends Superclass {
- @action
- save() {
- this.saveAttrNames.push("custom_fields");
- super.save(...arguments);
- }
- }
- );
+ api.addSaveableCustomFields("notifications");
api.addKeyboardShortcut("g a", "", { path: "/my/activity/assigned" });
}
@@ -706,7 +695,9 @@ export default {
api.addUserSearchOption("assignableGroups");
- api.addSaveableUserOptionField("notification_level_when_assigned");
+ api.addSaveableUserOption("notification_level_when_assigned", {
+ page: "tracking",
+ });
api.addBulkActionButton({
id: "assign-topics",
diff --git a/plugins/discourse-policy/assets/javascripts/pre-initializers/policy-user-options.js b/plugins/discourse-policy/assets/javascripts/pre-initializers/policy-user-options.js
index bacdef7fe0e..947448b3ea8 100644
--- a/plugins/discourse-policy/assets/javascripts/pre-initializers/policy-user-options.js
+++ b/plugins/discourse-policy/assets/javascripts/pre-initializers/policy-user-options.js
@@ -1,24 +1,17 @@
-import EmailsController from "discourse/controllers/preferences/emails";
import { withPluginApi } from "discourse/lib/plugin-api";
-const SEND_EMAIL_NOTIFICATIONS_FIELD = "policy_email_frequency";
-
export default {
name: "policy-user-options",
initialize(container) {
withPluginApi((api) => {
- const siteSettings = container.lookup("service:site-settings");
- if (siteSettings.policy_enabled) {
- api.addSaveableUserOptionField(SEND_EMAIL_NOTIFICATIONS_FIELD);
- }
- });
+ const { policy_enabled } = container.lookup("service:site-settings");
- EmailsController.reopen({
- init() {
- this._super(...arguments);
- this.saveAttrNames.push(SEND_EMAIL_NOTIFICATIONS_FIELD);
- },
+ if (policy_enabled) {
+ api.addSaveableUserOption("policy_email_frequency", {
+ page: "emails",
+ });
+ }
});
},
};
diff --git a/plugins/discourse-policy/test/javascripts/acceptance/policy-test.js b/plugins/discourse-policy/test/javascripts/acceptance/policy-test.js
index 781a32e96d6..21742b6118d 100644
--- a/plugins/discourse-policy/test/javascripts/acceptance/policy-test.js
+++ b/plugins/discourse-policy/test/javascripts/acceptance/policy-test.js
@@ -3,6 +3,10 @@ import { test } from "qunit";
import { cloneJSON } from "discourse/lib/object";
import postFixtures from "discourse/tests/fixtures/post";
import topicFixtures from "discourse/tests/fixtures/topic";
+import pretender, {
+ parsePostData,
+ response,
+} from "discourse/tests/helpers/create-pretender";
import {
acceptance,
updateCurrentUser,
@@ -63,8 +67,26 @@ acceptance("Discourse Policy - post", function (needs) {
});
test("edit email preferences", async function (assert) {
+ let savedData;
+ pretender.put("/u/eviltrout.json", (request) => {
+ savedData = parsePostData(request.requestBody);
+ return response({ user: {} });
+ });
+
await visit(`/u/eviltrout/preferences/emails`);
assert.dom("#user_policy_email_frequency").exists();
+
+ const dropdown = selectKit("#user_policy_email_frequency");
+ await dropdown.expand();
+ await dropdown.selectRowByValue("never");
+
+ await click(".save-changes");
+
+ assert.strictEqual(
+ savedData.policy_email_frequency,
+ "never",
+ "policy_email_frequency is included in saved data"
+ );
});
test("edit policy - staff", async function (assert) {
diff --git a/plugins/discourse-rewind/assets/javascripts/discourse/pre-initializers/rewind-user-options.js b/plugins/discourse-rewind/assets/javascripts/discourse/pre-initializers/rewind-user-options.js
index c3d0e400264..6b632fbb5cc 100644
--- a/plugins/discourse-rewind/assets/javascripts/discourse/pre-initializers/rewind-user-options.js
+++ b/plugins/discourse-rewind/assets/javascripts/discourse/pre-initializers/rewind-user-options.js
@@ -1,17 +1,17 @@
import { withPluginApi } from "discourse/lib/plugin-api";
-const ENABLED_FIELD_NAME = "discourse_rewind_enabled";
-const SHARE_FIELD_NAME = "discourse_rewind_share_publicly";
-
export default {
name: "rewind-user-options",
initialize(container) {
withPluginApi((api) => {
- const siteSettings = container.lookup("service:site-settings");
- if (siteSettings.discourse_rewind_enabled) {
- api.addSaveableUserOptionField(ENABLED_FIELD_NAME);
- api.addSaveableUserOptionField(SHARE_FIELD_NAME);
+ const { discourse_rewind_enabled } = container.lookup(
+ "service:site-settings"
+ );
+
+ if (discourse_rewind_enabled) {
+ api.addSaveableUserOption("discourse_rewind_enabled");
+ api.addSaveableUserOption("discourse_rewind_share_publicly");
}
});
},