Skip to content

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

DEV: Improve quoted post handling and enhance decorator stability (#33154)

Sérgio Saquetim5314b6aa829d
diff --git a/app/assets/javascripts/discourse/app/components/post.gjs b/app/assets/javascripts/discourse/app/components/post.gjs
index 146c5db021c..45b39cd7aa8 100644
--- a/app/assets/javascripts/discourse/app/components/post.gjs
+++ b/app/assets/javascripts/discourse/app/components/post.gjs
@@ -362,6 +362,11 @@ export default class Post extends Component {
)
}}
data-post-number={{@post.post_number}}
+ {{! The post component is wrapped in a `div` and sets the same `id` below in the `article` tag,
+ we need to only set it in the `div` when the post is cloaked.
+ This is not ideal, but the post-stream component sets the `id` for the children to ensure
+ all cloaked items can be referenced and we need to override it }}
+ id={{if @cloaked (concat "post_" @post.post_number)}}
>
{{#unless @cloaked}}
{{#let
diff --git a/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs b/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs
index c2398b5d859..cfc2519f0b2 100644
--- a/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs
+++ b/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs
@@ -6,6 +6,7 @@ import { htmlSafe } from "@ember/template";
import curryComponent from "ember-curry-component";
import DecoratedHtml from "discourse/components/decorated-html";
import { bind } from "discourse/lib/decorators";
+import { isRailsTesting, isTesting } from "discourse/lib/environment";
import { makeArray } from "discourse/lib/helpers";
import decorateLinkCounts from "discourse/lib/post-cooked-html-decorators/link-counts";
import decorateMentions from "discourse/lib/post-cooked-html-decorators/mentions";
@@ -47,48 +48,62 @@ export default class PostCookedHtml extends Component {
[...POST_COOKED_DECORATORS, ...this.extraDecorators].forEach(
(decorator) => {
- if (!this.#decoratorState.has(decorator)) {
- this.#decoratorState.set(decorator, {});
- }
-
- const owner = getOwner(this);
- const decorationCleanup = decorator(element, {
- data: {
- post: this.args.post,
- cooked: this.cooked,
- highlightTerm: this.highlightTerm,
- isIgnored: this.isIgnored,
- ignoredUsers: this.ignoredUsers,
- },
- createDetachedElement: this.#createDetachedElement,
- currentUser: this.currentUser,
- helper,
- renderNestedPostCookedHtml: (
- nestedElement,
- nestedPost,
- extraDecorators
- ) => {
- const nestedArguments = {
- post: nestedPost,
- streamElement: false,
+ try {
+ if (!this.#decoratorState.has(decorator)) {
+ this.#decoratorState.set(decorator, {});
+ }
+
+ const owner = getOwner(this);
+ const decorationCleanup = decorator(element, {
+ data: {
+ post: this.args.post,
+ cooked: this.cooked,
highlightTerm: this.highlightTerm,
- extraDecorators: [
- ...this.extraDecorators,
- ...makeArray(extraDecorators),
- ],
- };
-
- helper.renderGlimmer(
+ isIgnored: this.isIgnored,
+ ignoredUsers: this.ignoredUsers,
+ },
+ createDetachedElement: this.#createDetachedElement,
+ currentUser: this.currentUser,
+ helper,
+ renderNestedPostCookedHtml: (
nestedElement,
- curryComponent(PostCookedHtml, nestedArguments, owner)
- );
- },
- owner,
- state: this.#decoratorState.get(decorator),
- });
-
- if (typeof decorationCleanup === "function") {
- this.#pendingDecoratorCleanup.push(decorationCleanup);
+ nestedPost,
+ extraDecorators,
+ extraArguments
+ ) => {
+ const nestedArguments = {
+ ...extraArguments,
+ post: nestedPost,
+ streamElement: false,
+ highlightTerm: this.highlightTerm,
+ extraDecorators: [
+ ...this.extraDecorators,
+ ...makeArray(extraDecorators),
+ ],
+ };
+
+ helper.renderGlimmer(
+ nestedElement,
+ curryComponent(PostCookedHtml, nestedArguments, owner)
+ );
+ },
+ owner,
+ state: this.#decoratorState.get(decorator),
+ });
+
+ if (typeof decorationCleanup === "function") {
+ this.#pendingDecoratorCleanup.push(decorationCleanup);
+ }
+ } catch (e) {
+ if (isRailsTesting() || isTesting()) {
+ throw e;
+ } else {
+ // in case one of the decorators throws an error we want to surface it to the console but prevent
+ // the application from crashing
+
+ // eslint-disable-next-line no-console
+ console.error(e);
+ }
}
}
);
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js
index 08f7c31b235..89bea0f169d 100644
--- a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js
@@ -1,5 +1,6 @@
import { spinnerHTML } from "discourse/helpers/loading-spinner";
import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
import escape from "discourse/lib/escape";
import highlightHTML from "discourse/lib/highlight-html";
import { iconHTML } from "discourse/lib/icon-library";
@@ -72,7 +73,8 @@ function _updateQuoteElements(aside, desc, context) {
if (
topicNumber &&
postNumber &&
- topicNumber === data.post.topic_id?.toString()
+ topicNumber === data.post.topic_id?.toString() &&
+ data.post.topic
) {
const topicId = data.post.topic_id;
const slug = data.post.topic.slug;
@@ -117,8 +119,13 @@ function _updateQuoteElements(aside, desc, context) {
}
async function _toggleQuote(aside, context) {
- const { createDetachedElement, data, renderNestedPostCookedHtml, state } =
- context;
+ const {
+ createDetachedElement,
+ data,
+ renderNestedPostCookedHtml,
+ state,
+ owner,
+ } = context;
if (state.expanding) {
return;
@@ -155,12 +162,21 @@ async function _toggleQuote(aside, context) {
const postId = parseInt(aside.dataset.post, 10);
try {
- const quotedPost = await ajax(`/posts/by_number/${topicId}/${postId}`);
-
const post = data.post;
+ const quotedPost = owner
+ .lookup("service:store")
+ .createRecord(
+ "post",
+ await ajax(`/posts/by_number/${topicId}/${postId}`)
+ );
+
+ if (quotedPost.topic_id === post?.topic_id) {
+ quotedPost.topic = post.topic;
+ }
+
const quotedPosts = post.quoted || {};
quotedPosts[quotedPost.id] = quotedPost;
- post.set("quoted", quotedPosts);
+ post.quoted = quotedPosts;
const div = createDetachedElement("div");
div.classList.add("expanded-quote");
@@ -177,9 +193,11 @@ async function _toggleQuote(aside, context) {
blockQuote.innerHTML = "";
blockQuote.appendChild(div);
} catch (e) {
- if ([403, 404].includes(e.jqXHR.status)) {
+ if (e.jqXHR && [403, 404].includes(e.jqXHR.status)) {
const icon = iconHTML(e.jqXHR.status === 403 ? "lock" : "trash-can");
blockQuote.innerHTML = `<div class='expanded-quote icon-only'>${icon}</div>`;
+ } else {
+ popupAjaxError(e);
}
}
} else {
diff --git a/app/assets/javascripts/discourse/app/models/post.js b/app/assets/javascripts/discourse/app/models/post.js
index 515136b0a45..fc809d72010 100644
--- a/app/assets/javascripts/discourse/app/models/post.js
+++ b/app/assets/javascripts/discourse/app/models/post.js
@@ -192,12 +192,15 @@ export default class Post extends RestModel {
@trackedPostProperty post_number;
@trackedPostProperty post_type;
@trackedPostProperty primary_group_name;
+ @trackedPostProperty quoted;
@trackedPostProperty read;
@trackedPostProperty reply_count;
@trackedPostProperty reply_to_user;
@trackedPostProperty staff;
@trackedPostProperty staged;
@trackedPostProperty title_is_group;
+ @trackedPostProperty topic;
+ @trackedPostProperty topic_id;
@trackedPostProperty trust_level;
@trackedPostProperty updated_at;
@trackedPostProperty user;
@@ -605,6 +608,10 @@ export default class Post extends RestModel {
skip =
value.username === oldValue.username ||
get(value, "username") === get(oldValue, "username");
+ } else if (key === "topic" && !value && oldValue) {
+ // if `topic` is already set in the new instance we don't want to overwrite it with null, because the old
+ // instance wasn't fully initialized yet.
+ skip = true;
}
if (!skip) {
diff --git a/app/assets/javascripts/discourse/tests/acceptance/topic-test.js b/app/assets/javascripts/discourse/tests/acceptance/topic-test.js
index 4fd11f1cbb5..731f2bae868 100644
--- a/app/assets/javascripts/discourse/tests/acceptance/topic-test.js
+++ b/app/assets/javascripts/discourse/tests/acceptance/topic-test.js
@@ -666,6 +666,12 @@ import { i18n } from "discourse-i18n";
topicFixtures["/t/280/1.json"].post_stream.posts[2]
)
);
+ server.get("/posts/by_number/280/5", () =>
+ helper.response(
+ 200,
+ topicFixtures["/t/280/1.json"].post_stream.posts[4]
+ )
+ );
});
test("The quoted content is toggled correclty", async function (assert) {
@@ -711,6 +717,98 @@ import { i18n } from "discourse-i18n";
)
.hasAttribute("aria-expanded", "false");
});
+
+ // TODO (glimmer-post-stream): this test only works with the Glimmer Post Stream.
+ // When the removing the legacy code we should remove the `if` and run it unconditionally.
+ if (postStreamMode === "enabled") {
+ test("Nesting quoted content works", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ // outer quote
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+
+ assert
+ .dom("#post_7 .quote[data-topic='280'][data-post='5']")
+ .includesText("The problem I see here")
+ .doesNotIncludeText("So you could replace that lookup table");
+
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] > .title .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "true");
+ assert
+ .dom("#post_7 .quote[data-topic='280'][data-post='5']")
+ .includesText("The problem I see here")
+ .includesText("So you could replace that lookup table");
+
+ // nested quote
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+ assert
+ .dom(
+ "#post_7 .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3']"
+ )
+ .includesText(
+ 'So you could replace that lookup table with the "de" one to get German.'
+ )
+ .doesNotIncludeText(
+ "Yep, all strings are going through a lookup table.*"
+ );
+
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "true");
+ assert
+ .dom(
+ "#post_7 .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3']"
+ )
+ .includesText(
+ 'So you could replace that lookup table with the "de" one to get German.'
+ )
+ .includesText(
+ "Yep, all strings are going through a lookup table.*"
+ );
+
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote[data-topic='280'][data-post='3'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+
+ // outer quote
+ await click(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote-controls .quote-toggle"
+ );
+
+ assert
+ .dom(
+ "#post_7 .cooked .quote[data-topic='280'][data-post='5'] .quote-controls .quote-toggle"
+ )
+ .hasAttribute("aria-expanded", "false");
+ });
+ }
}
);
diff --git a/app/assets/javascripts/discourse/tests/fixtures/topic.js b/app/assets/javascripts/discourse/tests/fixtures/topic.js
index eb38516ae71..e0ce9c068e1 100644
--- a/app/assets/javascripts/discourse/tests/fixtures/topic.js
+++ b/app/assets/javascripts/discourse/tests/fixtures/topic.js
@@ -874,7 +874,7 @@ export default {
uploaded_avatar_id: 5253,
created_at: "2013-02-07T14:08:17.493Z",
cooked:
- '<p>Looks interesting, I\'ll take a peek.</p>\n\n<p>As said on dev, the best tool I can see in terms of giving translators a proper interface <em>and</em> quality control would be something like <a href="http://translate.wordpress.org/projects/bbpress/dev" rel="nofollow">GlotPress</a>. It\'s based on the PO messages format (is that somehow related to ICU?) but looks pretty great.</p>\n\n<p><aside class="quote" data-post="6" data-topic="280"><div class="title">\n<div class="quote-controls"></div>\n<img width="20" height="20" src="/user_avatar/meta.discourse.org/sam/40/5243.png" class="avatar">sam said:</div>\n<blockquote><p>fuzzy matching for localization</p></blockquote></aside></p>\n\n<p>I\'m not familiar with the term in this context, you mean keeping the English version in the code base (instead of a generic code like <code>message_error_nametooshort</code> ?)</p>',
+ '<aside class="quote" data-post="5" data-topic="280"><div class="title">\n<div class="quote-controls"></div>\n<img width="20" height="20" src="/user_avatar/meta.discourse.org/sam/40/5243.png" class="avatar">pekka said:</div>\n<blockquote><p>The problem I see here</p></blockquote></aside><p>Looks interesting, I\'ll take a peek.</p>\n\n<p>As said on dev, the best tool I can see in terms of giving translators a proper interface <em>and</em> quality control would be something like <a href="http://translate.wordpress.org/projects/bbpress/dev" rel="nofollow">GlotPress</a>. It\'s based on the PO messages format (is that somehow related to ICU?) but looks pretty great.</p>\n\n<p><aside class="quote" data-post="6" data-topic="280"><div class="title">\n<div class="quote-controls"></div>\n<img width="20" height="20" src="/user_avatar/meta.discourse.org/sam/40/5243.png" class="avatar">sam said:</div>\n<blockquote><p>fuzzy matching for localization</p></blockquote></aside></p>\n\n<p>I\'m not familiar with the term in this context, you mean keeping the English version in the code base (instead of a generic code like <code>message_error_nametooshort</code> ?)</p>',
post_number: 7,
post_type: 1,
updated_at: "2013-02-07T14:12:02.965Z",
diff --git a/spec/system/page_objects/components/post.rb b/spec/system/page_objects/components/post.rb
index 8b9fd1808fd..bfaaacbcfc2 100644
--- a/spec/system/page_objects/components/post.rb
+++ b/spec/system/page_objects/components/post.rb
@@ -8,7 +8,7 @@ module PageObjects
end
def post
- find("#post_#{@post_number}")
+ find(post_id)
end
def reply
@@ -28,6 +28,10 @@ module PageObjects
find("#embedded-posts__bottom--#{@post_number} .load-more-replies").click
end
+ def has_cooked_content?(value)
+ post.find(".contents > .cooked").has_content?(value)
+ end
+
def has_replies?(count: nil)
find("#embedded-posts__bottom--#{@post_number}").has_css?(".reply", count:)
end
@@ -40,6 +44,10 @@ module PageObjects
find("#embedded-posts__bottom--#{@post_number}").has_no_css?(".load-more-replies")
end
+ def visible?
+ has_css?(post_id)
+ end
+
def show_parent_posts
post.find(".reply-to-tab").click
end
@@ -51,6 +59,12 @@ module PageObjects
def has_no_parent_post_content?(content)
find("#embedded-posts__top--#{@post_number}").has_no_content?(content)
end
+
+ private
+
+ def post_id
+ "#post_#{@post_number}"
+ end
end
end
end
diff --git a/spec/system/post_stream_spec.rb b/spec/system/post_stream_spec.rb
index b49d38f18a0..aa7357f04cd 100644
--- a/spec/system/post_stream_spec.rb
+++ b/spec/system/post_stream_spec.rb
@@ -1,46 +1,89 @@
# frozen_string_literal: true
describe "Post stream", type: :system do
- fab!(:topic)
fab!(:user)
- fab!(:posts) { Fabricate.times(20, :post, topic: topic) }
+ fab!(:admin)
- before do
- sign_in(user)
- SiteSetting.glimmer_post_stream_mode = "enabled"
+ %w[enabled disabled].each do |value|
+ before { SiteSetting.glimmer_post_stream_mode = value }
+
+ context "when glimmer_post_stream_mode=#{value}" do
+ context "when posting" do
+ let(:composer) { PageObjects::Components::Composer.new }
+ let(:topic) { Fabricate(:topic, user: user) }
+ let(:op) { Fabricate(:post, topic: topic, user: user) }
+ let(:op_object) { PageObjects::Components::Post.new(op.post_number) }
+
+ before { sign_in(admin) }
+
+ it "can reply to a post and edit the reply" do
+ page.visit "/t/#{op.topic.id}"
+
+ # posting the reply works
+ op_object.reply
+ expect(composer).to be_opened
+ composer.type_content("This is a reply")
+ composer.submit
+
+ reply_object = PageObjects::Components::Post.new(op.post_number + 1)
+
+ expect(reply_object).to be_visible
+ expect(reply_object).to have_cooked_content("This is a reply")
+
+ # editing the reply without reloading the post stream works
+ reply_object.edit
+ expect(composer).to be_opened
+ composer.type_content("This is an edited reply")
+ composer.submit
+
+ expect(reply_object).to be_visible
+ expect(reply_object).to have_cooked_content("This is an edited reply")
+ end
+ end
+ end
end
- it "cloaks posts that are far from the viewport" do
- # Visit the topic page
- visit "/t/#{topic.slug}/#{topic.id}/1"
+ context "when scrolling" do
+ let!(:topic) { Fabricate(:topic) }
+ let!(:posts) { Fabricate.times(20, :post, topic: topic) }
+
+ before do
+ sign_in(user)
+ SiteSetting.glimmer_post_stream_mode = "enabled"
+ end
+
+ it "cloaks posts that are far from the viewport" do
+ # Visit the topic page
+ visit "/t/#{topic.slug}/#{topic.id}/1"
- # Ensure there are visible posts
- expect(page).to have_css(".topic-post")
+ # Ensure there are visible posts
+ expect(page).to have_css(".topic-post")
- post_stream = find(".post-stream")
+ post_stream = find(".post-stream")
- # Ensure the first post is uncloaked
- expect(post_stream).to have_css("> [data-post-number='1']")
- expect(post_stream).to have_no_css("> [data-post-number='1'].post-stream--cloaked")
+ # Ensure the first post is uncloaked
+ expect(post_stream).to have_css("> [data-post-number='1']")
+ expect(post_stream).to have_no_css("> [data-post-number='1'].post-stream--cloaked")
- # Check that some posts are cloaked (not all posts should be fully rendered at once)
- # The posts that are far from the viewport should have the "post-stream--cloaked" class
- expect(post_stream).to have_css(".post-stream--cloaked")
+ # Check that some posts are cloaked (not all posts should be fully rendered at once)
+ # The posts that are far from the viewport should have the "post-stream--cloaked" class
+ expect(post_stream).to have_css(".post-stream--cloaked")
- # Get the number of the last post
- last_post_number = topic.highest_post_number
+ # Get the number of the last post
+ last_post_number = topic.highest_post_number
- # Scroll to the bottom of the page to load more posts
- # We use the :end key to scroll to the bottom
- send_keys(:end)
+ # Scroll to the bottom of the page to load more posts
+ # We use the :end key to scroll to the bottom
+ send_keys(:end)
- # Verify that the last post is not cloaked
- expect(post_stream).to have_no_css(
- "> [data-post-number='#{last_post_number}'].post-stream--cloaked",
- )
+ # Verify that the last post is not cloaked
+ expect(post_stream).to have_no_css(
+ "> [data-post-number='#{last_post_number}'].post-stream--cloaked",
+ )
- # Verify that some posts at the top are now cloaked
- # we can check the first post to see if it's cloaked
- expect(post_stream).to have_css("> [data-post-number='1'].post-stream--cloaked")
+ # Verify that some posts at the top are now cloaked
+ # we can check the first post to see if it's cloaked
+ expect(post_stream).to have_css("> [data-post-number='1'].post-stream--cloaked")
+ end
end
end