A platform for community discussion. Free, open, simple.
DEV: update solved initializers to avoid using modifyClass pattern (#37918)
David Battersby80791e098093
diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.jsindex 844dc0012d4..cc23eb85b54 100644--- a/frontend/discourse/app/controllers/topic.js+++ b/frontend/discourse/app/controllers/topic.js@@ -37,6 +37,7 @@ import QuoteState from "discourse/lib/quote-state";import { extractLinkMeta } from "discourse/lib/render-topic-featured-link";import { fancyTitle } from "discourse/lib/topic-fancy-title";import { trackedArray } from "discourse/lib/tracked-tools";+import { applyBehaviorTransformer } from "discourse/lib/transformer";import DiscourseURL, { userPath } from "discourse/lib/url";import { escapeExpression } from "discourse/lib/utilities";import Bookmark, { AUTO_DELETE_PREFERENCES } from "discourse/models/bookmark";@@ -1252,25 +1253,37 @@ export default class TopicController extends Controller {if (!this.editingTopic) {return;}- const props = this.get("buffered.buffer");- const hasCategoryOrTagChanges =- props.category_id !== undefined || props.tags !== undefined;- try {- if (this.editingTopicLocalization) {- await this._saveTopicLocalization();- }+ return applyBehaviorTransformer(+ "topic-controller:finished-editing",+ async ({ context }) => {+ const props = context.buffered;+ const hasCategoryOrTagChanges =+ props.category_id !== undefined || props.tags !== undefined;- if (hasCategoryOrTagChanges || !this.editingTopicLocalization) {- await Topic.update(this.model, props, { fastEdit: true });- }+ try {+ if (context.editingTopicLocalization) {+ await this._saveTopicLocalization();+ }- this.buffered.discardChanges();- this._resetTranslationState();- this.set("editingTopic", false);- } catch (error) {- popupAjaxError(error);- }+ if (hasCategoryOrTagChanges || !context.editingTopicLocalization) {+ await Topic.update(context.model, props, { fastEdit: true });+ }++ this.buffered.discardChanges();+ this._resetTranslationState();+ this.set("editingTopic", false);+ } catch (error) {+ popupAjaxError(error);+ }+ },+ {+ editingTopic: this.editingTopic,+ editingTopicLocalization: this.editingTopicLocalization,+ buffered: this.get("buffered.buffer"),+ model: this.model,+ }+ );}async _saveTopicLocalization() {diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjsindex 9e4506cc78a..989823c4297 100644--- a/frontend/discourse/app/lib/plugin-api.gjs+++ b/frontend/discourse/app/lib/plugin-api.gjs@@ -117,7 +117,10 @@ import Composer, {} from "discourse/models/composer";import { addNavItem } from "discourse/models/nav-item";import { _addTrackedPostProperty } from "discourse/models/post";-import { registerCustomLastUnreadUrlCallback } from "discourse/models/topic";+import {+ _addTrackedTopicProperty,+ registerCustomLastUnreadUrlCallback,+} from "discourse/models/topic";import {addSaveableUserField,addSaveableUserOptionField,@@ -736,6 +739,20 @@ class _PluginApi {names.forEach((name) => _addTrackedPostProperty(name));}+ /**+ * Adds tracked properties to the topic model.+ *+ * This method is used to mark properties as tracked for topic updates.+ *+ * You'll need to do this if you've added properties to a Topic and need them to be+ * automatically updated in the UI when there are changes in the model.+ *+ * @param {...string} names - The names of the properties to be tracked.+ */+ addTrackedTopicProperties(...names) {+ names.forEach((name) => _addTrackedTopicProperty(name));+ }+/*** Decommissioned API**/diff --git a/frontend/discourse/app/lib/transformer/registry.js b/frontend/discourse/app/lib/transformer/registry.jsindex a80f8d11efd..c47ae2f880e 100644--- a/frontend/discourse/app/lib/transformer/registry.js+++ b/frontend/discourse/app/lib/transformer/registry.js@@ -6,6 +6,7 @@ export const BEHAVIOR_TRANSFORMERS = Object.freeze(["full-page-search-load-more","post-menu-toggle-like-action","post-stream-error-loading",+ "topic-controller:finished-editing","topic-list-item-click",]);diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.jsindex 3cd7bdfc162..44feb61b39b 100644--- a/frontend/discourse/app/models/topic.js+++ b/frontend/discourse/app/models/topic.js@@ -19,7 +19,10 @@ import { deepMerge } from "discourse/lib/object";import PreloadStore from "discourse/lib/preload-store";import { emojiUnescape } from "discourse/lib/text";import { fancyTitle } from "discourse/lib/topic-fancy-title";-import { trackedArray } from "discourse/lib/tracked-tools";+import {+ defineTrackedProperty,+ trackedArray,+} from "discourse/lib/tracked-tools";import DiscourseURL, { userPath } from "discourse/lib/url";import ActionSummary from "discourse/models/action-summary";import Bookmark from "discourse/models/bookmark";@@ -30,6 +33,16 @@ import { flushMap } from "discourse/services/store";import { i18n } from "discourse-i18n";import Category from "./category";+const pluginTrackedProperties = new Set();++export function _addTrackedTopicProperty(propertyKey) {+ pluginTrackedProperties.add(propertyKey);+}++export function clearAddedTrackedTopicProperties() {+ pluginTrackedProperties.clear();+}+export function loadTopicView(topic, args) {const data = deepMerge({}, args);const url = `/t/${topic.id}`;@@ -347,6 +360,14 @@ export default class Topic extends RestModel {topic: this,});+ constructor() {+ super(...arguments);++ pluginTrackedProperties.forEach((propertyKey) => {+ defineTrackedProperty(this, propertyKey);+ });+ }+@discourseComputed("last_read_post_number", "highest_post_number")visited(lastReadPostNumber, highestPostNumber) {// >= to handle case where there are deleted posts at the end of the topicdiff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.jsindex b9c8a595c12..ec0c4734067 100644--- a/frontend/discourse/tests/helpers/qunit-helpers.js+++ b/frontend/discourse/tests/helpers/qunit-helpers.js@@ -90,6 +90,7 @@ import { clearNavItems } from "discourse/models/nav-item";import { clearAddedTrackedPostProperties } from "discourse/models/post";import { resetLastEditNotificationClick } from "discourse/models/post-stream";import Site from "discourse/models/site";+import { clearAddedTrackedTopicProperties } from "discourse/models/topic";import User from "discourse/models/user";import { clearResolverOptions } from "discourse/resolver";import { _clearSnapshots } from "discourse/select-kit/components/composer-actions";@@ -268,6 +269,7 @@ export function testCleanup(container, app) {clearRegisteredTabs();clearRegisteredEditCategoryTabs();clearAddedTrackedPostProperties();+ clearAddedTrackedTopicProperties();resetGroupPostSmallActionCodes();enableClearA11yAnnouncementsInTests();resetHtmlDecorators();diff --git a/frontend/discourse/tests/unit/controllers/topic-test.js b/frontend/discourse/tests/unit/controllers/topic-test.jsindex 145752ffad7..dec99c855b2 100644--- a/frontend/discourse/tests/unit/controllers/topic-test.js+++ b/frontend/discourse/tests/unit/controllers/topic-test.js@@ -6,6 +6,7 @@ import { module, test } from "qunit";import sinon from "sinon";import { removeValueFromArray } from "discourse/lib/array-tools";import { forceMobile } from "discourse/lib/mobile";+import { withPluginApi } from "discourse/lib/plugin-api";import { Placeholder } from "discourse/models/post-stream";import pretender, { response } from "discourse/tests/helpers/create-pretender";@@ -621,4 +622,44 @@ module("Unit | Controller | topic", function (hooks) {assert.true(destroyed, "post was destroyed");});++ test("topic-controller:finished-editing behavior transformer", async function (assert) {+ const controller = getOwner(this).lookup("controller:topic");+ const model = this.store.createRecord("topic", {+ id: 123,+ title: "Test",+ });+ controller.setProperties({ model });+ controller.set("editingTopic", true);++ sinon.stub(model.constructor, "update").resolves();+ sinon.stub(controller, "send");++ withPluginApi((api) => {+ api.registerBehaviorTransformer(+ "topic-controller:finished-editing",+ ({ next }) => {+ if (controller.blockWithTransformer) {+ return;+ }+ next();+ }+ );+ });++ controller.blockWithTransformer = true;+ await controller.finishedEditingTopic();++ assert.true(+ controller.editingTopic,+ "transformer blocked finishedEditingTopic"+ );++ controller.blockWithTransformer = false;+ await controller.finishedEditingTopic();+ assert.false(+ controller.editingTopic,+ "transformer allowed finishedEditingTopic"+ );+ });});diff --git a/frontend/discourse/tests/unit/models/topic-test.js b/frontend/discourse/tests/unit/models/topic-test.jsindex d13bd425cfc..dc7cb58fd48 100644--- a/frontend/discourse/tests/unit/models/topic-test.js+++ b/frontend/discourse/tests/unit/models/topic-test.js@@ -2,6 +2,7 @@ import { getOwner } from "@ember/owner";import { setupTest } from "ember-qunit";import { IMAGE_VERSION as v } from "pretty-text/emoji/version";import { module, test } from "qunit";+import { withPluginApi } from "discourse/lib/plugin-api";import Category from "discourse/models/category";import Topic from "discourse/models/topic";import TopicDetails from "discourse/models/topic-details";@@ -254,4 +255,43 @@ module("Unit | Model | topic", function (hooks) {assert.false(invisibleTopic.visible);assert.true(invisibleTopic.invisible);});++ test("addTrackedTopicProperties", function (assert) {+ withPluginApi((api) => {+ api.addTrackedTopicProperties("plugin_property", "other_plugin_property");+ });++ const topic = this.store.createRecord("topic", { id: 1234 });++ topic.plugin_property = "test value";+ topic.other_plugin_property = "other value";++ assert.strictEqual(+ topic.plugin_property,+ "test value",+ "plugin tracked property can be set and read via direct assignment"+ );+ assert.strictEqual(+ topic.other_plugin_property,+ "other value",+ "other plugin tracked property can be set and read via direct assignment"+ );++ topic.updateFromJson({+ details: {},+ plugin_property: "updated value",+ other_plugin_property: "other updated value",+ });++ assert.strictEqual(+ topic.plugin_property,+ "updated value",+ "plugin tracked property is updated via updateFromJson"+ );+ assert.strictEqual(+ topic.other_plugin_property,+ "other updated value",+ "other plugin tracked property is updated via updateFromJson"+ );+ });});diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjsindex 782cd1006dc..50fd5bf2d37 100644--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-accept-answer-button.gjs@@ -5,6 +5,7 @@ import { service } from "@ember/service";import DButton from "discourse/components/d-button";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";+import setAcceptedSolution from "../lib/set-accepted-solution";export default class SolvedAcceptAnswerButton extends Component {static hidden(args) {@@ -62,7 +63,7 @@ async function acceptPost(post) {data: { id: post.id },});- topic.setAcceptedSolution(acceptedAnswer);+ setAcceptedSolution(topic, acceptedAnswer);} catch (e) {popupAjaxError(e);}diff --git a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjsindex 219bb5af48d..44464dacf7c 100644--- a/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs+++ b/plugins/discourse-solved/assets/javascripts/discourse/components/solved-unaccept-answer-button.gjs@@ -11,6 +11,7 @@ import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { and } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";+import setAcceptedSolution from "../lib/set-accepted-solution";export default class SolvedUnacceptAnswerButton extends Component {@service appEvents;@@ -118,7 +119,7 @@ async function unacceptPost(post) {data: { id: post.id },});- topic.setAcceptedSolution(undefined);+ setAcceptedSolution(topic, undefined);} catch (e) {popupAjaxError(e);}diff --git a/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs b/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjsindex be566b168ed..146bdadd703 100644--- a/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs+++ b/plugins/discourse-solved/assets/javascripts/discourse/initializers/extend-for-solved-button.gjs@@ -1,10 +1,10 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";import { withPluginApi } from "discourse/lib/plugin-api";import { i18n } from "discourse-i18n";import SolvedAcceptAnswerButton from "../components/solved-accept-answer-button";import SolvedAcceptedAnswer from "../components/solved-accepted-answer";import SolvedUnacceptAnswerButton from "../components/solved-unaccept-answer-button";+import setAcceptedSolution from "../lib/set-accepted-solution";function initializeWithApi(api) {customizePost(api);@@ -15,40 +15,7 @@ function initializeWithApi(api) {api.addDiscoveryQueryParam("solved", { replace: true, refreshModel: true });}- api.modifyClass(- "model:topic",- (Superclass) =>- class extends Superclass {- @tracked accepted_answer;- @tracked has_accepted_answer;-- setAcceptedSolution(acceptedAnswer) {- this.postStream?.posts?.forEach((post) => {- if (!acceptedAnswer) {- post.setProperties({- accepted_answer: false,- topic_accepted_answer: false,- });- } else if (post.post_number > 1) {- post.setProperties(- acceptedAnswer.post_number === post.post_number- ? {- accepted_answer: true,- topic_accepted_answer: true,- }- : {- accepted_answer: false,- topic_accepted_answer: true,- }- );- }- });-- this.accepted_answer = acceptedAnswer;- this.has_accepted_answer = !!acceptedAnswer;- }- }- );+ api.addTrackedTopicProperties("accepted_answer", "has_accepted_answer");}function customizePost(api) {@@ -122,7 +89,7 @@ function handleMessages(api) {const topic = controller.model;if (topic) {- topic.setAcceptedSolution(message.accepted_answer);+ setAcceptedSolution(topic, message.accepted_answer);}};diff --git a/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjs b/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjsindex c17e1284ac7..062e633fbbd 100644--- a/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjs+++ b/plugins/discourse-solved/assets/javascripts/discourse/initializers/solved-category-change-confirmation.gjs@@ -1,82 +1,74 @@-import { action } from "@ember/object";+import { helperContext } from "discourse/lib/helpers";import { withPluginApi } from "discourse/lib/plugin-api";import Category from "discourse/models/category";import SolvedRemovalConfirmationModal from "../components/modal/solved-removal-confirmation";const STORAGE_KEY = "discourse-solved-hide-category-change-confirmation";-export default {- name: "solved-category-change-confirmation",-- initialize() {- withPluginApi((api) => {- api.modifyClass(- "controller:topic",- (Superclass) =>- class extends Superclass {- _solvedEnabled(categoryId, tags) {- if (- this.siteSettings.allow_solved_on_all_topics ||- Category.findById(categoryId)?.custom_fields- ?.enable_accepted_answers === "true"- ) {- return true;- }-- const solvedTags = this.siteSettings.enable_solved_tags- .split("|")- .filter(Boolean);-- return (tags || []).some((t) => solvedTags.includes(t.name));- }-- @action- async finishedEditingTopic() {- if (!this.editingTopic) {- return;- }+function solvedEnabled(categoryId, tags) {+ const siteSettings = helperContext().siteSettings;- const props = this.get("buffered.buffer");- let solvedStateChanged = false;+ if (+ siteSettings.allow_solved_on_all_topics ||+ Category.findById(categoryId)?.custom_fields?.enable_accepted_answers ===+ "true"+ ) {+ return true;+ }- if ("category_id" in props || "tags" in props) {- const oldCategoryId = this.model.category_id;- const newCategoryId = props.category_id ?? oldCategoryId;- const oldTags = this.model.tags;- const newTags = props.tags ?? oldTags;+ const solvedTags = siteSettings.enable_solved_tags.split("|").filter(Boolean);- const oldAllowed = this._solvedEnabled(oldCategoryId, oldTags);- const newAllowed = this._solvedEnabled(newCategoryId, newTags);+ return (tags || []).some((t) => solvedTags.includes(t.name));+}- solvedStateChanged = oldAllowed !== newAllowed;-- if (this.model.accepted_answer && oldAllowed && !newAllowed) {- const showConfirmation =- localStorage.getItem(STORAGE_KEY) !== "true";-- if (showConfirmation) {- const result = await this.modal.show(- SolvedRemovalConfirmationModal- );+export default {+ name: "solved-category-change-confirmation",- if (!result?.confirmed) {- return;- }+ initialize() {+ withPluginApi((api) => {+ api.registerBehaviorTransformer(+ "topic-controller:finished-editing",+ async ({ next, context }) => {+ const modal = api.container.lookup("service:modal");+ const props = context.buffered;+ const model = context.model;+ let solvedStateChanged = false;++ if ("category_id" in props || "tags" in props) {+ const oldCategoryId = model.category_id;+ const newCategoryId = props.category_id ?? oldCategoryId;+ const oldTags = model.tags;+ const newTags = props.tags ?? oldTags;++ const oldAllowed = solvedEnabled(oldCategoryId, oldTags);+ const newAllowed = solvedEnabled(newCategoryId, newTags);++ solvedStateChanged = oldAllowed !== newAllowed;++ if (model.accepted_answer && oldAllowed && !newAllowed) {+ const showConfirmation =+ localStorage.getItem(STORAGE_KEY) !== "true";++ if (showConfirmation) {+ const result = await modal.show(SolvedRemovalConfirmationModal);++ if (!result?.confirmed) {+ return;+ }- if (result.dontShowAgain) {- localStorage.setItem(STORAGE_KEY, "true");- }- }+ if (result.dontShowAgain) {+ localStorage.setItem(STORAGE_KEY, "true");}}+ }+ }- await super.finishedEditingTopic();+ await next();- if (solvedStateChanged) {- this.model.postStream.refresh({ forceLoad: true });- }- }+ if (solvedStateChanged) {+ model.postStream.refresh({ forceLoad: true });}+ });});},diff --git a/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solution.js b/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solution.jsnew file mode 100644index 00000000000..6c29998244b--- /dev/null+++ b/plugins/discourse-solved/assets/javascripts/discourse/lib/set-accepted-solution.js@@ -0,0 +1,25 @@+export default function setAcceptedSolution(topic, acceptedAnswer) {+ topic.postStream?.posts?.forEach((post) => {+ if (!acceptedAnswer) {+ post.setProperties({+ accepted_answer: false,+ topic_accepted_answer: false,+ });+ } else if (post.post_number > 1) {+ post.setProperties(+ acceptedAnswer.post_number === post.post_number+ ? {+ accepted_answer: true,+ topic_accepted_answer: true,+ }+ : {+ accepted_answer: false,+ topic_accepted_answer: true,+ }+ );+ }+ });++ topic.accepted_answer = acceptedAnswer;+ topic.has_accepted_answer = !!acceptedAnswer;+}