Skip to content

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

FEATURE: Allow staff to unlist post revisions (#44926)

Gabriel Grubbaeb607b16c60c
diff --git a/app/assets/stylesheets/common/base/history.scss b/app/assets/stylesheets/common/base/history.scss
index d8f50da3abf..9d84c48cf03 100644
--- a/app/assets/stylesheets/common/base/history.scss
+++ b/app/assets/stylesheets/common/base/history.scss
@@ -71,6 +71,15 @@
gap: 0.25em;
}
+ .revision-details__unlisted {
+ color: var(--primary-medium);
+
+ .fk-d-tooltip__trigger-container {
+ align-items: center;
+ gap: 0.25em;
+ }
+ }
+
.revision__title,
.revision__locale,
.body-diff,
@@ -232,6 +241,7 @@
@include viewport.until(md) {
width: 100%;
flex: 1 1 100%;
+ flex-wrap: wrap;
button {
font-size: var(--font-down-1);
diff --git a/app/assets/stylesheets/common/components/notifications-tracking.scss b/app/assets/stylesheets/common/components/notifications-tracking.scss
index c597c1c22e5..3e5629e3986 100644
--- a/app/assets/stylesheets/common/components/notifications-tracking.scss
+++ b/app/assets/stylesheets/common/components/notifications-tracking.scss
@@ -1,6 +1,7 @@
.pinned-options-btn,
.notifications-tracking-btn,
.composer-actions-btn,
+.revision-visibility-btn,
.composer-toggle-item {
display: flex;
flex: 1 0 auto;
diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb
index a43ed1694b6..d5b83b214ac 100644
--- a/app/controllers/posts_controller.rb
+++ b/app/controllers/posts_controller.rb
@@ -471,7 +471,12 @@ class PostsController < ApplicationController
raise Discourse::NotFound if post.hidden && !guardian.can_view_hidden_post_revisions?
render_json_dump(
- PostRevisionSerializer.new(find_post_revision_from_params, scope: guardian, root: false),
+ PostRevisionSerializer.new(
+ find_post_revision_from_params,
+ scope: guardian,
+ root: false,
+ include_unlisted: include_unlisted_revisions?,
+ ),
)
end
@@ -484,6 +489,7 @@ class PostsController < ApplicationController
find_latest_post_revision_from_params,
scope: guardian,
root: false,
+ include_unlisted: include_unlisted_revisions?,
),
)
rescue ONPDiff::DiffLimitExceeded
@@ -559,6 +565,35 @@ class PostsController < ApplicationController
render body: nil
end
+ def unlist_revision
+ PostRevision::Unlist.call(service_params) do
+ on_success { head :no_content }
+ on_failed_contract do |contract|
+ render_json_error(contract.errors.full_messages, status: 400)
+ end
+ on_model_not_found(:post) { raise Discourse::NotFound }
+ on_failed_policy(:can_see_post) { raise Discourse::NotFound }
+ on_model_not_found(:post_revision) { raise Discourse::NotFound }
+ on_failed_policy(:can_unlist_post_revision) { raise Discourse::InvalidAccess }
+ on_failed_policy(:post_revision_not_hidden) do
+ render_json_error(I18n.t("cannot_unlist_hidden_revision"), status: 422)
+ end
+ end
+ end
+
+ def relist_revision
+ PostRevision::Relist.call(service_params) do
+ on_success { head :no_content }
+ on_failed_contract do |contract|
+ render_json_error(contract.errors.full_messages, status: 400)
+ end
+ on_model_not_found(:post) { raise Discourse::NotFound }
+ on_failed_policy(:can_see_post) { raise Discourse::NotFound }
+ on_model_not_found(:post_revision) { raise Discourse::NotFound }
+ on_failed_policy(:can_relist_post_revision) { raise Discourse::InvalidAccess }
+ end
+ end
+
def revert
raise Discourse::NotFound unless guardian.is_staff?
@@ -823,9 +858,8 @@ class PostsController < ApplicationController
def find_latest_post_revision_from_params
post = find_post_from_params
- finder = PostRevision.where(post_id: post.id).order(:number)
- finder = finder.where(hidden: false) unless guardian.is_staff?
- post_revision = finder.last
+ post_revision =
+ PostRevision.latest_for(post, guardian, include_unlisted: include_unlisted_revisions?)
raise Discourse::NotFound unless post_revision
@@ -855,6 +889,10 @@ class PostsController < ApplicationController
private
+ def include_unlisted_revisions?
+ params[:include_unlisted] == "true"
+ end
+
def markdown_for_revision
find_post_revision_from_topic_id.modifications[:raw].last
end
diff --git a/app/models/api_key_scope.rb b/app/models/api_key_scope.rb
index 1d9dacd4f12..d125a3a1081 100644
--- a/app/models/api_key_scope.rb
+++ b/app/models/api_key_scope.rb
@@ -90,7 +90,13 @@ class ApiKeyScope < ActiveRecord::Base
path_params: %i[post_id],
},
modify: {
- actions: %w[posts#hide_revision posts#show_revision posts#revert],
+ actions: %w[
+ posts#hide_revision
+ posts#show_revision
+ posts#unlist_revision
+ posts#relist_revision
+ posts#revert
+ ],
path_params: %i[post_id],
},
permanently_delete: {
diff --git a/app/models/post_revision.rb b/app/models/post_revision.rb
index 9c9c32363c3..fd036dacc03 100644
--- a/app/models/post_revision.rb
+++ b/app/models/post_revision.rb
@@ -4,6 +4,9 @@ class PostRevision < ActiveRecord::Base
belongs_to :post
belongs_to :user
+ # The history modal only loads this many of a post's newest revisions.
+ HISTORY_WINDOW = 99
+
attr_accessor :silent
serialize :modifications, type: Hash, coder: YAML
@@ -30,6 +33,18 @@ class PostRevision < ActiveRecord::Base
SQL
end
+ # Unlisted revisions are public, so one is still opened when no listed one is left among the
+ # revisions the history loads.
+ def self.latest_for(post, guardian, include_unlisted: false)
+ revisions = where(post_id: post.id).order(:number)
+ revisions = revisions.where(hidden: false) if !guardian.can_view_hidden_post_revisions?
+ return revisions.last if include_unlisted || guardian.can_navigate_unlisted_post_revisions?
+
+ loaded_numbers =
+ where(post_id: post.id).order(number: :desc).limit(HISTORY_WINDOW).select(:number)
+ revisions.where(unlisted: false, number: loaded_numbers).last || revisions.last
+ end
+
def categories
return [] if modifications["category_id"].blank?
@@ -37,13 +52,23 @@ class PostRevision < ActiveRecord::Base
end
def hide!
- update_column(:hidden, true)
+ update_columns(hidden: true, unlisted: false)
end
def show!
update_column(:hidden, false)
end
+ # Unlisting only trims what non-staff step through in the history; `hidden` is what
+ # restricts access.
+ def unlist!
+ update_column(:unlisted, true)
+ end
+
+ def relist!
+ update_column(:unlisted, false)
+ end
+
def create_notification
PostActionNotifier.after_create_post_revision(self)
end
@@ -68,6 +93,7 @@ end
# hidden :boolean default(FALSE), not null
# modifications :text
# number :integer
+# unlisted :boolean default(FALSE), not null
# created_at :datetime not null
# updated_at :datetime not null
# post_id :integer
diff --git a/app/serializers/post_revision_serializer.rb b/app/serializers/post_revision_serializer.rb
index e324c1dfddf..e24c0f9c9d8 100644
--- a/app/serializers/post_revision_serializer.rb
+++ b/app/serializers/post_revision_serializer.rb
@@ -6,6 +6,9 @@ class PostRevisionSerializer < ApplicationSerializer
# which revision is hidden
:previous_hidden,
:current_hidden,
+ # which revisions are skipped when navigating
+ :unlisted,
+ :unlisted_revision_count,
# dynamic & based on the current scope
:first_revision,
:previous_revision,
@@ -62,13 +65,17 @@ class PostRevisionSerializer < ApplicationSerializer
!!(adjacent_current && adjacent_current["hidden"])
end
+ def unlisted_revision_count
+ revisions.count { |r| r["unlisted"] }
+ end
+
def first_revision
- revisions.first["revision"]
+ navigable_revisions.first["revision"]
end
def previous_revision
@previous_revision ||=
- revisions
+ navigable_revisions
.select { |r| r["revision"] >= first_revision }
.select { |r| r["revision"] < current_revision }
.last
@@ -81,7 +88,7 @@ class PostRevisionSerializer < ApplicationSerializer
def next_revision
@next_revision ||=
- revisions
+ navigable_revisions
.select { |r| r["revision"] <= last_revision }
.select { |r| r["revision"] > current_revision }
.first
@@ -89,7 +96,9 @@ class PostRevisionSerializer < ApplicationSerializer
end
def last_revision
- @last_revision ||= revisions.select { |r| r["revision"] <= post.version }.last["revision"]
+ @last_revision ||=
+ navigable_revisions.select { |r| r["revision"] <= post.version }.last&.dig("revision") ||
+ current_revision
end
def current_version
@@ -267,11 +276,27 @@ class PostRevisionSerializer < ApplicationSerializer
all_revisions.select { |r| scope.can_view_hidden_post_revisions? || !r["hidden"] }
end
+ # Diffs keep using `revisions`, so skipping an unlisted revision never merges it into a
+ # neighbor's diff. The current revision stays so direct links to an unlisted one work.
+ def navigable_revisions
+ @navigable_revisions ||=
+ if scope.can_navigate_unlisted_post_revisions? || @options[:include_unlisted]
+ revisions
+ else
+ revisions.reject { |r| r["unlisted"] && r["revision"] != current_revision }
+ end
+ end
+
def all_revisions
return @all_revisions if @all_revisions
post_revisions =
- PostRevision.where(post_id: object.post_id).order(number: :desc).limit(99).to_a.reverse
+ PostRevision
+ .where(post_id: object.post_id)
+ .order(number: :desc)
+ .limit(PostRevision::HISTORY_WINDOW)
+ .to_a
+ .reverse
latest_modifications = {
"raw" => [post.raw],
@@ -314,6 +339,7 @@ class PostRevisionSerializer < ApplicationSerializer
revision = ActiveSupport::HashWithIndifferentAccess.new
revision[:revision] = pr.number
revision[:hidden] = pr.hidden
+ revision[:unlisted] = pr.unlisted
pr.modifications.each { |field, (value, _)| revision[field] = value }
diff --git a/app/services/post_revision/relist.rb b/app/services/post_revision/relist.rb
new file mode 100644
index 00000000000..55d470ec90f
--- /dev/null
+++ b/app/services/post_revision/relist.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+class PostRevision::Relist
+ include Service::Base
+
+ params do
+ attribute :post_id, :integer
+ attribute :revision, :integer
+
+ validates :post_id, :revision, presence: true
+ end
+
+ model :post
+ policy :can_see_post
+ model :post_revision
+ policy :can_relist_post_revision
+ step :relist
+
+ private
+
+ def fetch_post(params:)
+ # Staff can still see posts in a trashed topic, which the default topic scope hides.
+ Post
+ .with_deleted
+ .find_by(id: params.post_id)
+ &.tap { |post| post.topic ||= Topic.with_deleted.find_by(id: post.topic_id) }
+ end
+
+ def can_see_post(guardian:, post:)
+ guardian.can_see?(post)
+ end
+
+ def fetch_post_revision(params:, post:)
+ post.revisions.find_by(number: params.revision)
+ end
+
+ def can_relist_post_revision(guardian:, post_revision:)
+ guardian.can_relist_post_revision?(post_revision)
+ end
+
+ def relist(post_revision:)
+ post_revision.relist!
+ end
+end
diff --git a/app/services/post_revision/unlist.rb b/app/services/post_revision/unlist.rb
new file mode 100644
index 00000000000..d445b61cf9e
--- /dev/null
+++ b/app/services/post_revision/unlist.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+class PostRevision::Unlist
+ include Service::Base
+
+ params do
+ attribute :post_id, :integer
+ attribute :revision, :integer
+
+ validates :post_id, :revision, presence: true
+ end
+
+ model :post
+ policy :can_see_post
+
+ transaction do
+ model :post_revision
+ policy :can_unlist_post_revision
+ policy :post_revision_not_hidden
+ step :unlist
+ end
+
+ private
+
+ def fetch_post(params:)
+ # Staff can still see posts in a trashed topic, which the default topic scope hides.
+ Post
+ .with_deleted
+ .find_by(id: params.post_id)
+ &.tap { |post| post.topic ||= Topic.with_deleted.find_by(id: post.topic_id) }
+ end
+
+ def can_see_post(guardian:, post:)
+ guardian.can_see?(post)
+ end
+
+ def fetch_post_revision(params:, post:)
+ # Locked so a concurrent hide can't land between the hidden check and the write.
+ post.revisions.lock.find_by(number: params.revision)
+ end
+
+ def can_unlist_post_revision(guardian:, post_revision:)
+ guardian.can_unlist_post_revision?(post_revision)
+ end
+
+ def post_revision_not_hidden(post_revision:)
+ !post_revision.hidden
+ end
+
+ def unlist(post_revision:)
+ post_revision.unlist!
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 78cf42f6917..81b177c73dd 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -5424,6 +5424,20 @@ en:
revisions:
diff_too_complex: "This edit changed too much of the post at once, so it can't be shown."
diff_hidden: "Some of this post's edit history has been hidden, so this edit can't be shown."
+ unlisted:
+ label: "Unlisted"
+ description: "This edit is skipped when browsing the edit history, but its content is still public."
+ show_all_edits: "Show all edits"
+ visibility:
+ listed:
+ title: "Listed"
+ description: "Shown when browsing the edit history."
+ unlisted:
+ title: "Unlisted"
+ description: "Skipped when browsing the edit history."
+ hidden:
+ title: "Hidden"
+ description: "Removed from the public edit history, along with the diffs next to it."
locale:
no_locale_set: "No language set"
locale_removed: "Language removed"
@@ -5434,9 +5448,7 @@ en:
previous: "Previous revision"
next: "Next revision"
last: "Last revision"
- hide: "Hide revision"
- show: "Show revision"
- destroy: "Delete revisions"
+ destroy: "Delete all revisions"
destroy_confirm: "Are you sure you want to delete all of the revisions on this post? This action is permanent."
revert: "Revert to revision %{revision}"
edit_wiki: "Edit Wiki"
@@ -8429,7 +8441,7 @@ en:
list: List latest posts and private posts. RSS is also supported.
revisions:
read: "Get the latest or a specific revision."
- modify: "Hide, show, or revert revisions."
+ modify: "Hide, show, unlist, relist, or revert revisions."
permanently_delete: "Permanently delete a revision."
tags:
list: List tags.
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 9ef70980a9a..c6085b83b9e 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -852,6 +852,7 @@ en:
edit_conflict: "That post was edited by another user and your changes can no longer be saved."
revert_version_same: "The current version is same as the version you are trying to revert to."
reverted_to_version: "reverted to version #%{version}"
+ cannot_unlist_hidden_revision: "A hidden revision can't be unlisted. Show it first, then unlist it."
cannot_edit_on_slow_mode: "This topic is in slow mode. To encourage thoughtful, considered discussion, editing old posts in this topic is not currently allowed during slow mode."
excerpt_image: "image"
diff --git a/config/routes.rb b/config/routes.rb
index f8db1a77625..1f85fc827a9 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1366,6 +1366,14 @@ Discourse::Application.routes.draw do
get "revisions/:revision" => "posts#revisions", :constraints => { revision: /\d+/ }
put "revisions/:revision/hide" => "posts#hide_revision", :constraints => { revision: /\d+/ }
put "revisions/:revision/show" => "posts#show_revision", :constraints => { revision: /\d+/ }
+ put "revisions/:revision/unlist" => "posts#unlist_revision",
+ :constraints => {
+ revision: /\d+/,
+ }
+ put "revisions/:revision/relist" => "posts#relist_revision",
+ :constraints => {
+ revision: /\d+/,
+ }
put "revisions/:revision/revert" => "posts#revert", :constraints => { revision: /\d+/ }
delete "revisions/permanently_delete" => "posts#permanently_delete_revisions"
get "permanently_delete_check" => "posts#permanently_delete_check",
diff --git a/db/migrate/20261021180714_add_unlisted_to_post_revisions.rb b/db/migrate/20261021180714_add_unlisted_to_post_revisions.rb
new file mode 100644
index 00000000000..8f3a1302369
--- /dev/null
+++ b/db/migrate/20261021180714_add_unlisted_to_post_revisions.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+class AddUnlistedToPostRevisions < ActiveRecord::Migration[8.1]
+ def change
+ add_column :post_revisions, :unlisted, :boolean, default: false, null: false
+
+ # Validated in a separate migration so the table scan doesn't run under this lock.
+ add_check_constraint :post_revisions,
+ "NOT (hidden AND unlisted)",
+ name: "post_revisions_hidden_unlisted_exclusive",
+ validate: false
+ end
+end
diff --git a/db/migrate/20261021180718_validate_post_revisions_hidden_unlisted_check.rb b/db/migrate/20261021180718_validate_post_revisions_hidden_unlisted_check.rb
new file mode 100644
index 00000000000..7d7a4f0af36
--- /dev/null
+++ b/db/migrate/20261021180718_validate_post_revisions_hidden_unlisted_check.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+class ValidatePostRevisionsHiddenUnlistedCheck < ActiveRecord::Migration[8.1]
+ def up
+ validate_check_constraint :post_revisions, name: "post_revisions_hidden_unlisted_exclusive"
+ end
+
+ def down
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index 358424d7d79..e6cb0e6891d 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -9416,7 +9416,9 @@ CREATE TABLE public.post_revisions (
number integer,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
- hidden boolean DEFAULT false NOT NULL
+ hidden boolean DEFAULT false NOT NULL,
+ unlisted boolean DEFAULT false NOT NULL,
+ CONSTRAINT post_revisions_hidden_unlisted_exclusive CHECK ((NOT (hidden AND unlisted)))
);
@@ -26165,6 +26167,8 @@ SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
('20261029021723'),
+('20261021180718'),
+('20261021180714'),
('20261021063131'),
('20261021063122'),
('20261021061850'),
diff --git a/frontend/discourse/app/components/modal/history.gjs b/frontend/discourse/app/components/modal/history.gjs
index 0954cfff1fa..640988e1ed7 100644
--- a/frontend/discourse/app/components/modal/history.gjs
+++ b/frontend/discourse/app/components/modal/history.gjs
@@ -7,6 +7,7 @@ import Revision from "discourse/components/modal/history/revision";
import Revisions from "discourse/components/modal/history/revisions";
import TopicFooter from "discourse/components/modal/history/topic-footer";
import PermanentlyDeleteConfirmModal from "discourse/components/modal/permanently-delete-confirm";
+import { popupAjaxError } from "discourse/lib/ajax-error";
import { iconHTML } from "discourse/lib/icon-library";
import { sanitizeAsync } from "discourse/lib/text";
import Category from "discourse/models/category";
@@ -27,6 +28,22 @@ function customTagArray(val) {
return val;
}
+const VISIBILITY_TRANSITIONS = {
+ listed: {
+ unlisted: [Post.unlistRevision],
+ hidden: [Post.hideRevision],
+ },
+ unlisted: {
+ listed: [Post.relistRevision],
+ hidden: [Post.hideRevision],
+ },
+ // The server refuses to unlist a hidden revision, so it is shown first.
+ hidden: {
+ listed: [Post.showRevision],
+ unlisted: [Post.showRevision, Post.unlistRevision],
+ },
+};
+
export default class History extends Component {
@service dialog;
@service modal;
@@ -40,6 +57,7 @@ export default class History extends Component {
@tracked bodyDiff;
@tracked initialLoad = true;
@tracked error;
+ @tracked includeUnlisted = false;
constructor() {
super(...arguments);
@@ -81,6 +99,12 @@ export default class History extends Component {
return this.postRevision?.version_count > 2;
}
+ get showUnlistedToggle() {
+ return (
+ !this.currentUser?.staff && this.postRevision?.unlisted_revision_count > 0
+ );
+ }
+
get modalTitleKey() {
return this.args.model.post.version > 100
? "history_capped_revisions"
@@ -225,6 +249,13 @@ export default class History extends Component {
}
}
+ get visibility() {
+ if (this.postRevision?.previous_hidden) {
+ return "hidden";
+ }
+ return this.postRevision?.unlisted ? "unlisted" : "listed";
+ }
+
@action
async calculateBodyDiff(_, [bodyDiff]) {
let html = bodyDiff;
@@ -245,7 +276,9 @@ export default class History extends Component {
this.loading = true;
this.error = null;
try {
- const result = await Post.loadRevision(postId, postVersion);
+ const result = await Post.loadRevision(postId, postVersion, {
+ includeUnlisted: this.includeUnlisted,
+ });
this.postRevision = result;
if (result.diff_error) {
this.error = i18n("post.revisions.diff_too_complex");
@@ -264,18 +297,6 @@ export default class History extends Component {
}
}
- hide(postId, postVersion) {
- Post.hideRevision(postId, postVersion).then(() =>
- this.refresh(postId, postVersion)
- );
- }
-
- show(postId, postVersion) {
- Post.showRevision(postId, postVersion).then(() =>
- this.refresh(postId, postVersion)
- );
- }
-
async revert(post, postVersion) {
try {
const result = await post.revertToRevision(postVersion);
@@ -358,11 +379,6 @@ export default class History extends Component {
);
}
- @action
- hideVersion() {
- this.hide(this.postRevision?.post_id, this.postRevision?.current_revision);
- }
-
@action
permanentlyDeleteVersions() {
const postId = this.postRevision?.post_id;
@@ -380,8 +396,29 @@ export default class History extends Component {
}
@action
- showVersion() {
- this.show(this.postRevision?.post_id, this.postRevision?.current_revision);
+ async changeVisibility(target) {
+ const postId = this.postRevision?.post_id;
+ const postVersion = this.postRevision?.current_revision;
+
+ try {
+ for (const request of VISIBILITY_TRANSITIONS[this.visibility][target]) {
+ await request(postId, postVersion);
+ }
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ // A multi-step change can fail after its first step has landed.
+ await this.refresh(postId, postVersion);
+ }
+ }
+
+ @action
+ toggleIncludeUnlisted() {
+ this.includeUnlisted = !this.includeUnlisted;
+ this.refresh(
+ this.postRevision?.post_id,
+ this.postRevision?.current_revision
+ );
}
@action
@@ -441,11 +478,12 @@ export default class History extends Component {
{{#if this.postRevision}}
<TopicFooter
@canPermanentlyDelete={{this.siteSettings.can_permanently_delete}}
+ @changeVisibility={{this.changeVisibility}}
@displayEdit={{this.displayEdit}}
@displayRevisions={{this.displayRevisions}}
@editButtonLabel={{this.editButtonLabel}}
@editPost={{this.editPost}}
- @hideVersion={{this.hideVersion}}
+ @includeUnlisted={{this.includeUnlisted}}
@isStaff={{this.currentUser.staff}}
@loadFirstDisabled={{this.loadFirstDisabled}}
@loadFirstVersion={{this.loadFirstVersion}}
@@ -461,7 +499,9 @@ export default class History extends Component {
@revertToRevisionText={{this.revertToRevisionText}}
@revertToVersion={{this.revertToVersion}}
@revisionsText={{this.revisionsText}}
- @showVersion={{this.showVersion}}
+ @showUnlistedToggle={{this.showUnlistedToggle}}
+ @toggleIncludeUnlisted={{this.toggleIncludeUnlisted}}
+ @visibility={{this.visibility}}
/>
{{/if}}
{{/if}}
diff --git a/frontend/discourse/app/components/modal/history/revision.gjs b/frontend/discourse/app/components/modal/history/revision.gjs
index ebec5c4e49f..edb12d7ddda 100644
--- a/frontend/discourse/app/components/modal/history/revision.gjs
+++ b/frontend/discourse/app/components/modal/history/revision.gjs
@@ -4,6 +4,7 @@ import { LinkTo } from "@ember/routing";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import PluginOutlet from "discourse/components/plugin-outlet";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
import lazyHash from "discourse/helpers/lazy-hash";
import dAgeWithTooltip from "discourse/ui-kit/helpers/d-age-with-tooltip";
import dBoundAvatarTemplate from "discourse/ui-kit/helpers/d-bound-avatar-template";
@@ -44,6 +45,18 @@ export default class Revision extends Component {
<span class="edit-reason">{{@model.edit_reason}}</span>
{{/if}}
+ {{#if @model.unlisted}}
+ <DTooltip
+ class="revision-details__unlisted"
+ @content={{i18n "post.revisions.unlisted.description"}}
+ >
+ <:trigger>
+ {{dIcon "list"}}
+ <span>{{i18n "post.revisions.unlisted.label"}}</span>
+ </:trigger>
+ </DTooltip>
+ {{/if}}
+
{{#if this.site.desktopView}}
<span>
{{#if @model.user_changes}}
diff --git a/frontend/discourse/app/components/modal/history/topic-footer.gjs b/frontend/discourse/app/components/modal/history/topic-footer.gjs
index 1b99a3b15a2..29464b539dc 100644
--- a/frontend/discourse/app/components/modal/history/topic-footer.gjs
+++ b/frontend/discourse/app/components/modal/history/topic-footer.gjs
@@ -1,6 +1,9 @@
+import { on } from "@ember/modifier";
import { trustHTML } from "@ember/template";
import DButton from "discourse/ui-kit/d-button";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
+import VisibilityMenu from "./visibility-menu.gjs";
const TopicFooter = <template>
<div id="revision-controls">
@@ -44,6 +47,16 @@ const TopicFooter = <template>
</div>
<div id="revision-footer-buttons">
+ {{#if @showUnlistedToggle}}
+ <DToggleSwitch
+ class="show-unlisted-revisions"
+ disabled={{@loading}}
+ @label="post.revisions.show_all_edits"
+ @state={{@includeUnlisted}}
+ {{on "click" @toggleIncludeUnlisted}}
+ />
+ {{/if}}
+
{{#if @displayEdit}}
<DButton
class="btn-default edit-post"
@@ -64,33 +77,13 @@ const TopicFooter = <template>
/>
{{/if}}
- {{#if @model.previous_hidden}}
- <DButton
- class="btn-default show-revision"
- @action={{@showVersion}}
- @disabled={{@loading}}
- @icon="far-eye"
- @label="post.revisions.controls.show"
- />
- {{else}}
- <DButton
- class="btn-danger hide-revision"
- @action={{@hideVersion}}
- @disabled={{@loading}}
- @icon="far-eye-slash"
- @label="post.revisions.controls.hide"
- />
- {{/if}}
-
- {{#if (and @canPermanentlyDelete @model.previous_hidden)}}
- <DButton
- class="btn-danger destroy-revision"
- @action={{@permanentlyDeleteVersions}}
- @disabled={{@loading}}
- @icon="trash-can"
- @label="post.revisions.controls.destroy"
- />
- {{/if}}
+ <VisibilityMenu
+ @canPermanentlyDelete={{@canPermanentlyDelete}}
+ @disabled={{@loading}}
+ @onChange={{@changeVisibility}}
+ @onPermanentlyDelete={{@permanentlyDeleteVersions}}
+ @visibility={{@visibility}}
+ />
{{/if}}
</div>
</template>;
diff --git a/frontend/discourse/app/components/modal/history/visibility-menu.gjs b/frontend/discourse/app/components/modal/history/visibility-menu.gjs
new file mode 100644
index 00000000000..cfc22e29e59
--- /dev/null
+++ b/frontend/discourse/app/components/modal/history/visibility-menu.gjs
@@ -0,0 +1,97 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DMenu from "discourse/float-kit/components/d-menu";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+const OPTIONS = [
+ { id: "listed", icon: "far-eye" },
+ { id: "unlisted", icon: "list" },
+ { id: "hidden", icon: "far-eye-slash" },
+];
+
+export default class VisibilityMenu extends Component {
+ get options() {
+ return OPTIONS.map((option) => ({
+ ...option,
+ title: i18n(`post.revisions.visibility.${option.id}.title`),
+ description: i18n(`post.revisions.visibility.${option.id}.description`),
+ }));
+ }
+
+ get current() {
+ return this.options.find((option) => option.id === this.args.visibility);
+ }
+
+ get otherOptions() {
+ return this.options.filter((option) => option.id !== this.args.visibility);
+ }
+
+ @action
+ async select(close, id) {
+ await close();
+ this.args.onChange(id);
+ }
+
+ @action
+ async delete(close) {
+ await close();
+ this.args.onPermanentlyDelete();
+ }
+
+ <template>
+ {{! Inline, or the menu renders behind the modal it opens from. }}
+ <DMenu
+ @disabled={{@disabled}}
+ @icon={{this.current.icon}}
+ @identifier="revision-visibility"
+ @inline={{true}}
+ @label={{this.current.title}}
+ @modalForMobile={{true}}
+ @triggerClass="btn-default revision-visibility__trigger"
+ >
+ <:trigger>
+ {{dIcon "angle-down" class="revision-visibility__caret"}}
+ </:trigger>
+ <:content as |menu|>
+ <DDropdownMenu as |dropdown|>
+ {{#each this.otherOptions as |option|}}
+ <dropdown.item>
+ <DButton
+ class="revision-visibility-btn --with-description"
+ data-revision-visibility={{option.id}}
+ @action={{fn this.select menu.close option.id}}
+ >
+ <div class="revision-visibility-btn__icons">
+ {{dIcon option.icon}}
+ </div>
+ <div class="revision-visibility-btn__texts">
+ <span class="revision-visibility-btn__label">
+ {{option.title}}
+ </span>
+ <span class="revision-visibility-btn__description">
+ {{option.description}}
+ </span>
+ </div>
+ </DButton>
+ </dropdown.item>
+ {{/each}}
+ {{#if @canPermanentlyDelete}}
+ <dropdown.divider />
+ <dropdown.item>
+ <DButton
+ class="btn-transparent btn-danger destroy-revision"
+ @action={{fn this.delete menu.close}}
+ @icon="trash-can"
+ @label="post.revisions.controls.destroy"
+ />
+ </dropdown.item>
+ {{/if}}
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </template>
+}
diff --git a/frontend/discourse/app/models/post.ts b/frontend/discourse/app/models/post.ts
index 74c379a4048..e32d96d74c1 100644
--- a/frontend/discourse/app/models/post.ts
+++ b/frontend/discourse/app/models/post.ts
@@ -374,16 +374,17 @@ export default class Post extends RestModel {
static loadRevision(
postId: number,
- version: number
+ version: number,
+ { includeUnlisted = false }: { includeUnlisted?: boolean } = {}
): globalThis.Promise<EmberObject> {
- return ajax(`/posts/${postId}/revisions/${version}.json`).then(
- (result: RestPayload & { categories?: CategoryFields[] }) => {
- result.categories?.forEach((c: CategoryFields) =>
- Site.current().updateCategory(c)
- );
- return EmberObject.create(result as object);
- }
- );
+ return ajax(`/posts/${postId}/revisions/${version}.json`, {
+ data: includeUnlisted ? { include_unlisted: true } : {},
+ }).then((result: RestPayload & { categories?: CategoryFields[] }) => {
+ result.categories?.forEach((c: CategoryFields) =>
+ Site.current().updateCategory(c)
+ );
+ return EmberObject.create(result as object);
+ });
}
static hideRevision(
@@ -412,6 +413,24 @@ export default class Post extends RestModel {
});
}
+ static unlistRevision(
+ postId: number,
+ version: number
+ ): globalThis.Promise<unknown> {
+ return ajax(`/posts/${postId}/revisions/${version}/unlist`, {
+ type: "PUT",
+ });
+ }
+
+ static relistRevision(
+ postId: number,
+ version: number
+ ): globalThis.Promise<unknown> {
+ return ajax(`/posts/${postId}/revisions/${version}/relist`, {
+ type: "PUT",
+ });
+ }
+
static loadRawEmail(postId: number): globalThis.Promise<unknown> {
return ajax(`/posts/${postId}/raw-email.json`);
}
diff --git a/frontend/discourse/tests/acceptance/history-test.js b/frontend/discourse/tests/acceptance/history-test.js
index 337f74c5e0d..1076057181c 100644
--- a/frontend/discourse/tests/acceptance/history-test.js
+++ b/frontend/discourse/tests/acceptance/history-test.js
@@ -3,6 +3,7 @@ import { test } from "qunit";
import { cloneJSON } from "discourse/lib/object";
import topicFixtures from "discourse/tests/fixtures/topic";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
const revisionResponse = {
created_at: "2021-11-24T10:59:36.163Z",
@@ -135,3 +136,235 @@ acceptance("History Modal - not found", function (needs) {
.doesNotExist("it should refresh the post to hide the revisions button");
});
});
+
+acceptance("History Modal - revision visibility as staff", function (needs) {
+ let hidden, unlisted, unlistFails, requests;
+
+ needs.user();
+ needs.hooks.beforeEach(() => {
+ hidden = false;
+ unlisted = false;
+ unlistFails = false;
+ requests = [];
+ });
+ needs.pretender((server, helper) => {
+ const revision = () => ({
+ ...revisionResponse,
+ previous_hidden: hidden,
+ unlisted,
+ unlisted_revision_count: unlisted ? 1 : 0,
+ });
+ const change = (action, apply) => () => {
+ requests.push(action);
+ apply();
+ return helper.response({});
+ };
+
+ server.get("/posts/419/revisions/latest.json", () =>
+ helper.response(revision())
+ );
+ server.get("/posts/419/revisions/2.json", () =>
+ helper.response(revision())
+ );
+ server.put("/posts/419/revisions/2/unlist", (request) =>
+ unlistFails
+ ? helper.response(422, { errors: ["Can't unlist this revision"] })
+ : change("unlist", () => (unlisted = true))(request)
+ );
+ server.put(
+ "/posts/419/revisions/2/relist",
+ change("relist", () => (unlisted = false))
+ );
+ server.put(
+ "/posts/419/revisions/2/hide",
+ change("hide", () => {
+ hidden = true;
+ unlisted = false;
+ })
+ );
+ server.put(
+ "/posts/419/revisions/2/show",
+ change("show", () => (hidden = false))
+ );
+ });
+
+ async function chooseVisibility(visibility) {
+ await click(".history-modal .revision-visibility__trigger");
+ await click(`.history-modal [data-revision-visibility='${visibility}']`);
+ }
+
+ test("unlisting and relisting a revision", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("article[data-post-id='419'] .edits button");
+
+ assert
+ .dom(".history-modal .revision-visibility__trigger")
+ .hasText(i18n("post.revisions.visibility.listed.title"));
+ assert
+ .dom(".history-modal .revision-details__unlisted")
+ .doesNotExist("doesn't mark a listed revision");
+
+ await chooseVisibility("unlisted");
+
+ assert
+ .dom(".history-modal .revision-visibility__trigger")
+ .hasText(i18n("post.revisions.visibility.unlisted.title"));
+ assert
+ .dom(".history-modal .revision-details__unlisted")
+ .hasText(i18n("post.revisions.unlisted.label"), "marks it as unlisted");
+ assert
+ .dom(".history-modal .show-unlisted-revisions")
+ .doesNotExist("doesn't offer staff the unlisted toggle");
+
+ await chooseVisibility("listed");
+
+ assert
+ .dom(".history-modal .revision-details__unlisted")
+ .doesNotExist("removes the marker once relisted");
+ assert.deepEqual(requests, ["unlist", "relist"]);
+ });
+
+ test("only offers the other visibilities", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("article[data-post-id='419'] .edits button");
+ await click(".history-modal .revision-visibility__trigger");
+
+ assert
+ .dom(".history-modal [data-revision-visibility='listed']")
+ .doesNotExist("doesn't offer the current visibility");
+ assert.dom(".history-modal [data-revision-visibility='unlisted']").exists();
+ assert.dom(".history-modal [data-revision-visibility='hidden']").exists();
+ assert
+ .dom(".history-modal .destroy-revision")
+ .doesNotExist("doesn't offer to delete revisions by default");
+ });
+
+ test("unlisting a hidden revision", async function (assert) {
+ hidden = true;
+
+ await visit("/t/internationalization-localization/280");
+ await click("article[data-post-id='419'] .edits button");
+
+ assert
+ .dom(".history-modal .revision-visibility__trigger")
+ .hasText(i18n("post.revisions.visibility.hidden.title"));
+
+ await chooseVisibility("unlisted");
+
+ assert
+ .dom(".history-modal .revision-visibility__trigger")
+ .hasText(i18n("post.revisions.visibility.unlisted.title"));
+ assert.deepEqual(
+ requests,
+ ["show", "unlist"],
+ "shows the revision before unlisting it"
+ );
+ });
+
+ test("unlisting a hidden revision fails after showing it", async function (assert) {
+ hidden = true;
+ unlistFails = true;
+
+ await visit("/t/internationalization-localization/280");
+ await click("article[data-post-id='419'] .edits button");
+ await chooseVisibility("unlisted");
+
+ assert.dom(".dialog-body").exists("reports the failure");
+ assert
+ .dom(".history-modal .revision-visibility__trigger")
+ .hasText(
+ i18n("post.revisions.visibility.listed.title"),
+ "reflects the revision now being listed"
+ );
+ });
+});
+
+acceptance("History Modal - deleting revisions", function (needs) {
+ needs.user();
+ needs.settings({ can_permanently_delete: true });
+ needs.pretender((server, helper) => {
+ server.get("/posts/419/revisions/latest.json", () =>
+ helper.response(revisionResponse)
+ );
+ });
+
+ test("offers to delete all revisions from a listed revision", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("article[data-post-id='419'] .edits button");
+ await click(".history-modal .revision-visibility__trigger");
+
+ assert
+ .dom(".history-modal .destroy-revision")
+ .hasText(i18n("post.revisions.controls.destroy"));
+ });
+});
+
+acceptance("History Modal - unlisted revisions as a user", function (needs) {
+ let unlistedRevisionCount;
+
+ needs.user({ admin: false, moderator: false, staff: false });
+ needs.hooks.beforeEach(() => (unlistedRevisionCount = 1));
+ needs.pretender((server, helper) => {
+ const listedRevision = (request) => ({
+ ...revisionResponse,
+ first_revision: 2,
+ previous_revision: null,
+ next_revision: request.queryParams.include_unlisted ? 3 : null,
+ unlisted: false,
+ unlisted_revision_count: unlistedRevisionCount,
+ });
+
+ server.get("/posts/419/revisions/latest.json", (request) =>
+ helper.response(listedRevision(request))
+ );
+ server.get("/posts/419/revisions/2.json", (request) =>
+ helper.response(listedRevision(request))
+ );
+ server.get("/posts/419/revisions/3.json", () =>
+ helper.response({
+ ...revisionResponse,
+ first_revision: 2,
+ previous_revision: 2,
+ current_revision: 3,
+ last_revision: 3,
+ unlisted: true,
+ unlisted_revision_count: unlistedRevisionCount,
+ })
+ );
+ });
+
+ test("showing all edits", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("article[data-post-id='419'] .edits button");
+
+ assert
+ .dom(".history-modal .revision-visibility__trigger")
+ .doesNotExist("doesn't offer staff actions");
+ assert
+ .dom(".history-modal .next-revision")
+ .isDisabled("skips the unlisted revision");
+
+ await click(".history-modal .show-unlisted-revisions");
+
+ assert
+ .dom(".history-modal .show-unlisted-revisions")
+ .hasAria("checked", "true", "turns the toggle on");
+
+ await click(".history-modal .next-revision");
+
+ assert
+ .dom(".history-modal .revision-details__unlisted")
+ .exists("marks the unlisted revision");
+ });
+
+ test("without unlisted revisions", async function (assert) {
+ unlistedRevisionCount = 0;
+
+ await visit("/t/internationalization-localization/280");
+ await click("article[data-post-id='419'] .edits button");
+
+ assert
+ .dom(".history-modal .show-unlisted-revisions")
+ .doesNotExist("doesn't offer the unlisted toggle");
+ });
+});
diff --git a/lib/guardian/post_revision_guardian.rb b/lib/guardian/post_revision_guardian.rb
index 8988d444443..f481783aebf 100644
--- a/lib/guardian/post_revision_guardian.rb
+++ b/lib/guardian/post_revision_guardian.rb
@@ -21,6 +21,14 @@ module PostRevisionGuardian
is_staff?
end
+ def can_unlist_post_revision?(post_revision)
+ is_staff?
+ end
+
+ def can_relist_post_revision?(post_revision)
+ is_staff?
+ end
+
def can_view_post_version?(post, version)
can_view_hidden_post_revisions? ||
!PostRevision.where(post_id: post.id, hidden: true, number: ..version).exists?
@@ -29,4 +37,8 @@ module PostRevisionGuardian
def can_view_hidden_post_revisions?
is_staff?
end
+
+ def can_navigate_unlisted_post_revisions?
+ is_staff?
+ end
end
diff --git a/lib/post_revisor.rb b/lib/post_revisor.rb
index ea4e38f4547..6979654b17c 100644
--- a/lib/post_revisor.rb
+++ b/lib/post_revisor.rb
@@ -334,6 +334,9 @@ class PostRevisor
@topic.acting_user = @editor
@revised_at = @opts[:revised_at] || Time.now
@last_version_at = @post.last_version_at || Time.now
+ @latest_revision_unlisted =
+ @post.version > 1 &&
+ PostRevision.where(post_id: @post.id, number: @post.version).pick(:unlisted)
if guardian.affected_by_slow_mode?(@topic) && !grace_period_edit? &&
SiteSetting.slow_mode_prevents_editing && !@opts[:bypass_slow_mode]
@@ -485,13 +488,19 @@ class PostRevisor
return true
end
edited_by_another_user? || flagged? || !grace_period_edit? || owner_changed? ||
- force_new_version? || edit_reason_specified?
+ force_new_version? || edit_reason_specified? || latest_revision_unlisted?
end
def edit_reason_specified?
@fields[:edit_reason].present? && @fields[:edit_reason] != @post.edit_reason
end
+ # Folding a new edit into an unlisted revision would also skip it for non-staff.
+ # Read up front because `should_create_new_version?` is re-checked after the bump.
+ def latest_revision_unlisted?
+ @latest_revision_unlisted
+ end
+
def flagged?
@post.is_flagged?
end
diff --git a/spec/lib/guardian/post_revision_guardian_spec.rb b/spec/lib/guardian/post_revision_guardian_spec.rb
index bab2bac471c..dfdf8c9c00d 100644
--- a/spec/lib/guardian/post_revision_guardian_spec.rb
+++ b/spec/lib/guardian/post_revision_guardian_spec.rb
@@ -16,4 +16,32 @@ RSpec.describe Guardian do
expect(Guardian.new(moderator).can_view_post_version?(post, 2)).to eq(true)
end
end
+
+ describe "#can_navigate_unlisted_post_revisions?" do
+ it "only allows staff" do
+ expect(moderator.guardian.can_navigate_unlisted_post_revisions?).to eq(true)
+ expect(user.guardian.can_navigate_unlisted_post_revisions?).to eq(false)
+ expect(Guardian.new.can_navigate_unlisted_post_revisions?).to eq(false)
+ end
+ end
+
+ describe "#can_unlist_post_revision?" do
+ fab!(:post_revision) { Fabricate(:post_revision, post:, number: 3) }
+
+ it "only allows staff" do
+ expect(moderator.guardian.can_unlist_post_revision?(post_revision)).to eq(true)
+ expect(user.guardian.can_unlist_post_revision?(post_revision)).to eq(false)
+ expect(Guardian.new.can_unlist_post_revision?(post_revision)).to eq(false)
+ end
+ end
+
+ describe "#can_relist_post_revision?" do
+ fab!(:post_revision) { Fabricate(:post_revision, post:, number: 3, unlisted: true) }
+
+ it "only allows staff" do
+ expect(moderator.guardian.can_relist_post_revision?(post_revision)).to eq(true)
+ expect(user.guardian.can_relist_post_revision?(post_revision)).to eq(false)
+ expect(Guardian.new.can_relist_post_revision?(post_revision)).to eq(false)
+ end
+ end
end
diff --git a/spec/lib/post_revisor_spec.rb b/spec/lib/post_revisor_spec.rb
index f75b35a5b26..43d9b7f0e83 100644
--- a/spec/lib/post_revisor_spec.rb
+++ b/spec/lib/post_revisor_spec.rb
@@ -726,6 +726,51 @@ describe PostRevisor do
expect(post.revisions.size).to eq(0)
end
+ it "creates a new version instead of folding an edit into an unlisted revision" do
+ SiteSetting.editing_grace_period = 1.minute
+ SiteSetting.editing_grace_period_max_diff = 100
+
+ post_revisor.revise!(
+ post.user,
+ { raw: "updated body" },
+ revised_at: post.updated_at + SiteSetting.editing_grace_period + 1.second,
+ )
+ PostRevision.find_by(post:, number: 2).unlist!
+ post_revisor.revise!(
+ post.user,
+ { raw: "updated body again" },
+ revised_at: post.updated_at + SiteSetting.editing_grace_period + 2.seconds,
+ )
+ post.reload
+
+ expect(post.version).to eq(3)
+ expect(post.public_version).to eq(3)
+ expect(post.revisions.pluck(:number, :unlisted)).to eq([[2, true], [3, false]])
+ end
+
+ it "keeps an unlisted revision when an edit within the grace period reverts it" do
+ SiteSetting.editing_grace_period = 1.minute
+ SiteSetting.editing_grace_period_max_diff = 100
+ original_raw = post.raw
+
+ post_revisor.revise!(
+ post.user,
+ { raw: "updated body" },
+ revised_at: post.updated_at + SiteSetting.editing_grace_period + 1.second,
+ )
+ PostRevision.find_by(post:, number: 2).unlist!
+ post_revisor.revise!(
+ post.user,
+ { raw: original_raw },
+ revised_at: post.updated_at + SiteSetting.editing_grace_period + 2.seconds,
+ )
+ post.reload
+
+ expect(post.raw).to eq(original_raw)
+ expect(post.version).to eq(3)
+ expect(post.revisions.pluck(:number, :unlisted)).to eq([[2, true], [3, false]])
+ end
+
it "does not create a new version for tag-only topic change within grace period when tags unchanged" do
SiteSetting.tagging_enabled = true
SiteSetting.editing_grace_period = 1.minute
diff --git a/spec/models/post_revision_spec.rb b/spec/models/post_revision_spec.rb
index 4cfb8eb8f4e..89d8e31a2d7 100644
--- a/spec/models/post_revision_spec.rb
+++ b/spec/models/post_revision_spec.rb
@@ -30,4 +30,34 @@ RSpec.describe PostRevision do
pr.reload
expect(pr.modifications).to eq({ key: :value })
end
+
+ it "can't be hidden and unlisted at the same time" do
+ post_revision = Fabricate(:post_revision, hidden: true)
+
+ expect { post_revision.unlist! }.to raise_error(ActiveRecord::CheckViolation)
+ end
+
+ it "relists an unlisted revision when hiding it" do
+ post_revision = Fabricate(:post_revision, unlisted: true)
+
+ post_revision.hide!
+
+ expect(post_revision.reload).to have_attributes(hidden: true, unlisted: false)
+ end
+
+ describe ".latest_for" do
+ fab!(:post)
+ fab!(:listed_revision) { Fabricate(:post_revision, post:, number: 2) }
+ fab!(:unlisted_revision) { Fabricate(:post_revision, post:, number: 3, unlisted: true) }
+
+ it "returns the latest listed revision when skipping unlisted ones" do
+ expect(described_class.latest_for(post, Guardian.new)).to eq(listed_revision)
+ end
+
+ it "returns the latest unlisted revision when no listed one is left" do
+ listed_revision.unlist!
+
+ expect(described_class.latest_for(post, Guardian.new)).to eq(unlisted_revision)
+ end
+ end
end
diff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rb
index 458379a7c03..d737de6edad 100644
--- a/spec/requests/posts_controller_spec.rb
+++ b/spec/requests/posts_controller_spec.rb
@@ -3832,6 +3832,36 @@ RSpec.describe PostsController do
end
end
+ context "with an unlisted revision" do
+ fab!(:revised_post) { Fabricate(:post, version: 3) }
+
+ before do
+ Fabricate(:post_revision, post: revised_post, number: 2)
+ Fabricate(:post_revision, post: revised_post, number: 3, unlisted: true)
+ end
+
+ it "steps to it only when unlisted revisions are included" do
+ SiteSetting.edit_history_visible_to_public = true
+
+ get "/posts/#{revised_post.id}/revisions/2.json"
+ expect(response.parsed_body["next_revision"]).to eq(nil)
+
+ get "/posts/#{revised_post.id}/revisions/2.json", params: { include_unlisted: true }
+ expect(response.parsed_body["next_revision"]).to eq(3)
+ end
+
+ it "doesn't grant access to edit history that isn't visible" do
+ SiteSetting.edit_history_visible_to_public = false
+ sign_in(user)
+
+ get "/posts/#{revised_post.id}/revisions/2.json", params: { include_unlisted: true }
+ expect(response.status).to eq(403)
+
+ get "/posts/#{revised_post.id}/revisions/latest.json", params: { include_unlisted: true }
+ expect(response.status).to eq(403)
+ end
+ end
+
context "with a tagged topic" do
let(:tag) { Fabricate(:tag) }
@@ -3851,6 +3881,147 @@ RSpec.describe PostsController do
end
end
+ describe "#latest_revision" do
+ fab!(:post_owner, :user)
+ fab!(:revised_post) { Fabricate(:post, user: post_owner, raw: "Initial version") }
+
+ before do
+ SiteSetting.edit_history_visible_to_public = true
+ SiteSetting.editing_grace_period = 0
+
+ revised_post.revise(post_owner, raw: "Listed version")
+ revised_post.revise(post_owner, raw: "Unlisted version")
+ revised_post.revisions.find_by(number: 3).unlist!
+ end
+
+ it "opens the latest listed revision for non-staff" do
+ get "/posts/#{revised_post.id}/revisions/latest.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to include("current_revision" => 2, "next_revision" => nil)
+ end
+
+ it "opens the latest revision for non-staff who include unlisted revisions" do
+ get "/posts/#{revised_post.id}/revisions/latest.json", params: { include_unlisted: true }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to include("current_revision" => 3, "unlisted" => true)
+ end
+
+ it "opens the latest revision for staff" do
+ sign_in(moderator)
+
+ get "/posts/#{revised_post.id}/revisions/latest.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["current_revision"]).to eq(3)
+ end
+
+ it "falls back to the latest visible revision when no listed revision is left" do
+ revised_post.revisions.find_by(number: 2).unlist!
+ revised_post.revisions.find_by(number: 3).hide!
+
+ get "/posts/#{revised_post.id}/revisions/latest.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to include(
+ "current_revision" => 2,
+ "last_revision" => 2,
+ "unlisted" => true,
+ )
+ end
+
+ it "opens a loaded revision when the latest listed one is older than the loaded history" do
+ (4..102).each do |number|
+ Fabricate(:post_revision, post: revised_post, user: post_owner, number:, unlisted: true)
+ end
+
+ get "/posts/#{revised_post.id}/revisions/latest.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to include("current_revision" => 102, "unlisted" => true)
+ end
+ end
+
+ describe "#hide_revision" do
+ fab!(:revised_post) { Fabricate(:post, version: 2, public_version: 2) }
+ fab!(:post_revision) { Fabricate(:post_revision, post: revised_post, unlisted: true) }
+
+ it "clears the unlisted flag when hiding an unlisted revision" do
+ sign_in(moderator)
+
+ expect { put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/hide" }.to change {
+ revised_post.reload.public_version
+ }.by(-1)
+
+ expect(response.status).to eq(200)
+ expect(post_revision.reload).to have_attributes(hidden: true, unlisted: false)
+ end
+ end
+
+ describe "#unlist_revision" do
+ fab!(:revised_post) { Fabricate(:post, version: 2) }
+ fab!(:post_revision) { Fabricate(:post_revision, post: revised_post) }
+
+ it "only allows staff to unlist a revision" do
+ put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"
+ expect(response.status).to eq(403)
+
+ sign_in(user)
+ put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"
+ expect(response.status).to eq(403)
+
+ expect(post_revision.reload.unlisted).to eq(false)
+ end
+
+ it "unlists the revision" do
+ sign_in(moderator)
+
+ put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"
+
+ expect(response.status).to eq(204)
+ expect(post_revision.reload.unlisted).to eq(true)
+ end
+
+ it "refuses to unlist a hidden revision" do
+ post_revision.hide!
+ sign_in(moderator)
+
+ put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/unlist"
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to contain_exactly(
+ I18n.t("cannot_unlist_hidden_revision"),
+ )
+ expect(post_revision.reload).to have_attributes(hidden: true, unlisted: false)
+ end
+ end
+
+ describe "#relist_revision" do
+ fab!(:revised_post) { Fabricate(:post, version: 2) }
+ fab!(:post_revision) { Fabricate(:post_revision, post: revised_post, unlisted: true) }
+
+ it "only allows staff to relist a revision" do
+ put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/relist"
+ expect(response.status).to eq(403)
+
+ sign_in(user)
+ put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/relist"
+ expect(response.status).to eq(403)
+
+ expect(post_revision.reload.unlisted).to eq(true)
+ end
+
+ it "relists the revision" do
+ sign_in(moderator)
+
+ put "/posts/#{revised_post.id}/revisions/#{post_revision.number}/relist"
+
+ expect(response.status).to eq(204)
+ expect(post_revision.reload.unlisted).to eq(false)
+ end
+ end
+
describe "#permanently_delete_check" do
fab!(:post)
diff --git a/spec/serializers/post_revision_serializer_spec.rb b/spec/serializers/post_revision_serializer_spec.rb
index 5b7d582cf6a..bab72b8a7df 100644
--- a/spec/serializers/post_revision_serializer_spec.rb
+++ b/spec/serializers/post_revision_serializer_spec.rb
@@ -162,6 +162,98 @@ RSpec.describe PostRevisionSerializer do
end
end
+ describe "unlisted revisions" do
+ fab!(:admin)
+ fab!(:post_owner, :user)
+ fab!(:revised_post) { Fabricate(:post, user: post_owner, raw: "First version") }
+
+ before do
+ SiteSetting.editing_grace_period = 0
+
+ revised_post.revise(post_owner, raw: "Second version")
+ revised_post.revise(post_owner, raw: "Unlisted version")
+ revised_post.revise(post_owner, raw: "Fourth version")
+ revised_post.revisions.find_by(number: 3).unlist!
+ end
+
+ def serialize(number, guardian: Guardian.new, **options)
+ described_class.new(
+ revised_post.revisions.find_by(number:),
+ scope: guardian,
+ root: false,
+ **options,
+ ).as_json
+ end
+
+ it "skips unlisted revisions when non-staff navigate" do
+ expect(serialize(2)).to include(
+ first_revision: 2,
+ next_revision: 4,
+ last_revision: 4,
+ current_version: 2,
+ version_count: 4,
+ unlisted_revision_count: 1,
+ )
+ expect(serialize(4)).to include(previous_revision: 2, current_version: 4, version_count: 4)
+ end
+
+ it "diffs each revision against its direct predecessor for every viewer" do
+ expected_diffs = {
+ 2 => ["First version", "Second version"],
+ 3 => ["Second version", "Unlisted version"],
+ 4 => ["Unlisted version", "Fourth version"],
+ }
+ viewers = [
+ { guardian: admin.guardian },
+ { guardian: Guardian.new },
+ { guardian: Guardian.new, include_unlisted: true },
+ ]
+
+ viewers.each do |viewer|
+ expected_diffs.each do |number, (previous_raw, current_raw)|
+ expect(serialize(number, **viewer)[:body_changes][:side_by_side_markdown]).to eq(
+ DiscourseDiff.new(previous_raw, current_raw).side_by_side_markdown,
+ )
+ end
+ end
+ end
+
+ it "lets staff navigate every revision" do
+ expect(serialize(2, guardian: admin.guardian)).to include(next_revision: 3, version_count: 4)
+ end
+
+ it "lets non-staff include unlisted revisions" do
+ expect(serialize(2, include_unlisted: true)).to include(next_revision: 3, version_count: 4)
+ end
+
+ it "keeps suppressing diffs next to a hidden revision while skipping unlisted ones" do
+ revised_post.revise(post_owner, raw: "Fifth version")
+ revised_post.revisions.find_by(number: 4).hide!
+
+ expect(serialize(2)).to include(next_revision: 5)
+ expect(serialize(2)[:body_changes][:side_by_side_markdown]).to eq(
+ DiscourseDiff.new("First version", "Second version").side_by_side_markdown,
+ )
+ expect(serialize(3)).to include(current_hidden: true, body_changes: nil)
+ expect(serialize(5)).to include(
+ previous_revision: 2,
+ previous_hidden: true,
+ body_changes: nil,
+ )
+ end
+
+ it "renders an unlisted revision opened directly" do
+ json = serialize(3)
+
+ expect(json).to include(
+ unlisted: true,
+ current_revision: 3,
+ previous_revision: 2,
+ next_revision: 4,
+ )
+ end
+ end
+
describe "post locale edits" do
it "returns the locale changes when set to nothing" do
post_revision =
diff --git a/spec/services/post_revision/relist_spec.rb b/spec/services/post_revision/relist_spec.rb
new file mode 100644
index 00000000000..e76dca7294d
--- /dev/null
+++ b/spec/services/post_revision/relist_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+RSpec.describe PostRevision::Relist do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:post_id) }
+ it { is_expected.to validate_presence_of(:revision) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:acting_user, :moderator)
+ fab!(:post)
+ fab!(:post_revision) { Fabricate(:post_revision, post:, unlisted: true) }
+
+ let(:params) { { post_id:, revision: } }
+ let(:dependencies) { { guardian: } }
+ let(:guardian) { acting_user.guardian }
+ let(:post_id) { post.id }
+ let(:revision) { post_revision.number }
+
+ context "when contract is invalid" do
+ let(:revision) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when post is not found" do
+ let(:post_id) { 0 }
+
+ it { is_expected.to fail_to_find_a_model(:post) }
+ end
+
+ context "when acting user cannot see the post" do
+ fab!(:private_message_post)
+
+ let(:post_id) { private_message_post.id }
+
+ it { is_expected.to fail_a_policy(:can_see_post) }
+ end
+
+ context "when post is deleted" do
+ before { post.trash! }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when topic is deleted" do
+ before { post.topic.trash! }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when post revision is not found" do
+ let(:revision) { post_revision.number + 1 }
+
+ it { is_expected.to fail_to_find_a_model(:post_revision) }
+ end
+
+ context "when acting user cannot relist the post revision" do
+ fab!(:acting_user, :user)
+
+ it { is_expected.to fail_a_policy(:can_relist_post_revision) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "relists the post revision" do
+ expect { result }.to change { post_revision.reload.unlisted }.from(true).to(false)
+ end
+ end
+ end
+end
diff --git a/spec/services/post_revision/unlist_spec.rb b/spec/services/post_revision/unlist_spec.rb
new file mode 100644
index 00000000000..709849897e5
--- /dev/null
+++ b/spec/services/post_revision/unlist_spec.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+RSpec.describe PostRevision::Unlist do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:post_id) }
+ it { is_expected.to validate_presence_of(:revision) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:acting_user, :moderator)
+ fab!(:post)
+ fab!(:post_revision) { Fabricate(:post_revision, post:) }
+
+ let(:params) { { post_id:, revision: } }
+ let(:dependencies) { { guardian: } }
+ let(:guardian) { acting_user.guardian }
+ let(:post_id) { post.id }
+ let(:revision) { post_revision.number }
+
+ context "when contract is invalid" do
+ let(:revision) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when post is not found" do
+ let(:post_id) { 0 }
+
+ it { is_expected.to fail_to_find_a_model(:post) }
+ end
+
+ context "when acting user cannot see the post" do
+ fab!(:private_message_post)
+
+ let(:post_id) { private_message_post.id }
+
+ it { is_expected.to fail_a_policy(:can_see_post) }
+ end
+
+ context "when post is deleted" do
+ before { post.trash! }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when topic is deleted" do
+ before { post.topic.trash! }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when post revision is not found" do
+ let(:revision) { post_revision.number + 1 }
+
+ it { is_expected.to fail_to_find_a_model(:post_revision) }
+ end
+
+ context "when acting user cannot unlist the post revision" do
+ fab!(:acting_user, :user)
+
+ it { is_expected.to fail_a_policy(:can_unlist_post_revision) }
+ end
+
+ context "when post revision is hidden" do
+ fab!(:hidden_revision) { Fabricate(:post_revision, post:, number: 3, hidden: true) }
+
+ let(:revision) { hidden_revision.number }
+
+ it { is_expected.to fail_a_policy(:post_revision_not_hidden) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "unlists the post revision" do
+ expect { result }.to change { post_revision.reload.unlisted }.from(false).to(true)
+ end
+ end
+ end
+end
diff --git a/spec/system/page_objects/modals/post_history.rb b/spec/system/page_objects/modals/post_history.rb
index 373eb1e6569..2ef081cc89f 100644
--- a/spec/system/page_objects/modals/post_history.rb
+++ b/spec/system/page_objects/modals/post_history.rb
@@ -10,6 +10,11 @@ module PageObjects
self
end
+ def click_next_revision
+ footer.find("button.next-revision").click
+ self
+ end
+
def previous_locale
body.find(".revision__locale .revision-content.--previous")
end
@@ -22,17 +27,41 @@ module PageObjects
revision_numbers.find("strong:nth-child(3)")
end
- def hide_revision
- footer.find("button.hide-revision").click
+ def open_visibility_menu
+ footer.find(".revision-visibility__trigger").click
+ self
+ end
+
+ def choose_visibility(visibility)
+ open_visibility_menu
+ find("#{MODAL_SELECTOR} [data-revision-visibility='#{visibility}']").click
self
end
+ def show_all_edits
+ PageObjects::Components::DToggleSwitch.new(
+ "#{footer_selector} .show-unlisted-revisions",
+ ).toggle
+ self
+ end
+
+ def has_unlisted_marker?
+ body.has_css?(
+ ".revision-details__unlisted",
+ text: I18n.t("js.post.revisions.unlisted.label"),
+ )
+ end
+
+ def has_no_unlisted_marker?
+ body.has_no_css?(".revision-details__unlisted")
+ end
+
def destroy_revisions
- footer.find("button.destroy-revision").click
+ find("#{MODAL_SELECTOR} .destroy-revision").click
end
def has_destroy_revisions_button?
- footer.has_css?("button.destroy-revision")
+ has_css?("#{MODAL_SELECTOR} .destroy-revision")
end
def has_tag_changes?
@@ -51,6 +80,10 @@ module PageObjects
body.has_css?(".body-diff", text: text)
end
+ def has_no_body_diff?(text)
+ body.has_no_css?(".body-diff", text: text)
+ end
+
def previous_tags
body.find(".-tag-revisions .tag-revision__wrapper:first-child")
end
diff --git a/spec/system/permanently_delete_spec.rb b/spec/system/permanently_delete_spec.rb
index a32a1ea9dbf..1cd41b840c5 100644
--- a/spec/system/permanently_delete_spec.rb
+++ b/spec/system/permanently_delete_spec.rb
@@ -106,7 +106,7 @@ describe "Permanently delete" do
topic_page.open_post_history(post_with_revisions)
expect(post_history_modal).to be_open
- post_history_modal.hide_revision
+ post_history_modal.open_visibility_menu
expect(post_history_modal).to have_destroy_revisions_button
post_history_modal.destroy_revisions
diff --git a/spec/system/post_history_spec.rb b/spec/system/post_history_spec.rb
index 07e464f097c..45f97da98e8 100644
--- a/spec/system/post_history_spec.rb
+++ b/spec/system/post_history_spec.rb
@@ -106,3 +106,51 @@ describe "Post history with a hidden revision" do
expect(post_history_modal).to have_body_diff("Latest public version")
end
end
+
+describe "Post history with an unlisted revision" do
+ fab!(:admin)
+ fab!(:post_owner, :user)
+ fab!(:topic) { Fabricate(:topic, user: post_owner) }
+ fab!(:post) { Fabricate(:post, topic: topic, user: post_owner, raw: "Initial public version") }
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+ let(:post_history_modal) { PageObjects::Modals::PostHistory.new }
+
+ before do
+ SiteSetting.editing_grace_period = 0
+
+ post.revise(post_owner, raw: "Second public version")
+ post.revise(post_owner, raw: "Noisy intermediate version")
+ post.revise(post_owner, raw: "Latest public version")
+ end
+
+ it "lets staff unlist a revision" do
+ sign_in(admin)
+ topic_page.visit_topic(topic)
+ find(".post-info.edits").click
+ post_history_modal.click_previous_revision
+
+ expect(post_history_modal).to have_body_diff("Noisy intermediate version")
+ expect(post_history_modal).to have_no_unlisted_marker
+
+ post_history_modal.choose_visibility("unlisted")
+
+ expect(post_history_modal).to have_unlisted_marker
+ end
+
+ it "skips the unlisted revision for users until they show all edits" do
+ post.revisions.find_by(number: 3).unlist!
+
+ topic_page.visit_topic(topic)
+ find(".post-info.edits").click
+ post_history_modal.click_previous_revision
+
+ expect(post_history_modal).to have_body_diff("Second public version")
+ expect(post_history_modal).to have_no_body_diff("Noisy intermediate version")
+
+ post_history_modal.show_all_edits.click_next_revision
+
+ expect(post_history_modal).to have_unlisted_marker
+ expect(post_history_modal).to have_body_diff("Noisy intermediate version")
+ end
+end