Skip to content

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

DEV: Introduce state handling for post cooked HTML decorators (#33200)

Sérgio Saquetim4cf4225f3d86
diff --git a/app/assets/javascripts/discourse/app/components/async-content.gjs b/app/assets/javascripts/discourse/app/components/async-content.gjs
index 889e679335c..a1eb38be310 100644
--- a/app/assets/javascripts/discourse/app/components/async-content.gjs
+++ b/app/assets/javascripts/discourse/app/components/async-content.gjs
@@ -61,11 +61,6 @@ export default class AsyncContent extends Component {
return new TrackedAsyncData(value);
}
- get errorMessage() {
- const errorInfo = extractErrorInfo(this.data.error);
- return errorInfo.html ? htmlSafe(errorInfo.message) : errorInfo.message;
- }
-
get errorMode() {
return this.args.errorMode ?? DEFAULT_ERROR_MODE;
}
@@ -115,12 +110,27 @@ export default class AsyncContent extends Component {
{{/if}}
{{else if this.data.isRejected}}
{{#if (has-block "error")}}
- {{yield this.data.error to="error"}}
+ {{yield
+ this.data.error
+ (component AsyncContentInlineError error=this.data.error)
+ to="error"
+ }}
{{else if (eq this.errorMode "flash")}}
- <FlashMessage role="alert" @flash={{this.errorMessage}} @type="error" />
+ <AsyncContentInlineError @error={{this.data.error}} />
{{else if (eq this.errorMode "popup")}}
{{popupAjaxError this.data.error}}
{{/if}}
{{/if}}
</template>
}
+
+class AsyncContentInlineError extends Component {
+ get errorMessage() {
+ const errorInfo = extractErrorInfo(this.args.error);
+ return errorInfo.html ? htmlSafe(errorInfo.message) : errorInfo.message;
+ }
+
+ <template>
+ <FlashMessage role="alert" @flash={{this.errorMessage}} @type="error" />
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/decorated-html.gjs b/app/assets/javascripts/discourse/app/components/decorated-html.gjs
index 4ca7b8fc3b7..dc027ca0cc3 100644
--- a/app/assets/javascripts/discourse/app/components/decorated-html.gjs
+++ b/app/assets/javascripts/discourse/app/components/decorated-html.gjs
@@ -57,9 +57,15 @@ export default class DecoratedHtml extends Component {
{{~this.decoratedContent~}}
{{~#each this.renderGlimmerInfos as |info|~}}
- {{~#in-element info.element insertBefore=null~}}
- <info.component @data={{info.data}} />
- {{~/in-element~}}
+ {{~#if info.append}}
+ {{~#in-element info.element insertBefore=null~}}
+ <info.component @data={{info.data}} />
+ {{~/in-element~}}
+ {{~else}}
+ {{~#in-element info.element~}}
+ <info.component @data={{info.data}} />
+ {{~/in-element~}}
+ {{~/if}}
{{~/each~}}
</template>
}
@@ -75,7 +81,7 @@ class DecorateHtmlHelper {
this.#context = context;
}
- renderGlimmer(targetElement, component, data) {
+ renderGlimmer(targetElement, component, data, opts = {}) {
if (!(targetElement instanceof Element)) {
deprecated(
"Invalid `targetElement` passed to `helper.renderGlimmer` while using `api.decorateCookedElement` with the Glimmer Post Stream. `targetElement` must be a valid HTML element. This call has been ignored to prevent errors.",
@@ -98,6 +104,7 @@ class DecorateHtmlHelper {
element: targetElement,
component,
data,
+ append: opts.append ?? true,
};
this.#renderGlimmerInfos.push(info);
}
diff --git a/app/assets/javascripts/discourse/app/components/post.gjs b/app/assets/javascripts/discourse/app/components/post.gjs
index 45b39cd7aa8..90356b5e320 100644
--- a/app/assets/javascripts/discourse/app/components/post.gjs
+++ b/app/assets/javascripts/discourse/app/components/post.gjs
@@ -5,7 +5,7 @@ import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
import { service } from "@ember/service";
-import { TrackedArray } from "@ember-compat/tracked-built-ins";
+import { TrackedArray, TrackedMap } from "@ember-compat/tracked-built-ins";
import { TrackedAsyncData } from "ember-async-data";
import { and, eq, not, or } from "truth-helpers";
import DButton from "discourse/components/d-button";
@@ -48,6 +48,8 @@ export default class Post extends Component {
@tracked repliesAbove;
@tracked repliesBelow = new TrackedArray();
+ decoratorState = new TrackedMap();
+
get additionalClasses() {
return applyValueTransformer("post-class", [], {
post: this.args.post,
@@ -375,6 +377,7 @@ export default class Post extends Component {
actions=(hash
updateTopicPageQueryParams=@updateTopicPageQueryParams
)
+ decoratorState=this.decoratorState
topicPageQueryParams=@topicPageQueryParams
)
as |postOutletArgs|
@@ -470,6 +473,7 @@ export default class Post extends Component {
<PostCookedHtml
@post={{@post}}
@highlightTerm={{@highlightTerm}}
+ @decoratorState={{this.decoratorState}}
/>
</PluginOutlet>
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 cfc2519f0b2..2ffbea0696a 100644
--- a/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs
+++ b/app/assets/javascripts/discourse/app/components/post/cooked-html.gjs
@@ -3,6 +3,7 @@ import { tracked } from "@glimmer/tracking";
import { getOwner } from "@ember/owner";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
+import { TrackedMap } from "@ember-compat/tracked-built-ins";
import curryComponent from "ember-curry-component";
import DecoratedHtml from "discourse/components/decorated-html";
import { bind } from "discourse/lib/decorators";
@@ -30,8 +31,8 @@ export default class PostCookedHtml extends Component {
@service currentUser;
@tracked highlighted = false;
- #decoratorState = new WeakMap();
#pendingDecoratorCleanup = [];
+ #decoratorState = this.args.decoratorState || new TrackedMap();
willDestroy() {
super.willDestroy(...arguments);
@@ -49,11 +50,39 @@ export default class PostCookedHtml extends Component {
[...POST_COOKED_DECORATORS, ...this.extraDecorators].forEach(
(decorator) => {
try {
- if (!this.#decoratorState.has(decorator)) {
- this.#decoratorState.set(decorator, {});
+ let decoratorState;
+ if (this.#decoratorState.has(decorator)) {
+ decoratorState = this.#decoratorState.get(decorator);
+ } else {
+ decoratorState = new TrackedMap();
+ this.#decoratorState.set(decorator, decoratorState);
}
const owner = getOwner(this);
+ const renderNestedPostCookedHtml = (
+ nestedElement,
+ nestedPost,
+ extraDecorators,
+ extraArguments
+ ) => {
+ const nestedArguments = {
+ ...extraArguments,
+ post: nestedPost,
+ decoratorState,
+ streamElement: false,
+ highlightTerm: this.highlightTerm,
+ extraDecorators: [
+ ...this.extraDecorators,
+ ...makeArray(extraDecorators),
+ ],
+ };
+
+ helper.renderGlimmer(
+ nestedElement,
+ curryComponent(PostCookedHtml, nestedArguments, owner)
+ );
+ };
+
const decorationCleanup = decorator(element, {
data: {
post: this.args.post,
@@ -62,33 +91,19 @@ export default class PostCookedHtml extends Component {
isIgnored: this.isIgnored,
ignoredUsers: this.ignoredUsers,
},
+ decoratorState,
+ cooked: this.cooked,
createDetachedElement: this.#createDetachedElement,
currentUser: this.currentUser,
+ extraDecorators: this.extraDecorators,
helper,
- renderNestedPostCookedHtml: (
- nestedElement,
- 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)
- );
- },
+ highlightTerm: this.highlightTerm,
+ ignoredUsers: this.ignoredUsers,
+ isIgnored: this.isIgnored,
owner,
- state: this.#decoratorState.get(decorator),
+ post: this.args.post,
+ renderGlimmer: helper.renderGlimmer,
+ renderNestedPostCookedHtml,
});
if (typeof decorationCleanup === "function") {
diff --git a/app/assets/javascripts/discourse/app/components/post/quoted-content.gjs b/app/assets/javascripts/discourse/app/components/post/quoted-content.gjs
new file mode 100644
index 00000000000..9be9d5f744a
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post/quoted-content.gjs
@@ -0,0 +1,282 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { modifier as modifierFn } from "ember-modifier";
+import { eq, or } from "truth-helpers";
+import AsyncContent from "discourse/components/async-content";
+import DButton from "discourse/components/d-button";
+import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
+import element from "discourse/helpers/element";
+import elementClass from "discourse/helpers/element-class";
+import { ajax } from "discourse/lib/ajax";
+import { makeArray } from "discourse/lib/helpers";
+import highlightHTML from "discourse/lib/highlight-html";
+import { postUrl } from "discourse/lib/utilities";
+import PostCookedHtml from "./cooked-html";
+
+export default class PostQuotedContent extends Component {
+ @service store;
+
+ @tracked
+ expanded =
+ this.args.decoratorState?.get(this.stateExpandedId) ??
+ this.args.expanded ??
+ false;
+
+ applyWrapperDataAttributes = modifierFn((_, [target], data) => {
+ const attributes = Object.entries(data);
+ if (!target || attributes.length === 0) {
+ return null;
+ }
+ const originalValues = {};
+ attributes.forEach(([key, value]) => {
+ originalValues[key] = target.dataset[key];
+ target.dataset[key] = value;
+ });
+ return () => {
+ // restore the original values
+ Object.entries(originalValues).forEach(([key, value]) => {
+ if (value === undefined) {
+ delete target.dataset[key];
+ } else {
+ target.dataset[key] = value;
+ }
+ });
+ };
+ });
+
+ #quotedPost = this.args.decoratorState?.get(this.statePostId);
+
+ #highlightOriginalText = (cookedElement) => {
+ if (!this.expanded) {
+ return;
+ }
+ // to highlight the quoted text inside the original post content
+ highlightHTML(cookedElement, this.args.originalText, {
+ matchCase: true,
+ });
+ };
+
+ get extraDecorators() {
+ return [
+ ...makeArray(this.args.extraDecorators),
+ this.#highlightOriginalText,
+ ];
+ }
+
+ get isQuotedPostIgnored() {
+ return this.args.ignoredUsers?.includes(this.args.quotedUsername);
+ }
+
+ get navigateToPostIcon() {
+ if (!this.args.post) {
+ return "arrow-down";
+ }
+ return this.args.post.post_number < this.args.quotedPostNumber
+ ? "arrow-down"
+ : "arrow-up";
+ }
+
+ get quotedPostUrl() {
+ const { quotedTopicId, post, quotedPostNumber } = this.args;
+ if (quotedTopicId !== post?.topic?.id) {
+ return null;
+ }
+
+ const slug = post?.topic?.slug;
+ if (quotedPostNumber && slug) {
+ return postUrl(slug, quotedTopicId, quotedPostNumber);
+ }
+ return null;
+ }
+
+ get shouldDisplayNavigateToPostButton() {
+ return this.quotedPostUrl && !this.isQuotedPostIgnored;
+ }
+
+ get shouldDisplayToggleButton() {
+ return this.args.id && !this.args.fullQuote && !this.isQuotedPostIgnored;
+ }
+
+ get stateExpandedId() {
+ return `${this.args.id}--expanded`;
+ }
+
+ get statePostId() {
+ return `${this.args.id}--post`;
+ }
+
+ get toggleIcon() {
+ return this.expanded ? "chevron-up" : "chevron-down";
+ }
+
+ get OptionalWrapperComponent() {
+ return this.args.wrapperElement ? element("") : element("aside");
+ }
+
+ @action
+ async loadQuotedPost({ topicNumber, postNumber }) {
+ if (
+ this.#quotedPost?.topic_id === topicNumber &&
+ this.#quotedPost?.post_number === postNumber
+ ) {
+ return this.#quotedPost;
+ }
+ const url = `/posts/by_number/${topicNumber}/${postNumber}`;
+ const post = this.store.createRecord(
+ "post",
+ await ajax(url, {
+ ignoreUnsent: false,
+ })
+ );
+ if (post.topic_id === this.args.post?.topic_id) {
+ post.topic = this.args.post.topic;
+ }
+ this.#quotedPost = post;
+ this.args.decoratorState?.set(this.statePostId, post);
+ return post;
+ }
+
+ @action
+ onClickTitle(event) {
+ if (event.target.closest("a") || event.target.closest(".quote-controls")) {
+ return;
+ }
+ this.toggleExpanded();
+ }
+
+ @action
+ toggleExpanded() {
+ this.expanded = !this.expanded;
+ this.args.decoratorState?.set(this.stateExpandedId, this.expanded);
+ }
+
+ <template>
+ {{! template-lint-disable no-unnecessary-concat }}
+ <this.OptionalWrapperComponent
+ ...attributes
+ class={{concatClass
+ "quote"
+ (if @quotedPostNotFound "quote-post-not-found")
+ (if this.isQuotedPostIgnored "ignored-user")
+ }}
+ {{! forced quotes in the data-attributes below to cast the boolean values to string }}
+ data-expanded="{{this.expanded}}"
+ data-full="{{@fullQuote}}"
+ data-post={{@quotedPostNumber}}
+ data-topic={{@quotedTopicId}}
+ data-username={{@quotedUsername}}
+ >
+ {{#if @wrapperElement}}
+ {{! `this.OptionalWrapperComponent` can be empty to render only the children while decorating cooked content.
+ we need to handle the attributtes below in the existing wrapper received as @wrapperElement in this case }}
+ {{elementClass
+ (if this.isQuotedPostIgnored "ignored-user")
+ target=@wrapperElement
+ }}
+ {{/if}}
+ <div
+ class="title"
+ data-has-quote-controls={{or
+ this.shouldDisplayToggleButton
+ this.shouldDisplayNavigateToPostButton
+ }}
+ data-can-toggle-quote={{this.shouldDisplayToggleButton}}
+ {{(if
+ this.shouldDisplayToggleButton (modifier on "click" this.onClickTitle)
+ )}}
+ {{(if
+ @wrapperElement
+ (modifier
+ this.applyWrapperDataAttributes
+ @wrapperElement
+ expanded=this.expanded
+ )
+ )}}
+ >
+ {{~#if (has-block "title")~}}
+ {{~yield to="title"~}}
+ {{~else~}}
+ {{~#if @quotedPostNotFound~}}
+ {{~@quotedUsername~}}
+ {{~else~}}
+ {{~@title~}}
+ {{~/if~}}
+ {{~/if~}}
+ <div class="quote-controls">
+ {{~#if this.shouldDisplayToggleButton~}}
+ <DButton
+ class="btn-flat quote-toggle"
+ @action={{this.toggleExpanded}}
+ @ariaControls={{@id}}
+ @ariaExpanded={{this.expanded}}
+ @title="post.expand_collapse"
+ >
+ {{! rendering the icon in the block instead of using the parameter `@icon` prevents DButton from adding
+ extra whitespace that will interfere with the text captured when quoting a quoted content }}
+ {{~icon this.toggleIcon~}}
+ </DButton>
+ {{~/if~}}
+ {{~#if this.shouldDisplayNavigateToPostButton~}}
+ <DButton
+ class="btn-flat back"
+ @href={{this.quotedPostUrl}}
+ @title="post.follow_quote"
+ >
+ {{! rendering the icon in the block instead of using the parameter `@icon` prevents DButton from adding
+ extra whitespace that will interfere with the text captured when quoting a quoted content }}
+ {{~icon this.navigateToPostIcon~}}
+ </DButton>
+ {{~/if~}}
+ </div>
+ </div>
+ <blockquote id={{@id}}>
+ {{~#unless this.isQuotedPostIgnored~}}
+ {{~#if this.expanded~}}
+ <AsyncContent
+ @asyncData={{this.loadQuotedPost}}
+ @context={{hash
+ topicNumber=@quotedTopicId
+ postNumber=@quotedPostNumber
+ cachedPost=@quotedPost
+ }}
+ >
+ <:content as |expandedPost|>
+ <div class="expanded-quote" data-post-id={{expandedPost.id}}>
+ <PostCookedHtml
+ @post={{expandedPost}}
+ @decoratorState={{@decoratorState}}
+ @extraDecorators={{this.extraDecorators}}
+ @highlightTerm={{@highlightTerm}}
+ @streamElement={{false}}
+ />
+ </div>
+ </:content>
+ <:error as |error AsyncContentInlineErrorMessage|>
+ {{~#if (eq error.jqXHR.status 403)~}}
+ <div class="quote-error expanded-quote icon-only">
+ {{~icon "lock"~}}
+ </div>
+ {{~else if (eq error.jqXHR.status 404)~}}
+ <div class="quote-error expanded-quote icon-only">
+ {{~icon "trash-can"~}}
+ </div>
+ {{~else~}}
+ <div class="quote-error expanded-quote">
+ <AsyncContentInlineErrorMessage />
+ </div>
+ {{~/if~}}
+ </:error>
+ </AsyncContent>
+ {{~else~}}
+ {{~@collapsedContent~}}
+ {{~/if~}}
+ {{~/unless~}}
+ </blockquote>
+ </this.OptionalWrapperComponent>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/helpers/element-class.js b/app/assets/javascripts/discourse/app/helpers/element-class.js
new file mode 100644
index 00000000000..8b4c7297430
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/helpers/element-class.js
@@ -0,0 +1,18 @@
+import Helper from "@ember/component/helper";
+import { service } from "@ember/service";
+
+export default class ElementClass extends Helper {
+ @service elementClasses;
+
+ compute([...classes], { target }) {
+ if (!target) {
+ return;
+ }
+
+ this.elementClasses.registerClasses(
+ this,
+ target,
+ classes.flatMap((c) => c?.split(" ")).filter(Boolean)
+ );
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/helpers/element.gjs b/app/assets/javascripts/discourse/app/helpers/element.gjs
index 08d46a1d00a..75d22f5cb30 100644
--- a/app/assets/javascripts/discourse/app/helpers/element.gjs
+++ b/app/assets/javascripts/discourse/app/helpers/element.gjs
@@ -22,6 +22,9 @@ const shortcuts = {
td: <template>
<td ...attributes>{{yield}}</td>
</template>,
+ aside: <template>
+ <aside ...attributes>{{yield}}</aside>
+ </template>,
};
/**
diff --git a/app/assets/javascripts/discourse/app/lib/plugin-api.gjs b/app/assets/javascripts/discourse/app/lib/plugin-api.gjs
index 06e29fd76c7..0518fc68a29 100644
--- a/app/assets/javascripts/discourse/app/lib/plugin-api.gjs
+++ b/app/assets/javascripts/discourse/app/lib/plugin-api.gjs
@@ -482,7 +482,7 @@ class PluginApi {
* initialize() {
* withPluginApi("1.33.0", (api) => {
* api.addValueTransformerName("my-unique-transformer-name");
- * }),
+ * });
* },
* };
*
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/link-counts.js b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/link-counts.js
index 8df8b5ba923..30a8e8fdb3d 100644
--- a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/link-counts.js
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/link-counts.js
@@ -3,9 +3,9 @@ import { number } from "discourse/lib/formatter";
import { i18n } from "discourse-i18n";
export default function (element, context) {
- const { data } = context;
+ const { post } = context;
- const linkCounts = data.post.link_counts;
+ const linkCounts = post.link_counts;
if (!linkCounts?.length) {
return;
}
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/mentions.gjs b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/mentions.gjs
index 220370155eb..98fe85401b3 100644
--- a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/mentions.gjs
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/mentions.gjs
@@ -9,31 +9,25 @@ const CookedUserStatusMessage = <template>
</template>;
export default function (element, context) {
- const {
- data: { post },
- state,
- owner,
- helper,
- } = context;
-
- state.extractedMentions = _extractMentions(element, post);
+ const { post, owner, helper } = context;
+ const extractedMentions = extractMentions(element, post);
const userStatusService = owner.lookup("service:user-status");
- const _updateUserStatus = (updatedUser) => {
- state.extractedMentions
+ const updateUserStatus = (updatedUser) => {
+ extractedMentions
.filter(({ user }) => updatedUser.id === user?.id)
.forEach(({ mentions, user }) => {
- _renderUserStatusOnMentions(mentions, user, helper);
+ renderUserStatusOnMentions(mentions, user, helper);
});
};
- state.extractedMentions.forEach(({ mentions, user }) => {
+ extractedMentions.forEach(({ mentions, user }) => {
if (userStatusService.isEnabled) {
user.statusManager?.trackStatus?.();
- user.on?.("status-changed", element, _updateUserStatus);
+ user.on?.("status-changed", element, updateUserStatus);
- _renderUserStatusOnMentions(mentions, user, helper);
+ renderUserStatusOnMentions(mentions, user, helper);
}
const classes = applyValueTransformer("mentions-class", [], {
@@ -48,17 +42,15 @@ export default function (element, context) {
// cleanup code
return () => {
if (userStatusService.isEnabled) {
- state.extractedMentions.forEach(({ user }) => {
+ extractedMentions.forEach(({ user }) => {
user.statusManager?.stopTrackingStatus?.();
- user.off?.("status-changed", element, _updateUserStatus);
+ user.off?.("status-changed", element, updateUserStatus);
});
}
-
- state.extractedMentions = [];
};
}
-function _renderUserStatusOnMentions(mentions, user, helper) {
+function renderUserStatusOnMentions(mentions, user, helper) {
mentions.forEach((mention) => {
let wrapper = mention.querySelector(".user-status-message-wrapper");
@@ -79,7 +71,7 @@ function _renderUserStatusOnMentions(mentions, user, helper) {
});
}
-function _extractMentions(element, post) {
+function extractMentions(element, post) {
return (
post?.mentioned_users?.map((user) => {
const href = getURL(`/u/${user.username.toLowerCase()}`);
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.gjs b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.gjs
new file mode 100644
index 00000000000..e6cd4a2689b
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.gjs
@@ -0,0 +1,76 @@
+import { htmlSafe } from "@ember/template";
+import curryComponent from "ember-curry-component";
+import PostQuotedContent from "discourse/components/post/quoted-content";
+
+export default function quoteControls(element, context) {
+ // Extract required properties from context
+ const { post, highlightTerm, ignoredUsers, decoratorState, owner, helper } =
+ context;
+
+ // Find all quote blocks in the element
+ const quotes = element.querySelectorAll("aside.quote");
+
+ if (quotes.length === 0) {
+ return;
+ }
+
+ // Process each quote block
+ quotes.forEach((aside, index) => {
+ // Extract quote metadata from HTML dataset
+ const {
+ post: quotedPostRaw,
+ topic: topicRaw,
+ username,
+ expanded,
+ full,
+ } = aside.dataset;
+
+ if (!quotedPostRaw) {
+ return;
+ }
+
+ // Parse quoted post/topic IDs
+ const quotedTopicId = parseInt(topicRaw || post.topic_id, 10);
+ const quotedPostNumber = parseInt(quotedPostRaw, 10);
+
+ // Extract and sanitize quote title
+ const titleEl = aside.querySelector(".title");
+
+ let title;
+ if (titleEl) {
+ // Remove existing quote controls if present
+ titleEl.querySelector(".quote-controls")?.remove();
+ title = htmlSafe(titleEl.innerHTML);
+ }
+
+ // Get quote content
+ const blockquote = aside.querySelector("blockquote");
+
+ // Build props for PostQuotedContent component
+ const componentProps = {
+ collapsedContent: htmlSafe(blockquote?.innerHTML),
+ decoratorState,
+ expanded: expanded === "true",
+ fullQuote: full === "true",
+ highlightTerm,
+ id: `quote-id-${quotedTopicId}-${quotedPostNumber}-${index}`,
+ ignoredUsers,
+ originalText: blockquote?.textContent?.trim(),
+ post,
+ quotedPostNotFound: aside.classList.contains("quote-post-not-found"),
+ quotedPostNumber,
+ quotedTopicId,
+ title,
+ username,
+ wrapperElement: aside,
+ };
+
+ // Render the PostQuotedContent component in place of original quote
+ helper.renderGlimmer(
+ aside,
+ curryComponent(PostQuotedContent, componentProps, owner),
+ null,
+ { append: false }
+ );
+ });
+}
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
deleted file mode 100644
index 89bea0f169d..00000000000
--- a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/quote-controls.js
+++ /dev/null
@@ -1,210 +0,0 @@
-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";
-import { postUrl } from "discourse/lib/utilities";
-import { i18n } from "discourse-i18n";
-
-// TODO (glimmer-post-stream): investigate whether all this complex logic can be replaced with a proper Glimmer component
-export default function (element, context) {
- const { state } = context;
-
- const quotes = element.querySelectorAll("aside.quote");
- if (quotes.length === 0) {
- return;
- }
-
- state.originalQuoteContents = new Map();
-
- quotes.forEach((aside, index) => {
- if (aside.dataset.post) {
- const quoteId = `quote-id-${aside.dataset.topic}-${aside.dataset.post}-${index}`;
-
- const blockquote = aside.querySelector("blockquote");
- if (blockquote) {
- blockquote.id = quoteId;
- }
-
- _updateQuoteElements(aside, "chevron-down", context);
- const title = aside.querySelector(".title");
-
- if (!title) {
- return;
- }
-
- // If post/topic is not found then display username, skip controls
- if (aside.classList.contains("quote-post-not-found")) {
- if (aside.dataset.username) {
- title.innerHTML = escape(aside.dataset.username);
- } else {
- title.remove();
- }
-
- return;
- }
-
- // Unless it's a full quote, allow click to expand
- if (!aside.dataset.full && !title.dataset.hasQuoteControls) {
- title.addEventListener("click", (e) => {
- if (e.target.closest("a")) {
- return true;
- }
-
- _toggleQuote(aside, context);
- });
-
- title.dataset.hasQuoteControls = true;
- }
- }
- });
-}
-
-function _updateQuoteElements(aside, desc, context) {
- const { data } = context;
-
- const quoteTitle = i18n("post.follow_quote");
- const postNumber = aside.dataset.post;
- const topicNumber = aside.dataset.topic;
-
- // If we have a post reference
- let navLink = "";
- if (
- topicNumber &&
- postNumber &&
- topicNumber === data.post.topic_id?.toString() &&
- data.post.topic
- ) {
- const topicId = data.post.topic_id;
- const slug = data.post.topic.slug;
-
- const url = postUrl(slug, topicId, postNumber);
- const icon = iconHTML("arrow-up");
-
- navLink = `<a href='${url}' title='${quoteTitle}' class='btn-flat back'>${icon}</a>`;
- }
-
- // Only add the expand/contract control if it's not a full post
- const titleElement = aside.querySelector(".title");
- let expandContract = "";
-
- if (!aside.dataset.full) {
- const icon = iconHTML(desc, { title: "post.expand_collapse" });
- const quoteId = aside.querySelector("blockquote")?.id;
-
- if (quoteId) {
- const isExpanded = aside.dataset.expanded === "true";
- expandContract = `<button aria-controls="${quoteId}" aria-expanded="${isExpanded}" class="quote-toggle btn-flat">${icon}</button>`;
-
- if (titleElement) {
- titleElement.style.cursor = "pointer";
- }
- }
- }
-
- if (data.ignoredUsers?.length && titleElement) {
- const username = titleElement.innerText.trim().slice(0, -1);
-
- if (username.length > 0 && data.ignoredUsers.includes(username)) {
- aside.querySelectorAll("p").forEach((el) => el.remove());
- aside.classList.add("ignored-user");
- }
- }
-
- const quoteControls = aside.querySelector(".quote-controls");
- if (quoteControls) {
- quoteControls.innerHTML = expandContract + navLink;
- }
-}
-
-async function _toggleQuote(aside, context) {
- const {
- createDetachedElement,
- data,
- renderNestedPostCookedHtml,
- state,
- owner,
- } = context;
-
- if (state.expanding) {
- return;
- }
-
- state.expanding = true;
- const blockQuote = aside.querySelector("blockquote");
-
- if (!blockQuote) {
- return;
- }
-
- if (aside.dataset.expanded) {
- delete aside.dataset.expanded;
- } else {
- aside.dataset.expanded = true;
- }
-
- const quoteId = blockQuote.id;
-
- if (aside.dataset.expanded) {
- _updateQuoteElements(aside, "chevron-up", context);
-
- // Show expanded quote
- state.originalQuoteContents.set(quoteId, blockQuote.innerHTML);
-
- const originalText =
- blockQuote.textContent.trim() ||
- data.post.cooked.querySelector("blockquote").textContent.trim();
-
- blockQuote.innerHTML = spinnerHTML;
-
- const topicId = parseInt(aside.dataset.topic || data.post.topic_id, 10);
- const postId = parseInt(aside.dataset.post, 10);
-
- try {
- 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.quoted = quotedPosts;
-
- const div = createDetachedElement("div");
- div.classList.add("expanded-quote");
- div.dataset.postId = quotedPost.id;
-
- // inception
- renderNestedPostCookedHtml(div, quotedPost, (element) =>
- // to highlight the quoted text inside the original post content
- highlightHTML(element, originalText, {
- matchCase: true,
- })
- );
-
- blockQuote.innerHTML = "";
- blockQuote.appendChild(div);
- } catch (e) {
- 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 {
- // Hide expanded quote
- _updateQuoteElements(aside, "chevron-down", context);
- blockQuote.innerHTML = state.originalQuoteContents.get(blockQuote.id);
- }
-
- state.expanding = false;
-}
diff --git a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/search-highlight.js b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/search-highlight.js
index 57c3249bea7..a5480488ed3 100644
--- a/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/search-highlight.js
+++ b/app/assets/javascripts/discourse/app/lib/post-cooked-html-decorators/search-highlight.js
@@ -1,19 +1,9 @@
-import { unhighlightHTML } from "discourse/lib/highlight-html";
import highlightSearch from "discourse/lib/highlight-search";
export default function (element, context) {
- const { data, state } = context;
- const highlight = data.highlightTerm;
+ const { highlightTerm } = context;
- if (highlight && highlight.length > 2) {
- if (state.highlighted) {
- unhighlightHTML(element);
- }
-
- highlightSearch(element, highlight, { defaultClassName: true });
- state.highlighted = true;
- } else if (state.highlighted) {
- unhighlightHTML(element);
- state.highlighted = false;
+ if (highlightTerm && highlightTerm.length > 2) {
+ highlightSearch(element, highlightTerm, { defaultClassName: true });
}
}
diff --git a/app/assets/javascripts/discourse/tests/integration/components/async-content-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/async-content-test.gjs
index ff64496add3..e3917ac5296 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/async-content-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/async-content-test.gjs
@@ -324,7 +324,7 @@ module("Integration | Component | AsyncContent", function (hooks) {
});
module("<:error>", function () {
- test("it displays an inline error dialog when the block is not provided", async function (assert) {
+ test("it displays an inline error when the block is not provided", async function (assert) {
const promise = Promise.reject("error");
await render(
@@ -368,6 +368,27 @@ module("Integration | Component | AsyncContent", function (hooks) {
assert.dom(".error").hasText("error");
});
+ test("it passes the inline error message as a component when the promise is rejected", async function (assert) {
+ const promise = Promise.reject("error");
+
+ await render(
+ <template>
+ <AsyncContent @asyncData={{promise}}>
+ <:error as |error AsyncContentInlineErrorMessage|>
+ <div class="error">
+ <AsyncContentInlineErrorMessage />
+ </div>
+ </:error>
+ </AsyncContent>
+ </template>
+ );
+
+ assert.dom(".error").exists();
+
+ assert.dom(".alert-error").exists();
+ assert.dom(".alert-error").hasText("Sorry, an error has occurred.");
+ });
+
test("it does not display the block when the promise is resolved", async function (assert) {
const promise = Promise.resolve("data");
diff --git a/app/assets/stylesheets/common/base/topic-post.scss b/app/assets/stylesheets/common/base/topic-post.scss
index 1afa40e3501..894a08be038 100644
--- a/app/assets/stylesheets/common/base/topic-post.scss
+++ b/app/assets/stylesheets/common/base/topic-post.scss
@@ -635,6 +635,10 @@ aside.quote {
@include post-aside;
@include unselectable;
+ &[data-can-toggle-quote] {
+ cursor: pointer;
+ }
+
// blockquote is underneath this and has top margin
.avatar {
margin-right: 0.5em;
@@ -681,7 +685,8 @@ aside.quote {
margin-left: 0.3em;
}
- .quote-toggle {
+ .quote-toggle,
+ .back {
padding: 0;
}
}
diff --git a/spec/system/post_stream_spec.rb b/spec/system/post_stream_spec.rb
index 89027235eb1..f96ed99e257 100644
--- a/spec/system/post_stream_spec.rb
+++ b/spec/system/post_stream_spec.rb
@@ -100,5 +100,64 @@ describe "Post stream", type: :system do
# 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
+
+ it "keeps the state of quoted posts after uncloaking them" do
+ first_post = posts[0]
+ second_post = posts[1]
+ second_post.raw =
+ "[quote=\"#{first_post.user.username}, post:1, topic:#{topic.id}\"]\nHello\n[/quote]\n#{first_post.raw}"
+
+ # Rebake the post to process the quote markup
+ second_post.rebake!
+
+ # Visit the topic page
+ visit "/t/#{topic.slug}/#{topic.id}/1"
+
+ post2_selector = "[data-post-number='2']"
+
+ # Find the post-stream container
+ post_stream = find(".post-stream")
+
+ # Verify the second post is initially visible (uncloaked)
+ expect(post_stream).to have_css(post2_selector)
+ expect(post_stream).to have_no_css("#{post2_selector}.post-stream--cloaked")
+
+ # Verify the quote starts collapsed
+ expect(post_stream).to have_css("#{post2_selector} aside.quote[data-expanded='false']")
+
+ # Find the blockquote and verify the initial state
+ blockquote = post_stream.find("#{post2_selector} aside.quote blockquote")
+ expect(blockquote).to have_content("Hello")
+ expect(blockquote).to have_no_content(first_post.raw)
+
+ # Expand the quote by clicking the toggle button
+ post_stream.find(
+ "#{post2_selector} aside.quote[data-expanded='false'] button.quote-toggle",
+ ).click
+ expect(post_stream).to have_css("#{post2_selector} aside.quote[data-expanded='true']")
+
+ # Verify the expanded quote shows full content
+ blockquote = post_stream.find("#{post2_selector} aside.quote blockquote")
+ expect(blockquote).to have_content(first_post.raw)
+
+ # Scroll to bottom to trigger post cloaking
+ send_keys(:end)
+
+ # Verify that the second post gets cloaked and the quote is removed
+ expect(post_stream).to have_css("#{post2_selector}.post-stream--cloaked")
+ expect(post_stream).to have_no_css("#{post2_selector} aside.quote")
+
+ # Scroll back to top
+ send_keys(:home)
+
+ # Verify that the second post becomes visible again
+ expect(post_stream).to have_css(post2_selector)
+ expect(post_stream).to have_no_css("#{post2_selector}.post-stream--cloaked")
+
+ # Verify that the quote maintains an expanded state after uncloaking
+ expect(post_stream).to have_css("#{post2_selector} aside.quote[data-expanded='true']")
+ blockquote = post_stream.find("#{post2_selector} aside.quote blockquote")
+ expect(blockquote).to have_content(first_post.raw)
+ end
end
end