Skip to content

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

DEV: Refactor watched words to use tracked properties and filtered model (#36010)

Sérgio Saquetim4a951465cd5e
diff --git a/app/controllers/admin/watched_words_controller.rb b/app/controllers/admin/watched_words_controller.rb
index fa019a2ae10..797829adeb8 100644
--- a/app/controllers/admin/watched_words_controller.rb
+++ b/app/controllers/admin/watched_words_controller.rb
@@ -58,6 +58,8 @@ class Admin::WatchedWordsController < Admin::StaffController
begin
content = Encodings.to_utf8(File.read(file.tempfile, mode: "rb"))
+ words_updated = 0
+
CSV.parse(content) do |row|
if row[0].present? && (!has_replacement || row[1].present?)
watched_word =
@@ -68,16 +70,17 @@ class Admin::WatchedWordsController < Admin::StaffController
case_sensitive: "true" == row[2]&.strip&.downcase,
)
if watched_word.valid?
+ words_updated += 1
StaffActionLogger.new(current_user).log_watched_words_creation(watched_word)
end
end
end
- data = { url: "/ok" }
+ data = { result: "ok", words_updated: words_updated }
rescue => e
- data = failed_json.merge(errors: [e.message])
+ data = failed_json.merge(errors: [e.message], words_updated: words_updated)
end
- MessageBus.publish("/uploads/txt", data.as_json, client_ids: [params[:client_id]])
+ MessageBus.publish("/watched_words/upload", data.as_json, client_ids: [params[:client_id]])
end
render json: success_json
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 4617b0b0b1d..f9e96ed295a 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -7704,7 +7704,7 @@ en:
success: "Success"
exists: "Already exists"
upload: "Add from file"
- upload_successful: "Upload successful. Words have been added."
+ upload_successful: "Upload successful. The words will be processed shortly."
case_sensitivity_label: "Is case-sensitive"
case_sensitivity_description: "Only words with matching character casing"
html_label: "HTML"
diff --git a/frontend/discourse/admin/controllers/admin-watched-words.js b/frontend/discourse/admin/controllers/admin-watched-words.js
index b2a7e1113e3..942533a8bb5 100644
--- a/frontend/discourse/admin/controllers/admin-watched-words.js
+++ b/frontend/discourse/admin/controllers/admin-watched-words.js
@@ -1,51 +1,94 @@
+import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
import EmberObject, { action } from "@ember/object";
+import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
+import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { observes } from "@ember-decorators/object";
+import WatchedWord from "discourse/admin/models/watched-word";
+import { popupAjaxError } from "discourse/lib/ajax-error";
import discourseDebounce from "discourse/lib/debounce";
+import { bind } from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
+import { trackedArray } from "discourse/lib/tracked-tools";
+
+const MESSAGE_BUS_UPLOAD_PATH = "/watched_words/upload";
export default class AdminWatchedWordsController extends Controller {
- filter = null;
+ @service messageBus;
+
+ @tracked filter = null;
+ @trackedArray allWatchedWords;
+ @trackedArray filteredWatchedWords;
+
showWords = false;
- _filterContent() {
+ @observes("allWatchedWords", "filter")
+ filterContent() {
+ discourseDebounce(this, this.updateFilteredContent, INPUT_DELAY);
+ }
+
+ @bind
+ subscribe() {
+ this.messageBus.subscribe(MESSAGE_BUS_UPLOAD_PATH, this._onUploadMessage);
+ }
+
+ @bind
+ unsubscribe() {
+ this.messageBus.unsubscribe(MESSAGE_BUS_UPLOAD_PATH, this._onUploadMessage);
+ }
+
+ @bind
+ async updateAllWords() {
+ this.allWatchedWords = await WatchedWord.findAll();
+ this.filterContent();
+ }
+
+ @bind
+ updateFilteredContent() {
if (isEmpty(this.allWatchedWords)) {
return;
}
if (!this.filter) {
- this.set("model", this.allWatchedWords);
+ this.filteredWatchedWords = this.allWatchedWords;
return;
}
const filter = this.filter.toLowerCase();
- const model = [];
+ const filteredWatchedWords = [];
this.allWatchedWords.forEach((wordsForAction) => {
const wordRecords = wordsForAction.words.filter((wordRecord) => {
return wordRecord.word.includes(filter);
});
- model.pushObject(
+ filteredWatchedWords.push(
EmberObject.create({
nameKey: wordsForAction.nameKey,
name: wordsForAction.name,
- words: wordRecords,
+ words: new TrackedArray(wordRecords),
})
);
});
- this.set("model", model);
+
+ this.filteredWatchedWords = filteredWatchedWords;
}
- @observes("filter")
- filterContent() {
- discourseDebounce(this, this._filterContent, INPUT_DELAY);
+ @bind
+ async _onUploadMessage(message) {
+ if (message.words_updated > 0) {
+ await this.updateAllWords();
+ }
+
+ if (message.errors?.length) {
+ popupAjaxError(message.errors[0]);
+ }
}
@action
clearFilter() {
- this.set("filter", "");
+ this.filter = "";
}
@action
diff --git a/frontend/discourse/admin/controllers/admin-watched-words/action.js b/frontend/discourse/admin/controllers/admin-watched-words/action.js
index 72010b0dd06..db2e5b29dae 100644
--- a/frontend/discourse/admin/controllers/admin-watched-words/action.js
+++ b/frontend/discourse/admin/controllers/admin-watched-words/action.js
@@ -1,13 +1,12 @@
+import { tracked } from "@glimmer/tracking";
import Controller, { inject as controller } from "@ember/controller";
import { action } from "@ember/object";
import { or } from "@ember/object/computed";
import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import WatchedWordTestingModal from "discourse/admin/components/modal/watched-word-testing";
-import WatchedWord from "discourse/admin/models/watched-word";
import { ajax } from "discourse/lib/ajax";
import { fmt } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class AdminWatchedWordsActionController extends Controller {
@@ -15,7 +14,7 @@ export default class AdminWatchedWordsActionController extends Controller {
@service modal;
@controller adminWatchedWords;
- actionNameKey = null;
+ @tracked actionNameKey = null;
@fmt("actionNameKey", "/admin/customize/watched_words/action/%@/download")
downloadLink;
@@ -23,20 +22,20 @@ export default class AdminWatchedWordsActionController extends Controller {
@or("adminWatchedWords.showWords", "adminWatchedWords.filter")
showWordsList;
- findAction(actionName) {
- return (this.adminWatchedWords.model || []).find(
- (item) => item.nameKey === actionName
+ get currentAction() {
+ return this.adminWatchedWords.allWatchedWords.find(
+ (item) => item.nameKey === this.actionNameKey
);
}
- @discourseComputed("actionNameKey", "adminWatchedWords.model")
- currentAction(actionName) {
- return this.findAction(actionName);
+ get currentActionFiltered() {
+ return this.adminWatchedWords.filteredWatchedWords.find(
+ (item) => item.nameKey === this.actionNameKey
+ );
}
- @discourseComputed("currentAction.words.[]")
- regexpError(words) {
- for (const { regexp, word } of words) {
+ get regexpError() {
+ for (const { regexp, word } of this.currentAction.words) {
try {
RegExp(regexp);
} catch {
@@ -45,50 +44,60 @@ export default class AdminWatchedWordsActionController extends Controller {
}
}
- @discourseComputed("actionNameKey")
- actionDescription(actionNameKey) {
- return i18n(`admin.watched_words.action_descriptions.${actionNameKey}`);
+ get actionDescription() {
+ return i18n(
+ `admin.watched_words.action_descriptions.${this.actionNameKey}`
+ );
}
@action
recordAdded(arg) {
- const foundAction = this.findAction(this.actionNameKey);
- if (!foundAction) {
+ const currentAction = this.currentAction;
+ if (!currentAction) {
return;
}
- foundAction.words.unshiftObject(arg);
+ currentAction.words.unshift(arg);
schedule("afterRender", () => {
// remove from other actions lists
- for (const otherAction of this.adminWatchedWords.model) {
+ for (const otherAction of this.adminWatchedWords.filteredWatchedWords) {
if (otherAction.nameKey === this.actionNameKey) {
continue;
}
- const match = otherAction.words.find((w) => w.id === arg.id);
- if (match) {
- otherAction.words.removeObject(match);
+ const matchIndex = otherAction.words.findIndex((w) => w.id === arg.id);
+ if (matchIndex !== -1) {
+ otherAction.words.splice(matchIndex, 1);
break;
}
}
+
+ this.adminWatchedWords.updateFilteredContent();
});
}
@action
recordRemoved(arg) {
- this.currentAction?.words.removeObject(arg);
+ if (this.currentAction) {
+ const matchIndex = this.currentAction.words.findIndex(
+ (w) => w.id === arg.id
+ );
+ if (matchIndex !== -1) {
+ this.currentAction.words.splice(matchIndex, 1);
+ }
+ }
+
+ this.adminWatchedWords.updateFilteredContent();
}
@action
async uploadComplete() {
- const data = await WatchedWord.findAll();
- this.adminWatchedWords.set("model", data);
+ return this.adminWatchedWords.updateAllWords();
}
@action
async test() {
- const data = await WatchedWord.findAll();
- this.adminWatchedWords.set("model", data);
+ await this.adminWatchedWords.updateAllWords();
this.modal.show(WatchedWordTestingModal, {
model: { watchedWord: this.currentAction },
});
@@ -106,7 +115,11 @@ export default class AdminWatchedWordsActionController extends Controller {
type: "DELETE",
});
- this.findAction(actionKey)?.set("words", []);
+ const currentAction = this.currentAction;
+ if (currentAction) {
+ currentAction.words.length = 0;
+ this.adminWatchedWords.updateFilteredContent();
+ }
},
});
}
diff --git a/frontend/discourse/admin/models/watched-word.js b/frontend/discourse/admin/models/watched-word.js
index 2095ca5d659..4862423aeb5 100644
--- a/frontend/discourse/admin/models/watched-word.js
+++ b/frontend/discourse/admin/models/watched-word.js
@@ -1,27 +1,27 @@
import EmberObject from "@ember/object";
+import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { ajax } from "discourse/lib/ajax";
import { i18n } from "discourse-i18n";
export default class WatchedWord extends EmberObject {
- static findAll() {
- return ajax("/admin/customize/watched_words.json").then((list) => {
- const actions = {};
+ static async findAll() {
+ const list = await ajax("/admin/customize/watched_words.json");
+ const actions = {};
- list.actions.forEach((action) => {
- actions[action] = [];
- });
+ list.actions.forEach((action) => {
+ actions[action] = [];
+ });
- list.words.forEach((watchedWord) => {
- actions[watchedWord.action].pushObject(WatchedWord.create(watchedWord));
- });
+ list.words.forEach((watchedWord) => {
+ actions[watchedWord.action].push(WatchedWord.create(watchedWord));
+ });
- return Object.keys(actions).map((nameKey) => {
- return EmberObject.create({
- nameKey,
- name: i18n("admin.watched_words.actions." + nameKey),
- words: actions[nameKey],
- compiledRegularExpression: list.compiled_regular_expressions[nameKey],
- });
+ return Object.keys(actions).map((nameKey) => {
+ return EmberObject.create({
+ nameKey,
+ name: i18n("admin.watched_words.actions." + nameKey),
+ words: new TrackedArray(actions[nameKey]),
+ compiledRegularExpression: list.compiled_regular_expressions[nameKey],
});
});
}
diff --git a/frontend/discourse/admin/routes/admin-watched-words.js b/frontend/discourse/admin/routes/admin-watched-words.js
index 13efca96e37..5d7488c2cc7 100644
--- a/frontend/discourse/admin/routes/admin-watched-words.js
+++ b/frontend/discourse/admin/routes/admin-watched-words.js
@@ -16,8 +16,10 @@ export default class AdminWatchedWordsRoute extends DiscourseRoute {
return WatchedWord.findAll();
}
- afterModel(model) {
- const controller = this.controllerFor("adminWatchedWords");
- controller.set("allWatchedWords", model);
+ setupController(controller, model) {
+ controller.setProperties({
+ allWatchedWords: model,
+ filteredWatchedWords: model,
+ });
}
}
diff --git a/frontend/discourse/admin/templates/admin-watched-words.gjs b/frontend/discourse/admin/templates/admin-watched-words.gjs
index c02d0d31376..9a6db8641d9 100644
--- a/frontend/discourse/admin/templates/admin-watched-words.gjs
+++ b/frontend/discourse/admin/templates/admin-watched-words.gjs
@@ -1,3 +1,5 @@
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
import { LinkTo } from "@ember/routing";
import DBreadcrumbsItem from "discourse/components/d-breadcrumbs-item";
import DButton from "discourse/components/d-button";
@@ -43,9 +45,13 @@ export default <template>
</div>
</div>
- <div class="admin-nav pull-left">
+ <div
+ class="admin-nav pull-left"
+ {{didInsert @controller.subscribe}}
+ {{willDestroy @controller.unsubscribe}}
+ >
<ul class="nav nav-stacked">
- {{#each @controller.model as |watchedWordAction|}}
+ {{#each @controller.filteredWatchedWords as |watchedWordAction|}}
<li class={{watchedWordAction.nameKey}}>
<LinkTo
@route="adminWatchedWords.action"
diff --git a/frontend/discourse/admin/templates/admin-watched-words/action.gjs b/frontend/discourse/admin/templates/admin-watched-words/action.gjs
index dc8e7e4e14f..4fe4ba86d29 100644
--- a/frontend/discourse/admin/templates/admin-watched-words/action.gjs
+++ b/frontend/discourse/admin/templates/admin-watched-words/action.gjs
@@ -54,10 +54,10 @@ export default <template>
<WatchedWordForm
@actionKey={{@controller.actionNameKey}}
@action={{@controller.recordAdded}}
- @filteredContent={{@controller.currentAction.words}}
+ @filteredContent={{@controller.currentActionFiltered.words}}
/>
- {{#if @controller.currentAction.words}}
+ {{#if @controller.currentActionFiltered.words}}
<label class="show-words-checkbox">
<Input
@type="checkbox"
@@ -66,14 +66,14 @@ export default <template>
/>
{{i18n
"admin.watched_words.show_words"
}}
</label>
{{/if}}
{{#if @controller.showWordsList}}
<div class="watched-words-list watched-words-{{@controller.actionNameKey}}">
- {{#each @controller.currentAction.words as |word|}}
+ {{#each @controller.currentActionFiltered.words as |word|}}
<div class="watched-word-box">
<AdminWatchedWord
@actionKey={{@controller.actionNameKey}}