A platform for community discussion. Free, open, simple.
FEATURE: Allow editing a post's reply target from the composer (#39471)
Rafael dos Santos Silvaf3170f325c2a
diff --git a/app/assets/stylesheets/common/modal/_index.scss b/app/assets/stylesheets/common/modal/_index.scssindex d2dba276a2d..142e213533b 100644--- a/app/assets/stylesheets/common/modal/_index.scss+++ b/app/assets/stylesheets/common/modal/_index.scss@@ -1,3 +1,4 @@@import "modal-overrides";@import "user-status";@import "discourse-reactions-popup";+@import "change-reply-to";diff --git a/app/assets/stylesheets/common/modal/change-reply-to.scss b/app/assets/stylesheets/common/modal/change-reply-to.scssnew file mode 100644index 00000000000..9516ad0ff76--- /dev/null+++ b/app/assets/stylesheets/common/modal/change-reply-to.scss@@ -0,0 +1,50 @@+.change-reply-to-modal {+ .d-modal__container {+ max-width: 720px;+ width: 100%;+ }++ .d-modal__body {+ padding-bottom: 0;+ }++ .change-reply-to-modal__hint,+ .change-reply-to-modal__selection {+ margin: 0 0 var(--space-2) 0;+ color: var(--primary-medium);+ }++ // Re-flow the fullscreen timeline inline inside the modal body.+ .timeline-container.timeline-fullscreen {+ position: static;+ max-height: none;+ padding: var(--space-2) 0 0 0;+ margin: 0;+ box-shadow: none;+ border-top: none;+ background-color: transparent;+ z-index: auto;++ &.show {+ max-height: none;+ }++ .topic-timeline {+ display: block;+ width: auto;+ table-layout: auto;+ }++ // The timeline footer has "jump to post" and notification controls that+ // are irrelevant inside this picker; hide them.+ .timeline-footer-controls {+ display: none;+ }++ // Keep the excerpt readable; the fullscreen styles line-clamp to 8 which+ // is fine here too.+ .post-excerpt {+ margin-bottom: var(--space-2);+ }+ }+}diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rbindex c64a83d45f9..cc211ed256d 100644--- a/app/controllers/posts_controller.rb+++ b/app/controllers/posts_controller.rb@@ -232,6 +232,10 @@ class PostsController < ApplicationControllerlocale: params[:post][:locale],}+ if params[:post].key?(:reply_to_post_number)+ changes[:reply_to_post_number] = params[:post][:reply_to_post_number]+ end+Post.plugin_permitted_update_params.keys.each { |param| changes[param] = params[:post][param] }# keep `raw_old` for backwards compatibility@@ -582,7 +586,8 @@ class PostsController < ApplicationControllerguardian.ensure_can_edit!(post)if post_revision.modifications["raw"].blank? && post_revision.modifications["title"].blank? &&post_revision.modifications["category_id"].blank? &&- post_revision.modifications["tags"].blank?+ post_revision.modifications["tags"].blank? &&+ post_revision.modifications["reply_to_post_number"].blank?return render_json_error(I18n.t("revert_version_same"))end@@ -592,6 +597,10 @@ class PostsController < ApplicationControllerchanges[:raw] = post_revision.modifications["raw"][0] if post_revision.modifications["raw"].present? && post_revision.modifications["raw"][0] != post.raw+ if post_revision.modifications["reply_to_post_number"].present? &&+ post_revision.modifications["reply_to_post_number"][0] != post.reply_to_post_number+ changes[:reply_to_post_number] = post_revision.modifications["reply_to_post_number"][0]+ endif post.is_first_post?changes[:title] = post_revision.modifications["title"][0] if post_revision.modifications["title"diff --git a/app/models/concerns/has_nested_reply_stats.rb b/app/models/concerns/has_nested_reply_stats.rbindex c05cd4e744a..0cf50123513 100644--- a/app/models/concerns/has_nested_reply_stats.rb+++ b/app/models/concerns/has_nested_reply_stats.rb@@ -8,19 +8,79 @@ module HasNestedReplyStatsafter_destroy :nested_replies_decrement_statsend+ # Moves this post's subtree from `previous_reply_to_post_number` to its+ # current `reply_to_post_number` on the nested stats tree. Shared ancestors+ # are left alone — their total descendant count is unchanged — while+ # ancestors unique to either chain are adjusted by this post's subtree size.+ def nested_replies_apply_reparent(previous_reply_to_post_number)+ return unless SiteSetting.nested_replies_enabled+ return if previous_reply_to_post_number == reply_to_post_number++ subtree_size, whisper_subtree_size = nested_replies_subtree_sizes+ is_whisper = post_type == Post.types[:whisper] ? 1 : 0++ old_ancestors = nested_replies_walk(previous_reply_to_post_number)+ new_ancestors = nested_replies_walk(reply_to_post_number)++ old_ids = old_ancestors.map(&:id)+ new_ids = new_ancestors.map(&:id)+ old_only_ids = old_ids - new_ids+ new_only_ids = new_ids - old_ids++ old_direct_parent_id = old_ancestors.find { |a| a.depth == 1 }&.id+ new_direct_parent_id = new_ancestors.find { |a| a.depth == 1 }&.id++ if old_only_ids.any?+ DB.exec(<<~SQL, ids: old_only_ids, subtree: subtree_size, whisper: whisper_subtree_size)+ UPDATE nested_view_post_stats+ SET total_descendant_count = GREATEST(total_descendant_count - :subtree, 0),+ whisper_total_descendant_count = GREATEST(whisper_total_descendant_count - :whisper, 0),+ updated_at = NOW()+ WHERE post_id = ANY(ARRAY[:ids]::int[])+ SQL+ end++ if new_only_ids.any?+ DB.exec(<<~SQL, ids: new_only_ids, subtree: subtree_size, whisper: whisper_subtree_size)+ INSERT INTO nested_view_post_stats (post_id, direct_reply_count, total_descendant_count,+ whisper_direct_reply_count, whisper_total_descendant_count,+ created_at, updated_at)+ SELECT aid, 0, :subtree, 0, :whisper, NOW(), NOW()+ FROM unnest(ARRAY[:ids]::int[]) AS aid+ ON CONFLICT (post_id) DO UPDATE SET+ total_descendant_count = nested_view_post_stats.total_descendant_count + :subtree,+ whisper_total_descendant_count = nested_view_post_stats.whisper_total_descendant_count + :whisper,+ updated_at = NOW()+ SQL+ end++ DB.exec(<<~SQL, id: old_direct_parent_id, is_whisper: is_whisper) if old_direct_parent_id+ UPDATE nested_view_post_stats+ SET direct_reply_count = GREATEST(direct_reply_count - 1, 0),+ whisper_direct_reply_count = GREATEST(whisper_direct_reply_count - :is_whisper, 0),+ updated_at = NOW()+ WHERE post_id = :id+ SQL++ DB.exec(<<~SQL, id: new_direct_parent_id, is_whisper: is_whisper) if new_direct_parent_id+ INSERT INTO nested_view_post_stats (post_id, direct_reply_count, total_descendant_count,+ whisper_direct_reply_count, whisper_total_descendant_count,+ created_at, updated_at)+ VALUES (:id, 1, 0, :is_whisper, 0, NOW(), NOW())+ ON CONFLICT (post_id) DO UPDATE SET+ direct_reply_count = nested_view_post_stats.direct_reply_count + 1,+ whisper_direct_reply_count = nested_view_post_stats.whisper_direct_reply_count + :is_whisper,+ updated_at = NOW()+ SQL+ end+privatedef nested_replies_increment_statsreturn unless SiteSetting.nested_replies_enabledreturn if reply_to_post_number.blank?- ancestors =- NestedReplies.walk_ancestors(- topic_id: topic_id,- start_post_number: reply_to_post_number,- exclude_deleted: false,- )-+ ancestors = nested_replies_walk(reply_to_post_number)return if ancestors.empty?ancestor_ids = ancestors.map(&:id).uniq@@ -52,25 +112,10 @@ module HasNestedReplyStatsdef nested_replies_decrement_statsreturn unless SiteSetting.nested_replies_enabledif reply_to_post_number.present?- stat =- NestedViewPostStat.where(post_id: id).pick(- :total_descendant_count,- :whisper_total_descendant_count,- )- my_descendants = stat&.first || 0- my_whisper_descendants = stat&.second || 0- removed = 1 + my_descendants+ subtree_size, whisper_subtree_size = nested_replies_subtree_sizesis_whisper = post_type == Post.types[:whisper] ? 1 : 0- whisper_removed = is_whisper + my_whisper_descendants-- # Include deleted ancestors — they may still have stat rows from when- # they were alive, and those counts need to be decremented.- ancestors =- NestedReplies.walk_ancestors(- topic_id: topic_id,- start_post_number: reply_to_post_number,- exclude_deleted: false,- )++ ancestors = nested_replies_walk(reply_to_post_number)if ancestors.present?ancestor_ids = ancestors.map(&:id)@@ -94,8 +139,8 @@ module HasNestedReplyStatsSQLids: ancestor_ids,parent_id: direct_parent_id,- removed: removed,- whisper_removed: whisper_removed,+ removed: subtree_size,+ whisper_removed: whisper_subtree_size,is_whisper: is_whisper,)end@@ -103,4 +148,25 @@ module HasNestedReplyStatsNestedViewPostStat.where(post_id: id).delete_allend++ def nested_replies_subtree_sizes+ stat =+ NestedViewPostStat.where(post_id: id).pick(+ :total_descendant_count,+ :whisper_total_descendant_count,+ )+ is_whisper = post_type == Post.types[:whisper] ? 1 : 0+ [1 + (stat&.first || 0), is_whisper + (stat&.second || 0)]+ end++ def nested_replies_walk(start_post_number)+ return [] if start_post_number.blank?+ # Include deleted ancestors — they may still have stat rows from when they+ # were alive, and those counts need to stay consistent.+ NestedReplies.walk_ancestors(+ topic_id: topic_id,+ start_post_number: start_post_number,+ exclude_deleted: false,+ )+ endenddiff --git a/app/serializers/post_revision_serializer.rb b/app/serializers/post_revision_serializer.rbindex 5ed6e11b7c8..06651f4926b 100644--- a/app/serializers/post_revision_serializer.rb+++ b/app/serializers/post_revision_serializer.rb@@ -25,6 +25,7 @@ class PostRevisionSerializer < ApplicationSerializer:body_changes,:title_changes,:user_changes,+ :reply_to_post_number_changes,:tags_changes,:category_id_changes,:can_edit,@@ -186,6 +187,17 @@ class PostRevisionSerializer < ApplicationSerializerprevious["user_id"] != current["user_id"]end+ def reply_to_post_number_changes+ {+ previous: reply_to_info(previous["reply_to_post_number"]),+ current: reply_to_info(current["reply_to_post_number"]),+ }+ end++ def include_reply_to_post_number_changes?+ previous["reply_to_post_number"] != current["reply_to_post_number"]+ end+def tags_changespre = filter_tags previous["tags"]cur = filter_tags current["tags"]@@ -243,6 +255,7 @@ class PostRevisionSerializer < ApplicationSerializer"post_type" => [post.post_type],"user_id" => [post.user_id],"locale" => [post.locale],+ "reply_to_post_number" => [post.reply_to_post_number],}# Retrieve any `tracked_topic_fields`@@ -319,4 +332,22 @@ class PostRevisionSerializer < ApplicationSerializerreturn if category_id.blank?Category.secured(scope).find_by(id: category_id)&.idend++ def reply_to_info(post_number)+ return nil if post_number.blank?++ target = Post.where(topic_id: topic.id, post_number: post_number).first+ info = { post_number: post_number }++ # Only enrich with the target's author if the current viewer can see+ # that post. Deleted posts, whispers, and posts in restricted+ # categories must not leak their author through the revision history.+ if target && scope.can_see?(target) && target.user+ info[:username] = target.user.username_lower+ info[:display_username] = target.user.username+ info[:avatar_template] = target.user.avatar_template+ end++ info+ endenddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex be710bd996f..f0c71201df1 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -3133,6 +3133,16 @@ en:placeholder: "Enter translation for post here..."show_raw_markdown: "Show raw"+ change_reply_to:+ title: "Change reply target"+ hint: "Scroll the timeline to find the post you'd like to reply to."+ current_selection: "Selected: post #%{post_number} by @%{username}"+ invalid_target: "Choose a post earlier than the one you're editing."+ submit: "Set reply target"+ open: "Change which post this replies to"+ open_from_menu: "Reply to another post"+ remove: "Remove reply target"+group_mentioned_limit:one: "<b>Warning!</b> You mentioned <a href='%{group_link}'>%{group}</a>, however this group has more members than the administrator configured mention limit of %{count} user. Nobody will be notified."other: "<b>Warning!</b> You mentioned <a href='%{group_link}'>%{group}</a>, however this group has more members than the administrator configured mention limit of %{count} users. Nobody will be notified."@@ -4733,6 +4743,8 @@ en:locale:no_locale_set: "No language set"locale_removed: "Language removed"+ reply_to:+ none: "No reply target"controls:first: "First revision"previous: "Previous revision"diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 78512c820c2..fdf854fc3c2 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -917,6 +917,8 @@ en:change_failed_explanation: "You attempted to demote %{user_name} to '%{new_trust_level}'. However their trust level is already '%{current_trust_level}'. %{user_name} will remain at '%{current_trust_level}' - if you wish to demote user lock trust level first"post:+ errors:+ invalid_reply_to: "The selected post isn't a valid reply target. It must be an earlier post in the same topic."image_placeholder:broken: "This image is broken"blocked_hotlinked_title: "Image hosted on another site. Click to open in a new tab."diff --git a/frontend/discourse/app/components/composer-action-title.gjs b/frontend/discourse/app/components/composer-action-title.gjsindex a7c59f92292..a6db2a07b24 100644--- a/frontend/discourse/app/components/composer-action-title.gjs+++ b/frontend/discourse/app/components/composer-action-title.gjs@@ -1,7 +1,9 @@/* eslint-disable ember/no-classic-components */import Component from "@ember/component";import { hash } from "@ember/helper";-import { computed, set } from "@ember/object";+import { on } from "@ember/modifier";+import { action, computed, set } from "@ember/object";+import { service } from "@ember/service";import { trustHTML } from "@ember/template";import { tagName } from "@ember-decorators/component";import escape from "discourse/lib/escape";@@ -31,6 +33,8 @@ export default class ComposerActionTitle extends Component {// Note we update when some other attributes like tag/category change to allow// text customizations to use those.+ @service composer;+@computed("model.replyOptions")get options() {return this.model?.replyOptions;@@ -49,6 +53,20 @@ export default class ComposerActionTitle extends Component {set(this, "model.action", value);}+ @computed("action", "model.post.can_edit", "model.topic")+ get canEditReplyTo() {+ return (+ this.action === EDIT &&+ !!this.model?.post?.can_edit &&+ !!this.model?.topic+ );+ }++ @action+ openChangeReplyToModal() {+ this.composer.openChangeReplyToModal();+ }+@computed("options", "action", "model.tags", "model.category")get actionTitle() {const result = this.model.customizationFor("actionTitle");@@ -80,29 +98,31 @@ export default class ComposerActionTitle extends Component {return this._formatEditUserPost(this.options.userAvatar,this.options.userLink,- this.options.postLink,- this.options.originalUser+ this.options.postLink);}}}- _formatEditUserPost(userAvatar, userLink, postLink, originalUser) {- let editTitle = `+ @computed("options.originalUser")+ get replyTargetSegment() {+ const originalUser = this.options?.originalUser;+ if (!originalUser) {+ return null;+ }+ return trustHTML(+ `${iconHTML("share", { class: "reply-to-glyph" })}+ ${originalUser.avatar}+ <span class="original-username">${escape(originalUser.username)}</span>`+ );+ }++ _formatEditUserPost(userAvatar, userLink, postLink) {+ return trustHTML(`<a class="post-link" href="${postLink.href}">${postLink.anchor}</a>${userAvatar}<span class="username">${escape(userLink.anchor)}</span>- `;-- if (originalUser) {- editTitle += `- ${iconHTML("share", { class: "reply-to-glyph" })}- ${originalUser.avatar}- <span class="original-username">${escape(originalUser.username)}</span>- `;- }-- return trustHTML(editTitle);+ `);}_formatReplyToTopic(link) {@@ -138,8 +158,19 @@ export default class ComposerActionTitle extends Component {<span class="action-title" role="heading" aria-level="1">{{this.actionTitle}}+ {{#if this.replyTargetSegment}}+ {{#if this.canEditReplyTo}}+ <button+ type="button"+ class="composer-edit-reply-to"+ title={{i18n "composer.change_reply_to.open"}}+ {{on "click" this.openChangeReplyToModal}}+ >{{this.replyTargetSegment}}</button>+ {{else}}+ {{this.replyTargetSegment}}+ {{/if}}+ {{/if}}</span>-</div></template>}diff --git a/frontend/discourse/app/components/modal/change-reply-to.gjs b/frontend/discourse/app/components/modal/change-reply-to.gjsnew file mode 100644index 00000000000..ab116c6c237--- /dev/null+++ b/frontend/discourse/app/components/modal/change-reply-to.gjs@@ -0,0 +1,191 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import DButton from "discourse/components/d-button";+import DModal from "discourse/components/d-modal";+import TopicTimeline from "discourse/components/topic-timeline";+import { extractError } from "discourse/lib/ajax-error";+import { not } from "discourse/truth-helpers";+import { i18n } from "discourse-i18n";++export default class ChangeReplyTo extends Component {+ @tracked selectedPost = null;+ @tracked flash = null;++ noop = () => {};++ get topic() {+ return this.args.model.topic;+ }++ get editingPostNumber() {+ return this.args.model.editingPostNumber;+ }++ get canSubmit() {+ return (+ !!this.selectedPost &&+ this.selectedPost.post_number < this.editingPostNumber+ );+ }++ get canRemove() {+ return !!this.args.model.currentPostNumber;+ }++ get initialEnteredIndex() {+ const postNumber = this.args.model.currentPostNumber;+ if (!postNumber) {+ return 0;+ }+ const postStream = this.topic?.postStream;+ const post = postStream?.postForPostNumber?.(postNumber);+ if (!post) {+ return 0;+ }+ // `TopicTimeline` treats `@enteredIndex` as 0-based (see how its+ // `prevEvent.postIndex - 1` branch maps a 1-based event index back+ // down), while `progressIndexOfPost` returns 1-based. Subtract one+ // so the scrubber lands exactly on the current target.+ return Math.max(0, postStream.progressIndexOfPost(post) - 1);+ }++ @action+ async handleJumpToIndex(index) {+ await this.captureSelectionForIndex(index);+ }++ @action+ async handleJumpTop() {+ await this.captureSelectionForIndex(1);+ }++ @action+ async handleJumpBottom() {+ const total = this.topic?.postStream?.filteredPostsCount;+ if (total) {+ await this.captureSelectionForIndex(total);+ }+ }++ async captureSelectionForIndex(timelineIndex) {+ const postStream = this.topic?.postStream;+ if (!postStream || !timelineIndex) {+ return;+ }++ try {+ let post;+ if (postStream.isMegaTopic) {+ // On mega topics the timeline's `current` / jump callbacks are+ // post numbers, not stream positions — see `filteredPostsCount`.+ post =+ postStream.postForPostNumber(timelineIndex) ||+ (await postStream.loadPostByPostNumber(timelineIndex));+ } else {+ const postId = postStream.stream[timelineIndex - 1];+ if (!postId) {+ return;+ }+ post =+ postStream.findLoadedPost(postId) ||+ (await postStream.loadPost(postId));+ }++ if (!post) {+ return;+ }+ if (post.post_number >= this.editingPostNumber) {+ this.flash = i18n("composer.change_reply_to.invalid_target");+ this.selectedPost = null;+ return;+ }+ this.flash = null;+ this.selectedPost = post;+ } catch (e) {+ this.flash = extractError(e);+ }+ }++ @action+ submit() {+ if (!this.canSubmit) {+ return;+ }+ this.args.model.onSelect(this.selectedPost);+ this.args.closeModal();+ }++ @action+ remove() {+ this.args.model.onSelect(null);+ this.args.closeModal();+ }++ <template>+ <DModal+ @closeModal={{@closeModal}}+ @title={{i18n "composer.change_reply_to.title"}}+ @flash={{this.flash}}+ class="change-reply-to-modal"+ >+ <:body>+ {{#if this.selectedPost}}+ <p class="change-reply-to-modal__selection">+ {{i18n+ "composer.change_reply_to.current_selection"+ post_number=this.selectedPost.post_number+ username=this.selectedPost.username+ }}+ </p>+ {{else}}+ <p class="change-reply-to-modal__hint">+ {{i18n "composer.change_reply_to.hint"}}+ </p>+ {{/if}}++ <TopicTimeline+ @model={{this.topic}}+ @fullscreen={{true}}+ @enteredIndex={{this.initialEnteredIndex}}+ @jumpTop={{this.handleJumpTop}}+ @jumpBottom={{this.handleJumpBottom}}+ @jumpEnd={{this.handleJumpBottom}}+ @jumpToIndex={{this.handleJumpToIndex}}+ @jumpToPostPrompt={{this.noop}}+ @replyToPost={{this.noop}}+ @showTopReplies={{this.noop}}+ @toggleMultiSelect={{this.noop}}+ @showTopicSlowModeUpdate={{this.noop}}+ @deleteTopic={{this.noop}}+ @recoverTopic={{this.noop}}+ @toggleClosed={{this.noop}}+ @toggleArchived={{this.noop}}+ @toggleVisibility={{this.noop}}+ @showTopicTimerModal={{this.noop}}+ @showFeatureTopic={{this.noop}}+ @showChangeTimestamp={{this.noop}}+ @resetBumpDate={{this.noop}}+ @convertToPublicTopic={{this.noop}}+ @convertToPrivateMessage={{this.noop}}+ />+ </:body>+ <:footer>+ <DButton+ @action={{this.submit}}+ @label="composer.change_reply_to.submit"+ @disabled={{not this.canSubmit}}+ class="btn-primary"+ />+ {{#if this.canRemove}}+ <DButton+ @action={{this.remove}}+ @label="composer.change_reply_to.remove"+ class="btn-danger"+ />+ {{/if}}+ <DButton @action={{@closeModal}} @label="cancel" />+ </:footer>+ </DModal>+ </template>+}diff --git a/frontend/discourse/app/components/modal/history.gjs b/frontend/discourse/app/components/modal/history.gjsindex f4164f0aa23..360b4f25d21 100644--- a/frontend/discourse/app/components/modal/history.gjs+++ b/frontend/discourse/app/components/modal/history.gjs@@ -230,6 +230,21 @@ export default class History extends Component {await Category.asyncFindById(result.category_id));}+ if (result.post) {+ // `PostSerializer` omits `reply_to_user` when the user is nil OR+ // when `suppress_reply_when_quoting` is on and the post quotes its+ // target. Treat a missing key as "leave alone" — only clear it+ // when the post number is also cleared.+ const props = {+ reply_to_post_number: result.post.reply_to_post_number ?? null,+ };+ if ("reply_to_user" in result.post) {+ props.reply_to_user = result.post.reply_to_user;+ } else if (result.post.reply_to_post_number == null) {+ props.reply_to_user = null;+ }+ post.setProperties(props);+ }this.args.closeModal();} catch (e) {if (e.jqXHR.responseJSON?.errors?.[0]) {diff --git a/frontend/discourse/app/components/modal/history/revision.gjs b/frontend/discourse/app/components/modal/history/revision.gjsindex 2ea4ee5ec97..826b6c5b4e9 100644--- a/frontend/discourse/app/components/modal/history/revision.gjs+++ b/frontend/discourse/app/components/modal/history/revision.gjs@@ -61,6 +61,47 @@ export default class Revision extends Component {{{@model.user_changes.current.username}}{{/if}}+ {{#if @model.reply_to_post_number_changes}}+ <span class="reply-to-changes">+ {{icon "share"}}+ {{#if @model.reply_to_post_number_changes.previous}}+ <span+ >#{{@model.reply_to_post_number_changes.previous.post_number}}</span>+ {{#if+ @model.reply_to_post_number_changes.previous.avatar_template+ }}+ {{boundAvatarTemplate+ @model.reply_to_post_number_changes.previous.avatar_template+ "small"+ }}+ {{@model.reply_to_post_number_changes.previous.username}}+ {{/if}}+ {{else}}+ <span class="diff-del">{{i18n+ "post.revisions.reply_to.none"+ }}</span>+ {{/if}}+ →+ {{#if @model.reply_to_post_number_changes.current}}+ <span+ >#{{@model.reply_to_post_number_changes.current.post_number}}</span>+ {{#if+ @model.reply_to_post_number_changes.current.avatar_template+ }}+ {{boundAvatarTemplate+ @model.reply_to_post_number_changes.current.avatar_template+ "small"+ }}+ {{@model.reply_to_post_number_changes.current.username}}+ {{/if}}+ {{else}}+ <span class="diff-ins">{{i18n+ "post.revisions.reply_to.none"+ }}</span>+ {{/if}}+ </span>+ {{/if}}+{{#if @model.wiki_changes}}{{icon"far-pen-to-square"diff --git a/frontend/discourse/app/components/modal/history/revisions.gjs b/frontend/discourse/app/components/modal/history/revisions.gjsindex 1c2f10392df..29ce35b2839 100644--- a/frontend/discourse/app/components/modal/history/revisions.gjs+++ b/frontend/discourse/app/components/modal/history/revisions.gjs@@ -104,6 +104,44 @@ export default class Revisions extends Component {{{@model.user_changes.current.username}}</div>{{/if}}+ {{#if @model.reply_to_post_number_changes}}+ <div class="row reply-to-changes">+ {{icon "share"}}+ {{#if @model.reply_to_post_number_changes.previous}}+ #{{@model.reply_to_post_number_changes.previous.post_number}}+ {{#if+ @model.reply_to_post_number_changes.previous.avatar_template+ }}+ {{Avatar+ @model.reply_to_post_number_changes.previous.avatar_template+ "small"+ }}+ {{@model.reply_to_post_number_changes.previous.username}}+ {{/if}}+ {{else}}+ <span class="diff-del">{{i18n+ "post.revisions.reply_to.none"+ }}</span>+ {{/if}}+ →+ {{#if @model.reply_to_post_number_changes.current}}+ #{{@model.reply_to_post_number_changes.current.post_number}}+ {{#if+ @model.reply_to_post_number_changes.current.avatar_template+ }}+ {{Avatar+ @model.reply_to_post_number_changes.current.avatar_template+ "small"+ }}+ {{@model.reply_to_post_number_changes.current.username}}+ {{/if}}+ {{else}}+ <span class="diff-ins">{{i18n+ "post.revisions.reply_to.none"+ }}</span>+ {{/if}}+ </div>+ {{/if}}{{#if @model.wiki_changes}}<div class="row">{{icondiff --git a/frontend/discourse/app/components/topic-timeline/container.gjs b/frontend/discourse/app/components/topic-timeline/container.gjsindex e09fe48352f..230e4392c78 100644--- a/frontend/discourse/app/components/topic-timeline/container.gjs+++ b/frontend/discourse/app/components/topic-timeline/container.gjs@@ -107,10 +107,14 @@ export default class TopicTimelineScrollArea extends Component {}});+ // The timeline is usually rendered on a topic page where both of these+ // anchors exist. When it's rendered outside of that context (for example,+ // a modal opened from a floating composer on a non-topic route), they+ // may be absent — skip observing rather than crashing.const elements = [document.querySelector(".container.posts"),document.querySelector("#topic-bottom"),- ];+ ].filter(Boolean);for (let i = 0; i < elements.length; i++) {this.intersectionObserver.observe(elements[i]);diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.jsindex 47cfdd2fef6..5fc195033eb 100644--- a/frontend/discourse/app/models/composer.js+++ b/frontend/discourse/app/models/composer.js@@ -108,6 +108,8 @@ const CLOSED = "closed",original_title: "originalTitle",original_tags: "originalTags",locale: "locale",+ reply_to_post_number: "reply_to_post_number",+ reply_to_user: "reply_to_user",},_add_draft_fields = {},FAST_REPLY_LENGTH_THRESHOLD = 10000;@@ -210,6 +212,8 @@ export default class Composer extends RestModel {@tracked post;@tracked reply;@tracked whisper;+ @tracked reply_to_post_number = null;+ @tracked reply_to_user = null;@trackedlocale = this.siteSettings.content_localization_enabled? this.post?.locale@@ -533,7 +537,7 @@ export default class Composer extends RestModel {return this.category?.topic_title_placeholder || null;}- @computed("action", "post", "topic", "topic.title")+ @computed("action", "post", "topic", "topic.title", "reply_to_user")get replyOptions() {const options = {userLink: null,@@ -560,10 +564,8 @@ export default class Composer extends RestModel {options.userAvatar = tinyAvatar(avatarTemplate);if (this.site.desktopView) {- const originalUserName = this.post.get("reply_to_user.username");- const originalUserAvatar = this.post.get(- "reply_to_user.avatar_template"- );+ const originalUserName = this.reply_to_user?.username;+ const originalUserAvatar = this.reply_to_user?.avatar_template;if (originalUserName && originalUserAvatar && isEdit(this.action)) {options.originalUser = {username: originalUserName,@@ -1063,11 +1065,39 @@ export default class Composer extends RestModel {promise = promise.then(async () => {const post = await this.store.find("post", opts.post.id);+ // When a draft is being restored, `opts` already carries the+ // composer's saved `reply_to_*` state (see `_draft_serializer`).+ // Prefer those values so pending reply-target changes survive a+ // reload or navigation; fall back to the post's stored state+ // otherwise. `undefined` means the key wasn't in the draft at all.+ //+ // `post.reply_to_user` is a rich `User` model instance with+ // circular back-refs (via `statusManager`), so we extract a plain+ // snapshot — otherwise `JSON.stringify` during periodic draft saves+ // throws "Converting circular structure to JSON".+ const replyToPostNumber =+ opts.reply_to_post_number !== undefined+ ? opts.reply_to_post_number+ : (post.reply_to_post_number ?? null);+ const postReplyToUser = post.reply_to_user;+ const replyToUser =+ opts.reply_to_user !== undefined+ ? opts.reply_to_user+ : postReplyToUser+ ? {+ id: postReplyToUser.id,+ username: postReplyToUser.username,+ name: postReplyToUser.name,+ avatar_template: postReplyToUser.avatar_template,+ }+ : null;this.setProperties({post,reply: post.raw,originalText: post.raw,originalTitle: this.topic.title,+ reply_to_post_number: replyToPostNumber,+ reply_to_user: replyToUser,});if (post.post_number === 1 && this.canEditTitle) {@@ -1143,6 +1173,15 @@ export default class Composer extends RestModel {featuredLink: null,noBump: false,editConflict: false,+ reply_to_post_number: null,+ reply_to_user: null,+ });+ }++ setReplyTo(postNumber, user) {+ this.setProperties({+ reply_to_post_number: postNumber ?? null,+ reply_to_user: postNumber ? (user ?? null) : null,});}@@ -1188,6 +1227,12 @@ export default class Composer extends RestModel {this.serialize(_update_serializer, props);+ // Only send when changed; otherwise a stale composer value could+ // clobber a concurrent reply-target change by another editor.+ if (this.reply_to_post_number !== (post?.reply_to_post_number ?? null)) {+ props.reply_to_post_number = this.reply_to_post_number;+ }+// user clicked "overwrite edits" buttonif (this.editConflict) {delete props.original_text;@@ -1209,6 +1254,14 @@ export default class Composer extends RestModel {return promise.then(() => {return post.save(props).then((result) => {+ // The server omits `reply_to_user` from the response when it's+ // nil, so the post's in-memory value isn't overwritten when the+ // target is cleared. Mirror the composer's final state onto the+ // post so reply indicators update without a refresh.+ post.setProperties({+ reply_to_post_number: this.reply_to_post_number,+ reply_to_user: this.reply_to_user,+ });this.clearState();return result;});diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.jsindex df47877c0a2..bbc76cde0be 100644--- a/frontend/discourse/app/services/composer.js+++ b/frontend/discourse/app/services/composer.js@@ -7,6 +7,7 @@ import Service, { service } from "@ember/service";import { isEmpty } from "@ember/utils";import { observes } from "@ember-decorators/object";import { Promise } from "rsvp";+import ChangeReplyTo from "discourse/components/modal/change-reply-to";import DiscardDraftModal from "discourse/components/modal/discard-draft";import PostEnqueuedModal from "discourse/components/modal/post-enqueued";import SpreadsheetEditor from "discourse/components/modal/spreadsheet-editor";@@ -42,6 +43,7 @@ import { parseAttributesString } from "discourse/lib/wrap-utils";import Category from "discourse/models/category";import Composer, {CREATE_TOPIC,+ EDIT,NEW_PRIVATE_MESSAGE_KEY,NEW_TOPIC_KEY,SAVE_ICONS,@@ -76,6 +78,14 @@ async function loadDraft(store, opts = {}) {attrs[f] = draft[f] || opts[f];});+ // `||` above collapses explicit `null`; for these fields `null` means+ // "no reply target" and must round-trip through the draft.+ ["reply_to_post_number", "reply_to_user"].forEach((f) => {+ if (draft && f in draft) {+ attrs[f] = draft[f];+ }+ });+const composer = store.createRecord("composer");await composer.open(attrs);@@ -519,7 +529,13 @@ export default class ComposerService extends Service {return this.model?.requiredCategoryMissing && this.model?.replyLength === 0;}- @computed("model.composeState", "model.creatingTopic", "model.post")+ @computed(+ "model.composeState",+ "model.creatingTopic",+ "model.post",+ "model.action",+ "model.reply_to_post_number"+ )get popupMenuOptions() {if (this.model?.composeState === "open" ||@@ -556,6 +572,17 @@ export default class ComposerService extends Service {}));+ if (this.canOpenReplyToModal) {+ options.push(+ this._setupPopupMenuOption({+ name: "change-reply-to",+ action: this.openChangeReplyToModal,+ icon: "share",+ label: "composer.change_reply_to.open_from_menu",+ })+ );+ }+const secondaryOptions = [this._setupPopupMenuOption({name: "toggle-wrap",@@ -578,6 +605,52 @@ export default class ComposerService extends Service {}}+ // Exposed via the composer toolbar popup as a fallback entry point for+ // the reply-target picker. Needed in contexts where the reply indicator+ // isn't rendered next to the title (mobile) or is suppressed (e.g.+ // `suppress_reply_when_quoting`), regardless of whether a target already+ // exists.+ //+ // Post 1 (the OP) has no earlier posts — the picker would have nothing+ // to select.+ get canOpenReplyToModal() {+ const model = this.model;+ return (+ model?.action === EDIT &&+ !!model?.post?.can_edit &&+ !!model?.topic &&+ (model?.post?.post_number ?? 0) > 1+ );+ }++ @action+ openChangeReplyToModal() {+ const model = this.model;+ if (!model) {+ return;+ }++ this.modal.show(ChangeReplyTo, {+ model: {+ topic: model.topic,+ editingPostNumber: model.post?.post_number,+ currentPostNumber: model.reply_to_post_number,+ onSelect: (post) => {+ if (!post) {+ model.setReplyTo(null, null);+ return;+ }+ model.setReplyTo(post.post_number, {+ id: post.user_id,+ username: post.username,+ name: post.name,+ avatar_template: post.avatar_template,+ });+ },+ },+ });+ }+@computed("model.creatingPrivateMessage","model.targetRecipients",diff --git a/frontend/discourse/tests/acceptance/composer-reply-to-test.js b/frontend/discourse/tests/acceptance/composer-reply-to-test.jsnew file mode 100644index 00000000000..285a585b520--- /dev/null+++ b/frontend/discourse/tests/acceptance/composer-reply-to-test.js@@ -0,0 +1,56 @@+import { click, visit, waitFor } from "@ember/test-helpers";+import { test } from "qunit";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";++acceptance("Composer - Reply target picker", function (needs) {+ needs.user({ id: 5, username: "kris" });++ // The topic fixture caches post 6 without `raw`, so the edit flow's+ // `store.find("post", ...)` has to fetch it fresh — mock that response+ // with a reply target set.+ needs.pretender((server, helper) => {+ server.get("/posts/3654", () =>+ helper.response({+ id: 3654,+ post_number: 6,+ topic_id: 280,+ raw: "Yes, I really like the concept of fuzzy matching for localization.",+ reply_to_post_number: 5,+ reply_to_user: {+ username: "pekka",+ name: "Pekka",+ avatar_template: "/images/avatar.png",+ },+ can_edit: true,+ version: 1,+ locale: null,+ })+ );+ });++ async function openEditForReplyPost() {+ await visit("/t/internationalization-localization/280");+ // Post 6 isn't the current user's, so the edit button is collapsed into+ // the "show more" overflow by default — expand it first.+ await click("article#post_6 button.show-more-actions");+ await click("article#post_6 button.edit");+ await waitFor(".d-editor-input");+ }++ test("the reply indicator in the edit title is a clickable button", async function (assert) {+ await openEditForReplyPost();++ assert+ .dom("button.composer-edit-reply-to")+ .exists("renders the reply target as a button inside the action title");+ });++ test("the toolbar options menu exposes a 'Reply to another post' entry", async function (assert) {+ await openEditForReplyPost();+ await click(".toolbar-menu__options-trigger");++ assert+ .dom("[data-name='change-reply-to']")+ .exists("the menu item is available for editors");+ });+});diff --git a/frontend/discourse/tests/unit/models/composer-test.js b/frontend/discourse/tests/unit/models/composer-test.jsindex e679394bf95..1895d2ad1b6 100644--- a/frontend/discourse/tests/unit/models/composer-test.js+++ b/frontend/discourse/tests/unit/models/composer-test.js@@ -294,6 +294,8 @@ module("Unit | Model | composer", function (hooks) {reply: "asdf2",post: store.createRecord("post", { id: 1 }),title: "wat",+ reply_to_post_number: 3,+ reply_to_user: { username: "alice" },});composer.clearState();@@ -302,6 +304,70 @@ module("Unit | Model | composer", function (hooks) {assert.blank(composer.reply);assert.blank(composer.post);assert.blank(composer.title);+ assert.blank(composer.reply_to_post_number);+ assert.blank(composer.reply_to_user);+ });++ test("setReplyTo and replyOptions live updates in edit mode", function (assert) {+ const store = getOwner(this).lookup("service:store");+ const composer = createComposer.call(this, {+ action: EDIT,+ topic: store.createRecord("topic", { id: 1, title: "t" }),+ post: store.createRecord("post", {+ id: 1,+ post_number: 3,+ avatar_template: "/a.png",+ username: "bob",+ name: "Bob",+ }),+ reply_to_post_number: 2,+ reply_to_user: {+ username: "alice",+ avatar_template: "/alice.png",+ },+ });++ assert.strictEqual(+ composer.replyOptions.originalUser?.username,+ "alice",+ "originalUser reflects composer state on open"+ );++ composer.setReplyTo(null, null);+ assert.strictEqual(composer.reply_to_post_number, null);+ assert.strictEqual(composer.reply_to_user, null);+ assert.strictEqual(+ composer.replyOptions.originalUser,+ null,+ "originalUser clears after removing reply target"+ );++ composer.setReplyTo(1, {+ username: "carol",+ avatar_template: "/carol.png",+ });+ assert.strictEqual(composer.reply_to_post_number, 1);+ assert.strictEqual(+ composer.replyOptions.originalUser?.username,+ "carol",+ "originalUser reflects the newly chosen target"+ );+ });++ test("reply_to edits are serialized into drafts", function (assert) {+ const store = getOwner(this).lookup("service:store");+ const composer = createComposer.call(this, {+ action: EDIT,+ topic: store.createRecord("topic", { id: 1 }),+ post: store.createRecord("post", { id: 1, post_number: 3 }),+ reply_to_post_number: 2,+ reply_to_user: { username: "alice", avatar_template: "/alice.png" },+ });++ const draft = composer.serializeDraftData();++ assert.strictEqual(draft.reply_to_post_number, 2);+ assert.strictEqual(draft.reply_to_user.username, "alice");});test("initial category when uncategorized is allowed", function (assert) {diff --git a/lib/post_revisor.rb b/lib/post_revisor.rbindex 74d898b075f..a6707484a5e 100644--- a/lib/post_revisor.rb+++ b/lib/post_revisor.rb@@ -82,7 +82,16 @@ class PostRevisorendend- POST_TRACKED_FIELDS = %w[raw cooked edit_reason user_id wiki post_type locale]+ POST_TRACKED_FIELDS = %w[+ raw+ cooked+ edit_reason+ user_id+ wiki+ post_type+ locale+ reply_to_post_number+ ]# Extensions can inspect revision options via the `:post_edited` event payload.attr_reader :category_changed, :post_revision, :opts@@ -261,6 +270,12 @@ class PostRevisor@fields[:category_id] = @fields[:category_id].to_i if @fields.has_key?(:category_id)@fields.delete(:tags) if @fields.has_key?(:tags) && @fields[:tags].blank? && @topic.tags.empty?+ if @fields.has_key?(:reply_to_post_number)+ normalized = @fields[:reply_to_post_number].presence+ @fields[:reply_to_post_number] = normalized.nil? ? nil : normalized.to_i+ return false unless resolve_reply_to_change+ end+# always reset edit_reason unless provided, do not set to nil else# previous reasons are lost@fields.delete(:edit_reason) if @fields[:edit_reason].blank?@@ -547,6 +562,8 @@ class PostRevisor@post.public_send("#{field}=", @fields[field]) if @fields.has_key?(field)end+ @post.reply_to_user_id = @new_reply_to_parent&.user_id if @post.reply_to_post_number_changed?+@post.edit_reason = @fields[:edit_reason] if should_create_new_version?@post.last_editor_id = @editor.id@post.word_count = @fields[:raw].scan(/[[:word:]]+/).size if @fields.has_key?(:raw)@@ -554,9 +571,18 @@ class PostRevisor@post.extract_quoted_post_numbers+ previous_reply_to_post_number = @post.reply_to_post_number_was+@post_successfully_saved = @post.save(validate: @validate_post)@post.link_post_uploads- @post.save_reply_relationships++ if @post_successfully_saved+ @post.save_reply_relationships+ cleanup_previous_reply_to_relationship+ if @post.saved_change_to_reply_to_post_number?+ @post.nested_replies_apply_reparent(previous_reply_to_post_number)+ end+ end# we don't want to increment post count on user mergeif @post_successfully_saved && @editor.id != Discourse::SYSTEM_USER_ID@@ -854,4 +880,59 @@ class PostRevisordef reviewable_content_changed?raw_changed? || topic_title_changed?end++ private++ def resolve_reply_to_change+ new_post_number = @fields[:reply_to_post_number]++ # Resolve trashed prior parents too — their stale `PostReply` row and+ # `reply_count` need cleanup on reparent.+ @old_reply_to_parent =+ if @post.reply_to_post_number.present?+ Post.with_deleted.find_by(topic_id: @post.topic_id, post_number: @post.reply_to_post_number)+ end+ @new_reply_to_parent = nil++ return true if new_post_number == @post.reply_to_post_number++ if new_post_number.present?+ @new_reply_to_parent =+ Post.where(topic_id: @post.topic_id, post_number: new_post_number).first++ unless valid_reply_to_parent?(@new_reply_to_parent)+ @post.errors.add(:reply_to_post_number, I18n.t("post.errors.invalid_reply_to"))+ return false+ end+ end++ true+ end++ def valid_reply_to_parent?(parent)+ return false if parent.blank?+ return false if parent.id == @post.id+ return false if @post.post_number.present? && parent.post_number >= @post.post_number+ return false unless guardian.can_see?(parent)+ true+ end++ def cleanup_previous_reply_to_relationship+ return unless @post.saved_change_to_reply_to_post_number?+ return if @old_reply_to_parent.blank?++ old_post_number = @old_reply_to_parent.post_number+ still_referenced =+ @post.reply_to_post_number == old_post_number ||+ @post.quoted_post_numbers.include?(old_post_number)+ return if still_referenced++ deleted = PostReply.where(post_id: @old_reply_to_parent.id, reply_post_id: @post.id).delete_all++ if deleted > 0 && Topic.visible_post_types.include?(@post.post_type)+ Post.where(id: @old_reply_to_parent.id).update_all(+ "reply_count = GREATEST(reply_count - 1, 0)",+ )+ end+ endenddiff --git a/spec/lib/post_revisor_spec.rb b/spec/lib/post_revisor_spec.rbindex 06d4a623588..98d45d61da7 100644--- a/spec/lib/post_revisor_spec.rb+++ b/spec/lib/post_revisor_spec.rb@@ -2033,4 +2033,253 @@ describe PostRevisor doexpect(Draft.find_by(user_id: post.user.id, draft_key: draft_key)).to be_nilendend++ describe "revising reply_to_post_number" do+ fab!(:topic)+ fab!(:op_author, :user)+ fab!(:first_reply_author, :user)+ fab!(:second_reply_author, :user)+ fab!(:editor) { Fabricate(:user, refresh_auto_groups: true) }++ fab!(:original_post) { Fabricate(:post, topic: topic, user: op_author, post_number: 1) }+ fab!(:first_reply) do+ PostCreator.create!(+ first_reply_author,+ topic_id: topic.id,+ raw: "first reply body, long enough to be valid",+ reply_to_post_number: 1,+ )+ end+ fab!(:second_reply) do+ PostCreator.create!(+ second_reply_author,+ topic_id: topic.id,+ raw: "second reply body, long enough to be valid",+ reply_to_post_number: 1,+ )+ end+ fab!(:post_to_edit) do+ PostCreator.create!(+ editor,+ topic_id: topic.id,+ raw: "my reply body, long enough to be valid",+ reply_to_post_number: 1,+ )+ end++ def revise(value, opts = {})+ PostRevisor.new(post_to_edit).revise!(+ editor,+ { reply_to_post_number: value },+ { bypass_rate_limiter: true }.merge(opts),+ )+ end++ it "reparents to another earlier post and syncs reply_to_user_id" do+ original_parent_reply_count = original_post.reload.reply_count++ expect(revise(first_reply.post_number)).to eq(true)++ post_to_edit.reload+ expect(post_to_edit.reply_to_post_number).to eq(first_reply.post_number)+ expect(post_to_edit.reply_to_user_id).to eq(first_reply.user_id)+ expect(first_reply.reload.reply_count).to eq(1)+ expect(original_post.reload.reply_count).to eq(original_parent_reply_count - 1)+ end++ it "removes the reply relationship when set to nil" do+ expect(revise(nil)).to eq(true)++ post_to_edit.reload+ expect(post_to_edit.reply_to_post_number).to be_nil+ expect(post_to_edit.reply_to_user_id).to be_nil+ expect(PostReply.where(post_id: original_post.id, reply_post_id: post_to_edit.id)).to be_empty+ end++ it "tracks the change in a PostRevision" do+ revise(first_reply.post_number, force_new_version: true)++ revision = post_to_edit.post_revisions.order(:number).last+ expect(revision.modifications["reply_to_post_number"]).to eq([1, first_reply.post_number])+ end++ it "does not create a revision when the value is unchanged" do+ expect { revise(post_to_edit.reply_to_post_number) }.not_to change {+ post_to_edit.post_revisions.count+ }+ end++ it "rejects a self-reference" do+ expect(revise(post_to_edit.post_number)).to eq(false)+ expect(post_to_edit.errors[:reply_to_post_number]).to be_present+ expect(post_to_edit.reload.reply_to_post_number).to eq(1)+ end++ it "rejects a later post in the topic" do+ later_post =+ PostCreator.create!(+ first_reply_author,+ topic_id: topic.id,+ raw: "a later post, long enough to be valid",+ )+ expect(revise(later_post.post_number)).to eq(false)+ expect(post_to_edit.errors[:reply_to_post_number]).to be_present+ end++ it "rejects a post that does not exist in the topic" do+ expect(revise(999)).to eq(false)+ expect(post_to_edit.errors[:reply_to_post_number]).to be_present+ end++ it "rejects a deleted post" do+ first_reply.trash!+ expect(revise(first_reply.post_number)).to eq(false)+ expect(post_to_edit.errors[:reply_to_post_number]).to be_present+ end++ it "keeps the PostReply row for the old parent if the post still quotes it" do+ post_to_edit.update!(+ raw: "quoting\n[quote=\"#{op_author.username}, post:1, topic:#{topic.id}\"]hi[/quote]",+ )+ post_to_edit.extract_quoted_post_numbers+ post_to_edit.save!++ expect(revise(first_reply.post_number)).to eq(true)+ expect(+ PostReply.where(post_id: original_post.id, reply_post_id: post_to_edit.id),+ ).to be_present+ end++ it "rejects a target the editor cannot see" do+ SiteSetting.whispers_allowed_groups = Group::AUTO_GROUPS[:staff]+ whisper =+ PostCreator.create!(+ admin,+ topic_id: topic.id,+ raw: "a whisper the editor cannot see",+ post_type: Post.types[:whisper],+ )++ expect(revise(whisper.post_number)).to eq(false)+ expect(post_to_edit.errors[:reply_to_post_number]).to be_present+ end++ it "does not create new PostReply rows when the post save fails" do+ SiteSetting.min_post_length = 500+ new_parent_reply_count = first_reply.reload.reply_count++ result =+ PostRevisor.new(post_to_edit).revise!(+ editor,+ { raw: "too short", reply_to_post_number: first_reply.post_number },+ bypass_rate_limiter: true,+ )++ expect(result).to eq(false)+ expect(PostReply.where(post_id: first_reply.id, reply_post_id: post_to_edit.id)).to be_empty+ expect(first_reply.reload.reply_count).to eq(new_parent_reply_count)+ end++ it "cleans up the PostReply row when the previous parent is already trashed" do+ original_post.trash!++ expect(+ PostReply.where(post_id: original_post.id, reply_post_id: post_to_edit.id),+ ).to be_present++ expect(revise(first_reply.post_number)).to eq(true)++ expect(PostReply.where(post_id: original_post.id, reply_post_id: post_to_edit.id)).to be_empty+ end++ context "with nested reply stats" do+ def direct_reply_count(post)+ NestedViewPostStat.where(post_id: post.id).pick(:direct_reply_count) || 0+ end++ def total_descendant_count(post)+ NestedViewPostStat.where(post_id: post.id).pick(:total_descendant_count) || 0+ end++ it "moves the subtree between ancestor chains on reparent" do+ SiteSetting.nested_replies_enabled = true++ nested_op = Fabricate(:post, topic: topic, user: op_author)+ nested_reparent_target =+ PostCreator.create!(+ first_reply_author,+ topic_id: topic.id,+ raw: "reparent target, long enough to be valid",+ reply_to_post_number: nested_op.post_number,+ )+ moved_post =+ PostCreator.create!(+ editor,+ topic_id: topic.id,+ raw: "the one we'll reparent, long enough",+ reply_to_post_number: nested_op.post_number,+ )++ # Before: nested_op has two direct children (target + moved_post).+ expect(direct_reply_count(nested_op)).to eq(2)+ expect(total_descendant_count(nested_op)).to eq(2)+ expect(direct_reply_count(nested_reparent_target)).to eq(0)+ expect(total_descendant_count(nested_reparent_target)).to eq(0)++ result =+ PostRevisor.new(moved_post).revise!(+ editor,+ { reply_to_post_number: nested_reparent_target.post_number },+ bypass_rate_limiter: true,+ )++ expect(result).to eq(true)+ # After: moved_post now lives under target. nested_op stays a shared+ # ancestor (2 total descendants) but loses a direct child; target+ # gains one direct + one total.+ expect(direct_reply_count(nested_op)).to eq(1)+ expect(total_descendant_count(nested_op)).to eq(2)+ expect(direct_reply_count(nested_reparent_target)).to eq(1)+ expect(total_descendant_count(nested_reparent_target)).to eq(1)+ end++ it "moves the subtree up when the new target is the current grandparent" do+ SiteSetting.nested_replies_enabled = true++ nested_op = Fabricate(:post, topic: topic, user: op_author)+ middle =+ PostCreator.create!(+ first_reply_author,+ topic_id: topic.id,+ raw: "middle, long enough to be valid",+ reply_to_post_number: nested_op.post_number,+ )+ moved_post =+ PostCreator.create!(+ editor,+ topic_id: topic.id,+ raw: "will move up, long enough",+ reply_to_post_number: middle.post_number,+ )++ expect(direct_reply_count(nested_op)).to eq(1)+ expect(total_descendant_count(nested_op)).to eq(2)+ expect(direct_reply_count(middle)).to eq(1)+ expect(total_descendant_count(middle)).to eq(1)++ PostRevisor.new(moved_post).revise!(+ editor,+ { reply_to_post_number: nested_op.post_number },+ bypass_rate_limiter: true,+ )++ # middle loses its only descendant; nested_op's total stays at 2,+ # its direct child count goes from 1 to 2.+ expect(direct_reply_count(middle)).to eq(0)+ expect(total_descendant_count(middle)).to eq(0)+ expect(direct_reply_count(nested_op)).to eq(2)+ expect(total_descendant_count(nested_op)).to eq(2)+ end+ end+ endenddiff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rbindex 522a7990083..cc8650b79ee 100644--- a/spec/requests/posts_controller_spec.rb+++ b/spec/requests/posts_controller_spec.rb@@ -919,6 +919,68 @@ RSpec.describe PostsController doexpect(post.reload.custom_fields[:random_number]).to eq("244")endend++ describe "reply_to_post_number" do+ fab!(:topic)+ fab!(:op) { Fabricate(:post, topic: topic, user: Fabricate(:user)) }+ fab!(:first_reply) do+ Fabricate(:post, topic: topic, user: Fabricate(:user), reply_to_post_number: op.post_number)+ end+ fab!(:editable_post) do+ Fabricate(+ :post,+ topic: topic,+ user: user,+ reply_to_post_number: op.post_number,+ reply_to_user_id: op.user_id,+ )+ end++ before { sign_in(user) }++ it "reparents the post to another earlier post" do+ put "/posts/#{editable_post.id}.json",+ params: {+ post: {+ raw: editable_post.raw,+ reply_to_post_number: first_reply.post_number,+ },+ }++ expect(response.status).to eq(200)+ editable_post.reload+ expect(editable_post.reply_to_post_number).to eq(first_reply.post_number)+ expect(editable_post.reply_to_user_id).to eq(first_reply.user_id)+ end++ it "clears the reply relationship when set to null" do+ put "/posts/#{editable_post.id}.json",+ params: {+ post: {+ raw: editable_post.raw,+ reply_to_post_number: nil,+ },+ }++ expect(response.status).to eq(200)+ editable_post.reload+ expect(editable_post.reply_to_post_number).to be_nil+ expect(editable_post.reply_to_user_id).to be_nil+ end++ it "returns an error when the target is invalid" do+ put "/posts/#{editable_post.id}.json",+ params: {+ post: {+ raw: editable_post.raw,+ reply_to_post_number: editable_post.post_number,+ },+ }++ expect(response.status).to eq(422)+ expect(editable_post.reload.reply_to_post_number).to eq(op.post_number)+ end+ endenddescribe "#destroy_bookmark" do@@ -2960,6 +3022,25 @@ RSpec.describe PostsController dopost.topic.reloadexpect(post.topic.tags.pluck(:name).sort).to eq(%w[tag1 tag2])end++ it "supports reverting reply-target-only revisions" do+ earlier_post = Fabricate(:post, topic: post.topic, post_number: post.post_number - 1)+ post.update!(reply_to_post_number: nil)++ reply_to_revision =+ Fabricate(+ :post_revision,+ post: post,+ modifications: {+ "reply_to_post_number" => [earlier_post.post_number, nil],+ },+ )++ put "/posts/#{post_id}/revisions/#{reply_to_revision.number}/revert.json"++ expect(response.status).to eq(200)+ expect(post.reload.reply_to_post_number).to eq(earlier_post.post_number)+ endendenddiff --git a/spec/serializers/post_revision_serializer_spec.rb b/spec/serializers/post_revision_serializer_spec.rbindex b8b81a5a2e3..99ff33328b5 100644--- a/spec/serializers/post_revision_serializer_spec.rb+++ b/spec/serializers/post_revision_serializer_spec.rb@@ -176,4 +176,111 @@ RSpec.describe PostRevisionSerializer doexpect(json[:locale_changes][:current]).to eq("ja")endend++ describe "reply_to_post_number edits" do+ fab!(:topic)+ fab!(:op) { Fabricate(:post, topic: topic, post_number: 1) }+ fab!(:other_parent) { Fabricate(:post, topic: topic, post_number: 2) }+ fab!(:subject_post) do+ Fabricate(+ :post,+ topic: topic,+ post_number: 3,+ version: 2,+ reply_to_post_number: other_parent.post_number,+ )+ end++ def serialize(revision)+ PostRevisionSerializer.new(+ revision,+ scope: Guardian.new(Fabricate(:user)),+ root: false,+ ).as_json+ end++ it "exposes the change with user info enrichment when the target still exists" do+ revision =+ Fabricate(+ :post_revision,+ post: subject_post,+ modifications: {+ "reply_to_post_number" => [op.post_number, other_parent.post_number],+ },+ )++ json = serialize(revision)++ expect(json[:reply_to_post_number_changes][:previous][:post_number]).to eq(op.post_number)+ expect(json[:reply_to_post_number_changes][:previous][:username]).to eq(+ op.user.username_lower,+ )+ expect(json[:reply_to_post_number_changes][:current][:post_number]).to eq(+ other_parent.post_number,+ )+ expect(json[:reply_to_post_number_changes][:current][:username]).to eq(+ other_parent.user.username_lower,+ )+ end++ it "returns nil on the side that has no reply target" do+ revision =+ Fabricate(+ :post_revision,+ post: subject_post,+ modifications: {+ "reply_to_post_number" => [nil, other_parent.post_number],+ },+ )++ json = serialize(revision)++ expect(json[:reply_to_post_number_changes][:previous]).to be_nil+ expect(json[:reply_to_post_number_changes][:current][:post_number]).to eq(+ other_parent.post_number,+ )+ end++ it "omits the field when reply_to_post_number didn't change" do+ revision =+ Fabricate(:post_revision, post: subject_post, modifications: { "raw" => %w[old new] })++ json = serialize(revision)++ expect(json).not_to have_key(:reply_to_post_number_changes)+ end++ it "does not leak author info for a target the viewer cannot see" do+ SiteSetting.whispers_allowed_groups = Group::AUTO_GROUPS[:staff]+ whisper =+ Fabricate(+ :post,+ topic: topic,+ post_number: 4,+ post_type: Post.types[:whisper],+ user: Fabricate(:user),+ )+ subject_post.update!(reply_to_post_number: whisper.post_number)++ revision =+ Fabricate(+ :post_revision,+ post: subject_post,+ modifications: {+ "reply_to_post_number" => [other_parent.post_number, whisper.post_number],+ },+ )++ json =+ PostRevisionSerializer.new(+ revision,+ scope: Guardian.new(Fabricate(:user)),+ root: false,+ ).as_json++ expect(json[:reply_to_post_number_changes][:current][:post_number]).to eq(whisper.post_number)+ expect(json[:reply_to_post_number_changes][:current]).not_to have_key(:username)+ expect(json[:reply_to_post_number_changes][:current]).not_to have_key(:avatar_template)+ end+ endend