Skip to content

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

FIX: Stop reviewable state from leaking to the next reviewable (#42744)

Régis Hanol3f7cf1139da1
diff --git a/frontend/discourse/app/components/reviewable/item.gjs b/frontend/discourse/app/components/reviewable/item.gjs
index 8a0c4e33a45..0effdb51222 100644
--- a/frontend/discourse/app/components/reviewable/item.gjs
+++ b/frontend/discourse/app/components/reviewable/item.gjs
@@ -1,13 +1,12 @@
-/* eslint-disable ember/no-classic-components */
-import { tracked } from "@glimmer/tracking";
-import Component from "@ember/component";
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
import { fn, get } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action, computed, set } from "@ember/object";
+import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
+import { trackedObject } from "@ember/reactive/collections";
import { service } from "@ember/service";
import { classify, dasherize } from "@ember/string";
-import { tagName } from "@ember-decorators/component";
import ScrubRejectedUserModal from "discourse/admin/components/modal/scrub-rejected-user";
import ExplainReviewableModal from "discourse/components/modal/explain-reviewable";
import RejectReasonReviewableModal from "discourse/components/modal/reject-reason-reviewable";
@@ -97,7 +96,6 @@ export function registerReviewableTypeLabel(reviewableType, labelKey) {
reviewableTypeLabels[reviewableType] = labelKey;
}
-@tagName("")
export default class ReviewableItem extends Component {
@service dialog;
@service modal;
@@ -110,17 +108,10 @@ export default class ReviewableItem extends Component {
@optionalService adminTools;
@tracked disabled = false;
- @tracked activeTab = "timeline";
- @tracked insightsOpened = false;
-
- updating = null;
- editing = false;
- _updates = null;
- _previousReviewableId = null;
+ @tracked updating = false;
constructor() {
super(...arguments);
- this._previousReviewableId = this.reviewable?.id;
this.messageBus.subscribe("/reviewable_claimed", this._updateClaimedBy);
this.messageBus.subscribe("/reviewable_action", this._updateStatus);
}
@@ -131,13 +122,20 @@ export default class ReviewableItem extends Component {
this.messageBus.unsubscribe("/reviewable_action", this._updateStatus);
}
- didUpdateAttrs() {
- super.didUpdateAttrs(...arguments);
- if (this.reviewable?.id !== this._previousReviewableId) {
- this._previousReviewableId = this.reviewable?.id;
- this.activeTab = "timeline";
- this.insightsOpened = false;
- }
+ @cached
+ get state() {
+ // reading the argument is what ties this cache to a single reviewable
+ this.args.reviewable;
+
+ return trackedObject({
+ activeTab: "timeline",
+ insightsOpened: false,
+ updates: null,
+ });
+ }
+
+ get editing() {
+ return this.state.updates !== null;
}
@bind
@@ -145,89 +143,67 @@ export default class ReviewableItem extends Component {
return resolveReviewableComponent(getOwner(this), type);
}
- @computed(
- "reviewable.type",
- "reviewable.last_performing_username",
- "siteSettings.blur_tl0_flagged_posts_media",
- "reviewable.target_created_by_trust_level",
- "reviewable.deleted_at"
- )
get customClasses() {
- let classes = dasherize(this.reviewable?.type);
+ const { reviewable } = this.args;
+ let classes = dasherize(reviewable?.type);
- if (this.reviewable?.last_performing_username) {
+ if (reviewable?.last_performing_username) {
classes = `${classes} reviewable-stale`;
}
if (
this.siteSettings?.blur_tl0_flagged_posts_media &&
- this.reviewable?.target_created_by_trust_level === 0
+ reviewable?.target_created_by_trust_level === 0
) {
classes = `${classes} blur-images`;
}
- if (this.reviewable?.deleted_at) {
+ if (reviewable?.deleted_at) {
classes = `${classes} reviewable-deleted`;
}
return classes;
}
- @computed(
- "reviewable.created_from_flag",
- "reviewable.status",
- "claimOptional",
- "claimRequired",
- "reviewable.claimed_by",
- "isAiReviewable"
- )
get displayContextQuestion() {
+ const { reviewable } = this.args;
+
return (
- (this.reviewable?.created_from_flag &&
- this.reviewable?.status === PENDING &&
+ (reviewable?.created_from_flag &&
+ reviewable?.status === PENDING &&
(this.claimOptional ||
- (this.claimRequired && this.reviewable?.claimed_by !== null))) ||
+ (this.claimRequired && reviewable?.claimed_by !== null))) ||
this.isAiReviewable
);
}
- @computed("reviewable.type")
get isAiReviewable() {
- return (
- this.reviewable?.type === "ReviewableAiChatMessage" ||
- this.reviewable?.type === "ReviewableAiPost"
- );
+ const { type } = this.args.reviewable ?? {};
+
+ return type === "ReviewableAiChatMessage" || type === "ReviewableAiPost";
}
- @computed(
- "reviewable.topic",
- "reviewable.topic_id",
- "reviewable.removed_topic_id"
- )
get topicId() {
+ const { reviewable } = this.args;
+
return (
- (this.reviewable?.topic && this.reviewable?.topic?.id) ||
- this.reviewable?.topic_id ||
- this.reviewable?.removed_topic_id
+ reviewable?.topic?.id ||
+ reviewable?.topic_id ||
+ reviewable?.removed_topic_id
);
}
- @computed(
- "siteSettings.reviewable_claiming",
- "topicId",
- "reviewable.claimed_by.automatic",
- "reviewable.status"
- )
get claimEnabled() {
+ const { reviewable } = this.args;
+
return (
(this.siteSettings?.reviewable_claiming !== "disabled" ||
- this.reviewable?.claimed_by?.automatic) &&
+ reviewable?.claimed_by?.automatic) &&
!!this.topicId &&
- this.reviewable?.status === PENDING
+ reviewable?.status === PENDING
);
}
- @computed("siteSettings.reviewable_claiming", "claimEnabled")
get claimOptional() {
return (
!this.claimEnabled ||
@@ -235,42 +211,37 @@ export default class ReviewableItem extends Component {
);
}
- @computed("siteSettings.reviewable_claiming", "claimEnabled")
get claimRequired() {
return (
this.claimEnabled && this.siteSettings?.reviewable_claiming === "required"
);
}
- @computed(
- "claimEnabled",
- "siteSettings.reviewable_claiming",
- "reviewable.claimed_by",
- "reviewable.bundled_actions"
- )
get canPerform() {
- if (this.reviewable?.bundled_actions?.length === 0) {
+ const { reviewable } = this.args;
+
+ if (reviewable?.bundled_actions?.length === 0) {
return false;
}
if (!this.claimEnabled) {
return true;
}
- if (this.reviewable?.claimed_by) {
- return this.reviewable?.claimed_by?.user.id === this.currentUser.id;
+ if (reviewable?.claimed_by) {
+ return reviewable.claimed_by.user.id === this.currentUser.id;
}
return this.siteSettings?.reviewable_claiming !== "required";
}
- @computed("_updates.category_id", "reviewable.category.id")
get tagCategoryId() {
- return this._updates?.category_id || this.reviewable?.category?.id;
+ return (
+ this.state.updates?.category_id || this.args.reviewable?.category?.id
+ );
}
- @computed("reviewable.reviewable_scores")
get scoreSummary() {
- const scoreData = this.reviewable?.reviewable_scores?.reduce(
+ const scoreData = this.args.reviewable?.reviewable_scores?.reduce(
(acc, score) => {
if (!acc[score.score_type.type]) {
acc[score.score_type.type] = {
@@ -289,30 +260,31 @@ export default class ReviewableItem extends Component {
return Object.values(scoreData);
}
- @computed("reviewable.type", "reviewable.created_from_flag", "topicId")
get reviewableTypeLabel() {
+ const { reviewable } = this.args;
+
// handle plugin types
- if (reviewableTypeLabels[this.reviewable?.type]) {
- return reviewableTypeLabels[this.reviewable?.type];
+ if (reviewableTypeLabels[reviewable?.type]) {
+ return reviewableTypeLabels[reviewable?.type];
}
// core types
- if (this.reviewable?.type === "ReviewableUser") {
+ if (reviewable?.type === "ReviewableUser") {
return "review.user_label";
}
- if (this.reviewable?.type === "ReviewableQueuedPost") {
+ if (reviewable?.type === "ReviewableQueuedPost") {
// if topic_id is null it's a new topic
return this.topicId
? "review.queued_post_label"
: "review.queued_topic_label";
}
- if (this.reviewable?.type === "ReviewableChatMessage") {
+ if (reviewable?.type === "ReviewableChatMessage") {
return "review.chat_flagged_as";
}
- if (this.reviewable?.created_from_flag) {
+ if (reviewable?.created_from_flag) {
return "review.post_flagged_as";
}
@@ -326,44 +298,46 @@ export default class ReviewableItem extends Component {
return;
}
+ const { reviewable } = this.args;
const user = this.store.createRecord("user", data.user);
- this.reviewable.set(
- "claimed_by",
- data.claimed ? { user, automatic: data.automatic } : null
- );
+ reviewable.claimed_by = data.claimed
+ ? { user, automatic: data.automatic }
+ : null;
- if (data.automatic || this.reviewable.status !== PENDING) {
+ if (data.automatic || reviewable.status !== PENDING) {
return;
}
- this.reviewable.set("reviewable_histories", [
- ...this.reviewable.reviewable_histories,
+ reviewable.reviewable_histories = [
+ ...reviewable.reviewable_histories,
{
reviewable_history_type: data.claimed ? CLAIMED : UNCLAIMED,
created_at: new Date().toISOString(),
created_by: user,
},
- ]);
+ ];
}
@bind
_updateStatus(data) {
- if (data.remove_reviewable_ids?.includes(this.reviewable.id)) {
+ const { reviewable } = this.args;
+
+ if (data.remove_reviewable_ids?.includes(reviewable.id)) {
delete data.remove_reviewable_ids;
- this._performResult(data, {}, this.reviewable);
+ this._performResult(data, {}, reviewable);
}
}
@bind
async _performConfirmed(performableAction, additionalData = {}) {
- let reviewable = this.reviewable;
+ let reviewable = this.args.reviewable;
let performAction = async () => {
this.disabled = true;
- let version = reviewable.get("version");
- this.set("updating", true);
+ let version = reviewable.version;
+ this.updating = true;
const data = {
send_email: reviewable.sendEmail,
@@ -393,7 +367,7 @@ export default class ReviewableItem extends Component {
)
)
.finally(() => {
- this.set("updating", false);
+ this.updating = false;
this.disabled = false;
});
};
@@ -441,11 +415,11 @@ export default class ReviewableItem extends Component {
});
}
- if (this.remove && result.remove_reviewable_ids?.length > 0) {
- this.remove(result.remove_reviewable_ids);
+ if (this.args.remove && result.remove_reviewable_ids?.length > 0) {
+ this.args.remove(result.remove_reviewable_ids);
} else {
- if (this.updateStatuses && result.reviewable_updates) {
- this.updateStatuses(result.reviewable_updates);
+ if (this.args.updateStatuses && result.reviewable_updates) {
+ this.args.updateStatuses(result.reviewable_updates);
}
return this.store.find("reviewable", reviewable.id);
@@ -463,13 +437,11 @@ export default class ReviewableItem extends Component {
@bind
async scrubRejectedUser(reason) {
+ const { id } = this.args.reviewable;
+
try {
- await ajax({
- url: `/review/${this.reviewable.id}/scrub`,
- type: "PUT",
- data: { reason },
- });
- this.store.find("reviewable", this.reviewable.id);
+ await ajax({ url: `/review/${id}/scrub`, type: "PUT", data: { reason } });
+ this.store.find("reviewable", id);
} catch (e) {
popupAjaxError(e);
}
@@ -513,57 +485,55 @@ export default class ReviewableItem extends Component {
_penalize(adminToolMethod, reviewable, performAction) {
let adminTools = this.adminTools;
if (adminTools) {
- let createdBy = reviewable.get("target_created_by");
- let postId = reviewable.get("post_id");
- let postEdit = reviewable.get("raw") ?? reviewable.get("payload.raw");
+ let createdBy = reviewable.target_created_by;
+ let postId = reviewable.post_id;
+ let postEdit = reviewable.raw ?? reviewable.payload?.raw;
return adminTools[adminToolMethod](createdBy, {
postId,
postEdit,
- reviewableId: reviewable.get("id"),
+ reviewableId: reviewable.id,
before: performAction,
});
}
}
async #claimReviewable() {
- if (!this.reviewable.topic) {
+ const { reviewable } = this.args;
+
+ if (!reviewable.topic) {
// We can't claim a reviewable without a topic, so treat it as claimed
return true;
}
- if (!this.reviewable.claimed_by) {
+ if (!reviewable.claimed_by) {
const claim = this.store.createRecord("reviewable-claimed-topic");
try {
- await claim.save({
- topic_id: this.reviewable.topic.id,
- automatic: true,
- });
- this.reviewable.set("claimed_by", {
- user: this.currentUser,
- automatic: true,
- });
+ await claim.save({ topic_id: reviewable.topic.id, automatic: true });
+ reviewable.claimed_by = { user: this.currentUser, automatic: true };
} catch (e) {
popupAjaxError(e);
return false;
}
}
- return this.reviewable.claimed_by?.user?.id === this.currentUser.id;
+ return reviewable.claimed_by?.user?.id === this.currentUser.id;
}
async #unclaimAutomaticReviewable() {
- if (!this.reviewable.topic || !this.reviewable.claimed_by?.automatic) {
+ const { reviewable } = this.args;
+
+ if (!reviewable.topic || !reviewable.claimed_by?.automatic) {
return;
}
try {
- await ajax(`/reviewable_claimed_topics/${this.reviewable.topic.id}`, {
+ await ajax(`/reviewable_claimed_topics/${reviewable.topic.id}`, {
type: "DELETE",
data: { automatic: true },
});
- this.reviewable.set("claimed_by", null);
+ reviewable.claimed_by = null;
} catch (e) {
popupAjaxError(e);
}
@@ -580,57 +550,54 @@ export default class ReviewableItem extends Component {
@action
switchTab(tabName, event) {
event.preventDefault();
- this.activeTab = tabName;
+ this.state.activeTab = tabName;
if (tabName === "insights") {
- this.insightsOpened = true;
+ this.state.insightsOpened = true;
}
}
@action
edit() {
- this.set("editing", true);
- this.set("_updates", { payload: {} });
+ this.state.updates = trackedObject({});
}
@action
cancelEdit() {
- this.set("editing", false);
+ this.state.updates = null;
}
@action
saveEdit() {
- let updates = this._updates;
-
- // Remove empty objects
- Object.keys(updates).forEach((name) => {
- let attr = updates[name];
- if (typeof attr === "object" && Object.keys(attr).length === 0) {
- delete updates[name];
- }
- });
-
- this.set("updating", true);
- return this.reviewable
- .update(updates)
- .then(() => this.set("editing", false))
+ this.updating = true;
+ return this.args.reviewable
+ .update({ ...this.state.updates })
+ .then(() => (this.state.updates = null))
.catch(popupAjaxError)
- .finally(() => this.set("updating", false));
+ .finally(() => (this.updating = false));
}
@action
categoryChanged(categoryId) {
- let category = Category.findById(categoryId);
+ const category =
+ Category.findById(categoryId) ?? Category.findUncategorized();
- if (!category) {
- category = Category.findUncategorized();
- }
-
- set(this._updates, "category_id", category.id);
+ this.#updateField("category_id", category.id);
}
@action
valueChanged(fieldId, event) {
- set(this._updates, fieldId, event.target.value);
+ this.#updateField(fieldId, event.target.value);
+ }
+
+ #updateField(fieldId, value) {
+ const [key, nestedKey] = fieldId.split(".");
+ const updates = this.state.updates;
+
+ if (nestedKey) {
+ updates[key] = { ...updates[key], [nestedKey]: value };
+ } else {
+ updates[key] = value;
+ }
}
@action
@@ -664,7 +631,7 @@ export default class ReviewableItem extends Component {
if (await this.#claimReviewable()) {
this.modal.show(actionModalClass, {
model: {
- reviewable: this.reviewable,
+ reviewable: this.args.reviewable,
performConfirmed: this._performConfirmed,
action: performableAction,
},
@@ -675,8 +642,13 @@ export default class ReviewableItem extends Component {
}
}
+ @action
+ claimedByChanged(claimedBy) {
+ this.args.reviewable.claimed_by = claimedBy;
+ }
+
get permalink() {
- return getAbsoluteURL(`/review/${this.reviewable.id}`);
+ return getAbsoluteURL(`/review/${this.args.reviewable.id}`);
}
@action
@@ -692,7 +664,7 @@ export default class ReviewableItem extends Component {
try {
await clipboardCopy(this.permalink);
showAlert(
- this.reviewable.id,
+ this.args.reviewable.id,
"reviewable-permalink-copy",
"review.copy_link_feedback",
{ actionBtn: button }
@@ -707,7 +679,7 @@ export default class ReviewableItem extends Component {
<div class="review-container">
<div
- data-reviewable-id={{this.reviewable.id}}
+ data-reviewable-id={{@reviewable.id}}
class="review-item {{this.customClasses}}"
>
<div class="review-item__primary-content">
@@ -734,24 +706,21 @@ export default class ReviewableItem extends Component {
{{dIcon "link"}}
</button>
- {{newReviewableStatus
- this.reviewable.status
- this.reviewable.type
- }}
+ {{newReviewableStatus @reviewable.status @reviewable.type}}
<span class="reviewable-created-date">
- {{dFormatDate this.reviewable.created_at format="tiny"}}
+ {{dFormatDate @reviewable.created_at format="tiny"}}
</span>
</div>
{{#if this.editing}}
<div class="editable-fields">
- {{#each this.reviewable.editable_fields as |f|}}
+ {{#each @reviewable.editable_fields as |f|}}
<div class="editable-field {{dDasherize f.id}}">
{{#let (get fieldComponents f.type) as |FieldComponent|}}
<FieldComponent
@tagName=""
- @value={{editableValue this.reviewable f.id}}
+ @value={{editableValue @reviewable f.id}}
@tagCategoryId={{this.tagCategoryId}}
@valueChanged={{fn this.valueChanged f.id}}
@categoryChanged={{this.categoryChanged}}
@@ -763,20 +732,17 @@ export default class ReviewableItem extends Component {
{{else}}
<DAsyncContent
@asyncData={{this.resolveReviewableComponent}}
- @context={{this.reviewable.type}}
+ @context={{@reviewable.type}}
>
<:content as |ReviewableComponent|>
<ReviewableComponent
- @reviewable={{this.reviewable}}
+ @reviewable={{@reviewable}}
@tagName=""
/>
</:content>
<:empty>
<div class="alert alert-error review-item__no-component">
- {{i18n
- "review.no_component_found"
- type=this.reviewable.type
- }}
+ {{i18n "review.no_component_found" [email protected]}}
</div>
</:empty>
</DAsyncContent>
@@ -792,12 +758,12 @@ export default class ReviewableItem extends Component {
<li
class={{dConcatClass
"timeline"
- (if (eq this.activeTab "timeline") "active")
+ (if (eq this.state.activeTab "timeline") "active")
}}
>
<a
href="#"
- class={{if (eq this.activeTab "timeline") "active"}}
+ class={{if (eq this.state.activeTab "timeline") "active"}}
{{on "click" (fn this.switchTab "timeline")}}
>
{{i18n "review.timeline_and_notes"}}
@@ -806,12 +772,12 @@ export default class ReviewableItem extends Component {
<li
class={{dConcatClass
"insights"
- (if (eq this.activeTab "insights") "active")
+ (if (eq this.state.activeTab "insights") "active")
}}
>
<a
href="#"
- class={{if (eq this.activeTab "insights") "active"}}
+ class={{if (eq this.state.activeTab "insights") "active"}}
{{on "click" (fn this.switchTab "insights")}}
>
{{i18n "review.insights.title"}}
@@ -820,15 +786,15 @@ export default class ReviewableItem extends Component {
</DHorizontalOverflowNav>
</div>
- {{#if this.insightsOpened}}
- <div hidden={{not (eq this.activeTab "insights")}}>
- <ReviewableInsights @reviewable={{this.reviewable}} />
+ {{#if this.state.insightsOpened}}
+ <div hidden={{not (eq this.state.activeTab "insights")}}>
+ <ReviewableInsights @reviewable={{@reviewable}} />
</div>
{{/if}}
- {{#if (eq this.activeTab "timeline")}}
+ {{#if (eq this.state.activeTab "timeline")}}
<ReviewableTimeline
- @reviewable={{this.reviewable}}
- @historyEvents={{this.reviewable.reviewable_histories}}
+ @reviewable={{@reviewable}}
+ @historyEvents={{@reviewable.reviewable_histories}}
/>
{{/if}}
</div>
@@ -836,16 +802,16 @@ export default class ReviewableItem extends Component {
<div class="review-item__aside">
- {{#unless this.reviewable.last_performing_username}}
+ {{#unless @reviewable.last_performing_username}}
{{#if this.canPerform}}
<div class="review-item__moderator-actions">
<h3 class="review-item__aside-title">
{{#if this.editing}}
{{i18n "review.editing_post"}}
{{else if this.displayContextQuestion}}
- {{this.reviewable.flaggedReviewableContextQuestion}}
- {{else if this.reviewable.userReviewableContextQuestion}}
- {{this.reviewable.userReviewableContextQuestion}}
+ {{@reviewable.flaggedReviewableContextQuestion}}
+ {{else if @reviewable.userReviewableContextQuestion}}
+ {{@reviewable.userReviewableContextQuestion}}
{{else}}
{{i18n "review.moderator_actions"}}
{{/if}}
@@ -866,7 +832,7 @@ export default class ReviewableItem extends Component {
class="btn-danger reviewable-action cancel-edit"
/>
{{else}}
- {{#each this.reviewable.bundled_actions as |bundle|}}
+ {{#each @reviewable.bundled_actions as |bundle|}}
<ReviewableBundledAction
@bundle={{bundle}}
@performAction={{this.perform}}
@@ -874,7 +840,7 @@ export default class ReviewableItem extends Component {
/>
{{/each}}
- {{#if this.reviewable.can_edit}}
+ {{#if @reviewable.can_edit}}
<DButton
@disabled={{this.disabled}}
@action={{this.edit}}
@@ -889,20 +855,20 @@ export default class ReviewableItem extends Component {
{{#if this.claimEnabled}}
<div class="review-item__moderator-actions --extra">
- {{#if this.reviewable.claimed_by}}
+ {{#if @reviewable.claimed_by}}
<div class="review-item__assigned">
{{dIcon "user-plus"}}
<ReviewableCreatedBy
@showUsername={{true}}
@avatarSize="small"
- @user={{this.reviewable.claimed_by.user}}
+ @user={{@reviewable.claimed_by.user}}
/>
</div>
{{/if}}
<ReviewableClaimedTopic
@topicId={{this.topicId}}
- @claimedBy={{this.reviewable.claimed_by}}
- @onClaim={{fn (mut this.reviewable.claimed_by)}}
+ @claimedBy={{@reviewable.claimed_by}}
+ @onClaim={{this.claimedByChanged}}
/>
</div>
{{/if}}
diff --git a/frontend/discourse/app/components/reviewable/timeline.gjs b/frontend/discourse/app/components/reviewable/timeline.gjs
index 255bd5ab1fa..aa18b4eef63 100644
--- a/frontend/discourse/app/components/reviewable/timeline.gjs
+++ b/frontend/discourse/app/components/reviewable/timeline.gjs
@@ -1,5 +1,4 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
import { fn } from "@ember/helper";
import { action } from "@ember/object";
import { service } from "@ember/service";
@@ -30,19 +29,6 @@ import { i18n } from "discourse-i18n";
export default class ReviewableTimeline extends Component {
@service currentUser;
- /**
- * Array of notes associated with the reviewable
- *
- * @type {Array<ReviewableNote>}
- */
- @tracked reviewableNotes = [];
-
- constructor() {
- super(...arguments);
-
- this.reviewableNotes = this.args.reviewable.reviewable_notes || [];
- }
-
/**
* Combines all timeline events from reviewable scores, histories, and the reviewable itself
* and sorts them chronologically.
@@ -157,7 +143,7 @@ export default class ReviewableTimeline extends Component {
}
// Add notes events
- this.reviewableNotes.forEach((note) => {
+ this.args.reviewable.reviewable_notes?.forEach((note) => {
const date = note.created_at;
events.push({
type: "note",
@@ -209,8 +195,7 @@ export default class ReviewableTimeline extends Component {
noteData.user = this.currentUser;
}
- this.reviewableNotes = [...this.reviewableNotes, noteData];
- this.args.reviewable.reviewable_notes = this.reviewableNotes;
+ this.args.reviewable.reviewable_notes.push(noteData);
}
/**
@@ -225,8 +210,8 @@ export default class ReviewableTimeline extends Component {
type: "DELETE",
});
- // Remove the note from the local array
- this.reviewableNotes = this.reviewableNotes.filter(
+ const { reviewable } = this.args;
+ reviewable.reviewable_notes = reviewable.reviewable_notes.filter(
(note) => note.id !== noteId
);
} catch (error) {
diff --git a/frontend/discourse/app/models/reviewable.js b/frontend/discourse/app/models/reviewable.js
index 5bb6baf3766..d76f19ac71a 100644
--- a/frontend/discourse/app/models/reviewable.js
+++ b/frontend/discourse/app/models/reviewable.js
@@ -1,8 +1,10 @@
+import { tracked } from "@glimmer/tracking";
import { computed } from "@ember/object";
import { dasherize, underscore } from "@ember/string";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
import { uniqueItemsFromArray } from "discourse/lib/array-tools";
+import { autoTrackedArray } from "discourse/lib/tracked-tools";
import RestModel from "discourse/models/rest";
import I18n, { i18n } from "discourse-i18n";
import Category from "./category";
@@ -20,6 +22,47 @@ export default class Reviewable extends RestModel {
return json;
}
+ @tracked blank_post;
+ @tracked bundled_actions;
+ @tracked can_edit;
+ @tracked category_id;
+ @tracked claimed_by;
+ @tracked cooked;
+ @tracked created_at;
+ @tracked created_by;
+ @tracked created_from_flag;
+ @tracked deleted_at;
+ @tracked editable_fields;
+ @tracked fancy_title;
+ @tracked id;
+ @tracked last_performing_username;
+ @tracked payload;
+ @tracked post_id;
+ @tracked post_updated_at;
+ @tracked post_version;
+ @tracked raw;
+ @tracked removed_topic_id;
+ @tracked reviewable_histories;
+ @tracked reviewable_scores;
+ @tracked score;
+ @tracked status;
+ @tracked target_created_at;
+ @tracked target_created_by;
+ @tracked target_created_by_trust_level;
+ @tracked target_deleted_at;
+ @tracked target_deleted_by;
+ @tracked target_id;
+ @tracked target_type;
+ @tracked target_url;
+ @tracked topic;
+ @tracked topic_id;
+ @tracked topic_tags;
+ @tracked topic_url;
+ @tracked type;
+ @tracked type_source;
+ @tracked version;
+ @autoTrackedArray reviewable_notes = [];
+
@computed("type", "topic")
get resolvedType() {
// Display "Queued Topic" if the post will create a topic
diff --git a/frontend/discourse/tests/integration/components/reviewable/item-test.gjs b/frontend/discourse/tests/integration/components/reviewable/item-test.gjs
index dbf998f9943..9ca6d77fc9c 100644
--- a/frontend/discourse/tests/integration/components/reviewable/item-test.gjs
+++ b/frontend/discourse/tests/integration/components/reviewable/item-test.gjs
@@ -1,5 +1,6 @@
+import { tracked } from "@glimmer/tracking";
import { getOwner } from "@ember/owner";
-import { render } from "@ember/test-helpers";
+import { click, fillIn, render, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
import ReviewableItem from "discourse/components/reviewable/item";
import { withPluginApi } from "discourse/lib/plugin-api";
@@ -24,6 +25,20 @@ function claimableReviewable(context, attrs = {}) {
});
}
+function plainReviewable(attrs = {}) {
+ return { id: 456, topic: null, reviewable_scores: [], ...attrs };
+}
+
+function editableReviewable(id) {
+ return plainReviewable({
+ id,
+ type: "ReviewableQueuedPost",
+ can_edit: true,
+ editable_fields: [{ id: "payload.title", type: "text" }],
+ payload: { title: "Original title" },
+ });
+}
+
function publishClaim({ topicId = 123, claimed, automatic = false }) {
return publishToMessageBus("/reviewable_claimed", {
topic_id: topicId,
@@ -99,13 +114,7 @@ module("Integration | Component | Reviewable | Item", function (hooks) {
test("does not error when a claim is broadcast for a reviewable without a topic", async function (assert) {
// e.g. ReviewableUser / a queued new topic have no associated topic object
- const topiclessReviewable = {
- id: 456,
- type: "ReviewableUser",
- topic: null,
- reviewable_scores: [],
- payload: { username: "flagged-user" },
- };
+ const topiclessReviewable = plainReviewable({ type: "ReviewableUser" });
await render(
<template>
@@ -277,4 +286,75 @@ module("Integration | Component | Reviewable | Item", function (hooks) {
assert.dom(".custom-reviewable").hasText("ReviewableCustomThing");
});
+
+ test("leaves edit mode when a different reviewable is passed in", async function (assert) {
+ const state = new (class {
+ @tracked reviewable = editableReviewable(1);
+ })();
+
+ await render(
+ <template><ReviewableItem @reviewable={{state.reviewable}} /></template>
+ );
+
+ await click(".reviewable-action.edit");
+
+ state.reviewable = editableReviewable(2);
+ await settled();
+
+ assert
+ .dom(".editable-fields")
+ .doesNotExist(
+ "does not carry the pending edit over to the new reviewable"
+ );
+ });
+
+ test("keeps a pending edit when the reviewable it belongs to is refreshed", async function (assert) {
+ const queuedPost = getOwner(this)
+ .lookup("service:store")
+ .createRecord("reviewable", editableReviewable(1));
+
+ await render(
+ <template><ReviewableItem @reviewable={{queuedPost}} /></template>
+ );
+
+ await click(".reviewable-action.edit");
+ await fillIn(".editable-field.payload-title input", "Edited first title");
+
+ queuedPost.setProperties({ version: 2 });
+ await settled();
+
+ assert
+ .dom(".editable-field.payload-title input")
+ .hasValue(
+ "Edited first title",
+ "an in-place refresh of the same reviewable keeps the pending edit"
+ );
+ });
+
+ test("goes back to the timeline tab when a different reviewable is passed in", async function (assert) {
+ const state = new (class {
+ @tracked reviewable = plainReviewable({ id: 1, type: "ReviewableUser" });
+ })();
+
+ await render(
+ <template><ReviewableItem @reviewable={{state.reviewable}} /></template>
+ );
+
+ await click(".d-nav-submenu__tabs .insights a");
+
+ assert
+ .dom(".d-nav-submenu__tabs .insights a")
+ .hasClass("active", "the insights tab is selected");
+ assert.dom(".review-insight").exists("the insights tab is mounted");
+
+ state.reviewable = plainReviewable({ id: 2, type: "ReviewableUser" });
+ await settled();
+
+ assert
+ .dom(".d-nav-submenu__tabs .timeline a")
+ .hasClass("active", "the new reviewable opens on its own timeline");
+ assert
+ .dom(".review-insight")
+ .doesNotExist("the previous reviewable's insights are torn down");
+ });
});
diff --git a/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs b/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs
index 66d6e41874c..98c309cf92c 100644
--- a/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs
+++ b/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs
@@ -1,12 +1,34 @@
-import { render } from "@ember/test-helpers";
+import { tracked } from "@glimmer/tracking";
+import { getOwner } from "@ember/owner";
+import { click, render, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
import ReviewableTimeline from "discourse/components/reviewable/timeline";
import { CLAIMED, UNCLAIMED } from "discourse/models/reviewable-history";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
module("Integration | Component | Reviewable | Timeline", function (hooks) {
setupRenderingTest(hooks);
+ function note(id, content) {
+ return {
+ id,
+ content,
+ created_at: `2024-01-0${id - 9}T00:00:00.000Z`,
+ user: { id: 1, username: "moderator" },
+ };
+ }
+
+ function storedReviewable(context, notes) {
+ return getOwner(context)
+ .lookup("service:store")
+ .createRecord("reviewable", {
+ id: 1,
+ reviewable_scores: [],
+ reviewable_notes: notes,
+ });
+ }
+
function reviewableWithReason(reason) {
return {
reviewable_scores: [
@@ -82,4 +104,75 @@ module("Integration | Component | Reviewable | Timeline", function (hooks) {
assert.dom(".timeline-event__icon .d-icon-user-plus").exists();
assert.dom(".timeline-event__icon .d-icon-user-xmark").exists();
});
+
+ test("renders the notes of the reviewable currently passed in", async function (assert) {
+ const state = new (class {
+ @tracked
+ reviewable = {
+ reviewable_scores: [],
+ reviewable_notes: [note(10, "Note on the first reviewable")],
+ };
+ })();
+
+ await render(
+ <template>
+ <ReviewableTimeline @reviewable={{state.reviewable}} />
+ </template>
+ );
+
+ assert
+ .dom(".timeline-event__description")
+ .hasText("Note on the first reviewable", "renders the note it owns");
+
+ state.reviewable = { reviewable_scores: [] };
+ await settled();
+
+ assert
+ .dom(".timeline-event")
+ .doesNotExist("drops the previous reviewable's notes");
+ });
+
+ test("renders a note pushed onto the reviewable after it was rendered", async function (assert) {
+ const reviewable = storedReviewable(this, [note(10, "An existing note")]);
+
+ await render(
+ <template><ReviewableTimeline @reviewable={{reviewable}} /></template>
+ );
+
+ assert
+ .dom(".timeline-event__description")
+ .hasText("An existing note", "renders the note it was created with");
+
+ reviewable.reviewable_notes.push(note(11, "A note added from the form"));
+ await settled();
+
+ assert
+ .dom(".timeline-event:last-child .timeline-event__description")
+ .hasText("A note added from the form", "appends the pushed note");
+ });
+
+ test("removes a deleted note from the timeline", async function (assert) {
+ const reviewable = storedReviewable(this, [
+ note(10, "A note that stays"),
+ note(11, "A note that gets deleted"),
+ ]);
+
+ this.currentUser.admin = true;
+ pretender.delete("/review/1/notes/11", () => response({}));
+
+ await render(
+ <template><ReviewableTimeline @reviewable={{reviewable}} /></template>
+ );
+
+ await click(".timeline-event:last-child .timeline-event__delete-note");
+
+ assert
+ .dom(".timeline-event")
+ .exists({ count: 1 }, "drops the deleted note");
+ assert.deepEqual(
+ [...reviewable.reviewable_notes].map((n) => n.id),
+ [10],
+ "writes the removal back to the reviewable"
+ );
+ });
});
diff --git a/spec/system/page_objects/components/user_menu.rb b/spec/system/page_objects/components/user_menu.rb
index 0fd854c46d1..4677ce4f5ed 100644
--- a/spec/system/page_objects/components/user_menu.rb
+++ b/spec/system/page_objects/components/user_menu.rb
@@ -27,6 +27,17 @@ module PageObjects
self
end
+ def click_review_queue_tab
+ click_link("user-menu-button-review-queue")
+ has_css?("#quick-access-review-queue")
+ self
+ end
+
+ def click_reviewable(reviewable)
+ find("#quick-access-review-queue a[href$='/review/#{reviewable.id}']").click
+ self
+ end
+
def click_logout_button
find("#quick-access-profile .logout .btn").click
has_css?(".d-header .login-button")
diff --git a/spec/system/page_objects/pages/review.rb b/spec/system/page_objects/pages/review.rb
index 85af39ffde0..57a649d659a 100644
--- a/spec/system/page_objects/pages/review.rb
+++ b/spec/system/page_objects/pages/review.rb
@@ -12,6 +12,17 @@ module PageObjects
self
end
+ # Reaching a reviewable through the user menu keeps the app running, which
+ # is the only way to exercise the state a reviewable item carries over from
+ # the previously displayed one. `visit_reviewable` always starts afresh.
+ def visit_reviewable_from_user_menu(reviewable)
+ PageObjects::Components::UserMenu.new.open.click_review_queue_tab.click_reviewable(
+ reviewable,
+ )
+ reviewable_by_id(reviewable.id)
+ self
+ end
+
def select_bundled_action(reviewable, value, bundle_index: nil)
within(reviewable_by_id(reviewable.id)) do
dropdown =
diff --git a/spec/system/viewing_reviewable_spec.rb b/spec/system/viewing_reviewable_spec.rb
index 6e40f041eb4..f9b8b93fe03 100644
--- a/spec/system/viewing_reviewable_spec.rb
+++ b/spec/system/viewing_reviewable_spec.rb
@@ -119,6 +119,23 @@ describe "Viewing reviewable item" do
expect(page).to have_text("This is a review note.")
end
+ it "only shows a note on the reviewable it was added to" do
+ other_reviewable = Fabricate(:reviewable_flagged_post)
+
+ review_page.visit_reviewable(reviewable_flagged_post)
+ review_note_form.add_note("This is a review note.")
+
+ expect(page).to have_text("This is a review note.")
+
+ review_page.visit_reviewable_from_user_menu(other_reviewable)
+
+ expect(page).to have_no_text("This is a review note.")
+
+ review_page.visit_reviewable_from_user_menu(reviewable_flagged_post)
+
+ expect(page).to have_text("This is a review note.")
+ end
+
it "shows confirmation dialog when navigating away with unsaved note, but not after clearing the note" do
dialog = PageObjects::Components::Dialog.new
@@ -270,7 +287,7 @@ describe "Viewing reviewable item" do
expect(review_page).to have_ip_hostname("ip-81-2-69-142.example.com")
- review_page.visit_reviewable(other_reviewable)
+ review_page.visit_reviewable_from_user_menu(other_reviewable)
review_page.click_insights_tab
expect(review_page).to have_ip_hostname("ip-2-125-160-216.example.com")