Skip to content

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

FEATURE: Highlight quoted text when expanding or following a quote

Régis Hanol98c97eba1e5c
diff --git a/app/assets/stylesheets/common/base/topic-post.scss b/app/assets/stylesheets/common/base/topic-post.scss
index bb06eb7a0e1..66d42614505 100644
--- a/app/assets/stylesheets/common/base/topic-post.scss
+++ b/app/assets/stylesheets/common/base/topic-post.scss
@@ -1980,6 +1980,11 @@ span.highlighted {
background-color: var(--highlight-bg);
}
+.quote-highlight {
+ background-color: var(--highlight-bg);
+ scroll-margin-top: 3lh;
+}
+
.pausable-animated-image {
position: relative;
display: inline-block;
diff --git a/frontend/discourse/app/components/post-stream.gjs b/frontend/discourse/app/components/post-stream.gjs
index c28b18ac0c6..d50a0ec4e37 100644
--- a/frontend/discourse/app/components/post-stream.gjs
+++ b/frontend/discourse/app/components/post-stream.gjs
@@ -59,6 +59,9 @@ export default class PostStream extends Component {
body.focus({ preventScroll: true });
});
+ quoteHighlightFor = (post) =>
+ this.args.postStream.quoteHighlights.get(post.post_number);
+
constructor() {
super(...arguments);
@@ -386,6 +389,7 @@ export default class PostStream extends Component {
@permanentlyDeletePost={{fn @permanentlyDeletePost post}}
@post={{post}}
@prevPost={{previousPost}}
+ @quoteHighlight={{this.quoteHighlightFor post}}
@rebakePost={{fn @rebakePost post}}
@recoverPost={{fn @recoverPost post}}
@removeAllowedGroup={{@removeAllowedGroup}}
diff --git a/frontend/discourse/app/components/post.gjs b/frontend/discourse/app/components/post.gjs
index 7fbf18357bd..49294d7f7d9 100644
--- a/frontend/discourse/app/components/post.gjs
+++ b/frontend/discourse/app/components/post.gjs
@@ -562,6 +562,7 @@ export default class Post extends Component {
@decoratorState={{this.decoratorState}}
@highlightTerm={{@highlightTerm}}
@post={{@post}}
+ @quoteHighlight={{@quoteHighlight}}
@streamElement={{@streamElement}}
/>
</PluginOutlet>
diff --git a/frontend/discourse/app/components/post/cooked-html.gjs b/frontend/discourse/app/components/post/cooked-html.gjs
index 776bd8feb15..d14f1a64fd3 100644
--- a/frontend/discourse/app/components/post/cooked-html.gjs
+++ b/frontend/discourse/app/components/post/cooked-html.gjs
@@ -12,6 +12,7 @@ import decorateLinkCounts from "discourse/lib/post-cooked-html-decorators/link-c
import decorateLocalizedOneboxes from "discourse/lib/post-cooked-html-decorators/localized-oneboxes";
import decorateMentions from "discourse/lib/post-cooked-html-decorators/mentions";
import decorateQuoteControls from "discourse/lib/post-cooked-html-decorators/quote-controls";
+import decorateQuoteHighlight from "discourse/lib/post-cooked-html-decorators/quote-highlight";
import decorateSearchHighlight from "discourse/lib/post-cooked-html-decorators/search-highlight";
import decorateSelectionBarrier from "discourse/lib/post-cooked-html-decorators/selection-barrier";
import decorateStatefulHtmlElements from "discourse/lib/post-cooked-html-decorators/stateful-html-elements";
@@ -29,6 +30,7 @@ const POST_COOKED_DECORATORS = [
decorateQuoteControls,
decorateLinkCounts,
decorateSearchHighlight,
+ decorateQuoteHighlight,
decorateMentions,
];
@@ -147,6 +149,7 @@ export default class PostCookedHtml extends Component {
isIgnored: args.isIgnored,
owner,
post: this.args.post,
+ quoteHighlight: args.quoteHighlight,
renderGlimmer: helper.renderGlimmer,
renderNestedPostCookedHtml,
streamElement: this.isStreamElement,
@@ -193,6 +196,7 @@ export default class PostCookedHtml extends Component {
highlightTerm=this.highlightTerm
isIgnored=this.isIgnored
ignoredUsers=this.ignoredUsers
+ quoteHighlight=@quoteHighlight
}}
@html={{trustHTML this.cooked}}
@model={{@post}}
diff --git a/frontend/discourse/app/components/post/quoted-content.gjs b/frontend/discourse/app/components/post/quoted-content.gjs
index 4b25883630e..851657d6255 100644
--- a/frontend/discourse/app/components/post/quoted-content.gjs
+++ b/frontend/discourse/app/components/post/quoted-content.gjs
@@ -3,12 +3,20 @@ import { tracked } from "@glimmer/tracking";
import { hash } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
+import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { modifier as modifierFn } from "ember-modifier";
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 { reveal } from "discourse/lib/highlight-html";
+import { wantsNewWindow } from "discourse/lib/intercept-click";
+import {
+ highlightQuote,
+ quotableText,
+ QUOTE_HIGHLIGHT_ID,
+} from "discourse/lib/quote";
+import DiscourseURL from "discourse/lib/url";
import { postUrl } from "discourse/lib/utilities";
import { eq } from "discourse/truth-helpers";
import DAsyncContent from "discourse/ui-kit/d-async-content";
@@ -50,14 +58,22 @@ export default class PostQuotedContent extends Component {
});
#quotedPost = this.args.decoratorState?.get(this.statePostId);
+ #collapsedElement;
+ #renderedText;
+ #scrollToHighlight = false;
#highlightOriginalText = (cookedElement) => {
if (!this.expanded) {
+ this.#collapsedElement = cookedElement;
return;
}
- // to highlight the quoted text inside the original post content
- highlightHTML(cookedElement, this.args.originalText, {
- matchCase: true,
+
+ schedule("afterRender", () => {
+ const highlights = highlightQuote(cookedElement, this.#quotedText);
+ if (this.#scrollToHighlight) {
+ this.#scrollToHighlight = false;
+ this.#showHighlights(cookedElement, highlights);
+ }
});
};
@@ -129,6 +145,13 @@ export default class PostQuotedContent extends Component {
return this.args.wrapperElement ? dElement("") : dElement("aside");
}
+ get #quotedText() {
+ return (
+ this.#renderedText ||
+ (this.args.originalQuote && quotableText(this.args.originalQuote))
+ );
+ }
+
@action
async loadQuotedPost({ topicNumber, postNumber }) {
if (
@@ -152,6 +175,22 @@ export default class PostQuotedContent extends Component {
return post;
}
+ @action
+ followQuote(event) {
+ if (wantsNewWindow(event)) {
+ return;
+ }
+
+ event.preventDefault();
+ this.#saveRenderedText();
+ document.getElementById(QUOTE_HIGHLIGHT_ID)?.removeAttribute("id");
+
+ DiscourseURL.routeTo(this.quotedPostUrl, {
+ anchor: QUOTE_HIGHLIGHT_ID,
+ highlightQuote: this.#quotedText,
+ });
+ }
+
@action
onClickTitle(event) {
if (event.target.closest("a") || event.target.closest(".quote-controls")) {
@@ -162,10 +201,35 @@ export default class PostQuotedContent extends Component {
@action
toggleExpanded() {
+ this.#saveRenderedText();
this.expanded = !this.expanded;
+ this.#scrollToHighlight = this.expanded;
this.args.decoratorState?.set(this.stateExpandedId, this.expanded);
}
+ #saveRenderedText() {
+ if (!this.expanded && this.#collapsedElement) {
+ this.#renderedText = quotableText(this.#collapsedElement);
+ }
+ }
+
+ #showHighlights(cookedElement, highlights) {
+ if (!highlights.length) {
+ return;
+ }
+
+ this.#finishExpandAnimation(cookedElement);
+ reveal(highlights);
+ highlights[0].scrollIntoView({ block: "center" });
+ }
+
+ #finishExpandAnimation(cookedElement) {
+ cookedElement
+ .closest(".expanded-quote")
+ ?.getAnimations()
+ .forEach((animation) => animation.finish());
+ }
+
<template>
<this.OptionalWrapperComponent
...attributes
@@ -240,6 +304,7 @@ export default class PostQuotedContent extends Component {
@ariaLabel="post.follow_quote"
@href={{this.quotedPostUrl}}
@title="post.follow_quote"
+ {{on "click" this.followQuote}}
>
{{! 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 }}
diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.js
index 0ffbc7b751e..b76b4ec7731 100644
--- a/frontend/discourse/app/controllers/topic.js
+++ b/frontend/discourse/app/controllers/topic.js
@@ -1945,6 +1945,11 @@ export default class TopicController extends Controller {
if (options.jump !== false) {
this.model?.postStream?.focusPostOnRender(postNumber);
}
+
+ this.model?.postStream?.highlightQuoteOnRender(
+ postNumber,
+ options.highlightQuote
+ );
}
_showRevision(postNumber, revision) {
diff --git a/frontend/discourse/app/lib/highlight-html.js b/frontend/discourse/app/lib/highlight-html.js
index a3b4c523c98..d6672fb22c0 100644
--- a/frontend/discourse/app/lib/highlight-html.js
+++ b/frontend/discourse/app/lib/highlight-html.js
@@ -1,5 +1,7 @@
import { makeArray } from "discourse/lib/helpers";
+export const REVEAL_EVENT = "beforematch";
+
function highlight(node, pattern, nodeName, className) {
if (
![Node.ELEMENT_NODE, Node.TEXT_NODE].includes(node.nodeType) ||
@@ -86,3 +88,9 @@ export function unhighlightHTML(opts = {}) {
parentNode.normalize();
});
}
+
+export function reveal(elements) {
+ elements.forEach((element) =>
+ element.dispatchEvent(new Event(REVEAL_EVENT, { bubbles: true }))
+ );
+}
diff --git a/frontend/discourse/app/lib/lock-on.js b/frontend/discourse/app/lib/lock-on.js
index d6c57acd992..a964f218d2e 100644
--- a/frontend/discourse/app/lib/lock-on.js
+++ b/frontend/discourse/app/lib/lock-on.js
@@ -50,7 +50,8 @@ export default class LockOn {
}
}
- return offset - headerOffset();
+ const scrollMargin = parseFloat(getComputedStyle(element).scrollMarginTop);
+ return offset - headerOffset() - scrollMargin;
}
clearLock() {
diff --git a/frontend/discourse/app/lib/post-cooked-html-decorators/quote-controls.gjs b/frontend/discourse/app/lib/post-cooked-html-decorators/quote-controls.gjs
index c3ddbce5aa3..d8f0793ab45 100644
--- a/frontend/discourse/app/lib/post-cooked-html-decorators/quote-controls.gjs
+++ b/frontend/discourse/app/lib/post-cooked-html-decorators/quote-controls.gjs
@@ -62,7 +62,7 @@ export default function quoteControls(element, context) {
highlightTerm,
id: `quote-id-${quotedTopicId}-${quotedPostNumber}-${index}`,
ignoredUsers,
- originalText: blockquote?.textContent?.trim(),
+ originalQuote: blockquote,
post,
quotedPostNotFound: aside.classList.contains("quote-post-not-found"),
quotedPostNumber,
diff --git a/frontend/discourse/app/lib/post-cooked-html-decorators/quote-highlight.js b/frontend/discourse/app/lib/post-cooked-html-decorators/quote-highlight.js
new file mode 100644
index 00000000000..09cf3115158
--- /dev/null
+++ b/frontend/discourse/app/lib/post-cooked-html-decorators/quote-highlight.js
@@ -0,0 +1,20 @@
+import { schedule } from "@ember/runloop";
+import { reveal } from "discourse/lib/highlight-html";
+import { highlightQuote, QUOTE_HIGHLIGHT_ID } from "discourse/lib/quote";
+
+export default function (element, { quoteHighlight }) {
+ if (!quoteHighlight) {
+ return;
+ }
+
+ schedule("afterRender", () => {
+ const highlights = highlightQuote(element, quoteHighlight.quote);
+ const anchor = highlights[0] ?? element.closest(".topic-post") ?? element;
+ anchor.id = QUOTE_HIGHLIGHT_ID;
+
+ if (!quoteHighlight.revealed) {
+ quoteHighlight.revealed = true;
+ reveal(highlights);
+ }
+ });
+}
diff --git a/frontend/discourse/app/lib/post-cooked-html-decorators/stateful-html-elements.js b/frontend/discourse/app/lib/post-cooked-html-decorators/stateful-html-elements.js
index 41d0e6645a0..657e7020352 100644
--- a/frontend/discourse/app/lib/post-cooked-html-decorators/stateful-html-elements.js
+++ b/frontend/discourse/app/lib/post-cooked-html-decorators/stateful-html-elements.js
@@ -1,5 +1,14 @@
+import { REVEAL_EVENT } from "discourse/lib/highlight-html";
+
export default function (element, context) {
restoreOpenedDetails(element, context);
+ openDetailsOnReveal(element);
+}
+
+function openDetailsOnReveal(element) {
+ element.querySelectorAll("details").forEach((details) => {
+ details.addEventListener(REVEAL_EVENT, () => (details.open = true));
+ });
}
function restoreOpenedDetails(element, context) {
diff --git a/frontend/discourse/app/lib/quote.js b/frontend/discourse/app/lib/quote.js
index 499ce88c2ac..ee9e00b7d4b 100644
--- a/frontend/discourse/app/lib/quote.js
+++ b/frontend/discourse/app/lib/quote.js
@@ -3,6 +3,13 @@ import { prioritizeNameFallback } from "discourse/lib/settings";
import { applyValueTransformer } from "discourse/lib/transformer";
import { stripQuotationMarks } from "discourse-markdown-it/features/bbcode-block";
+const WHITESPACE = /\s/;
+const WORD_CHARACTER = /[\p{L}\p{N}_]/u;
+const MIN_PARTIAL_MATCH_LENGTH = 20;
+const HIGHLIGHT_CLASS = "quote-highlight";
+
+export const QUOTE_HIGHLIGHT_ID = "quote-highlight-start";
+
export const QUOTE_REGEXP =
/\[quote=([^\]]*)\]((?:[\s\S](?!\[quote=[^\]]*\]))*?)\[\/quote\]/im;
@@ -48,3 +55,138 @@ export function buildQuote(post, contents, opts = {}) {
const paramsString = transformedParams.join(", ");
return `[quote="${paramsString}"]\n${contents.trim()}\n[/quote]\n\n`;
}
+
+function indexOfWord(haystack, needle, isWordAt) {
+ const first = haystack.indexOf(needle);
+
+ for (
+ let index = first;
+ index !== -1;
+ index = haystack.indexOf(needle, index + 1)
+ ) {
+ if (isWordAt(index, index + needle.length)) {
+ return index;
+ }
+ }
+
+ return first;
+}
+
+function findLongestPrefix(haystack, needle, isBoundary) {
+ const start = indexOfWord(
+ haystack,
+ needle,
+ (from, to) => isBoundary(from) && isBoundary(to)
+ );
+ if (start !== -1) {
+ return [start, needle.length];
+ }
+
+ let best = [-1, 0];
+ let low = MIN_PARTIAL_MATCH_LENGTH;
+ let high = needle.length - 1;
+
+ while (low <= high) {
+ const length = Math.floor((low + high) / 2);
+ const index = indexOfWord(haystack, needle.slice(0, length), isBoundary);
+
+ if (index === -1) {
+ high = length - 1;
+ continue;
+ }
+
+ best = [index, length];
+ low = length + 1;
+ }
+
+ return best;
+}
+
+function collectText(node, visit) {
+ for (const child of node.childNodes) {
+ if (child.nodeType === Node.TEXT_NODE) {
+ visit(child, child.data);
+ continue;
+ }
+
+ collectText(child, visit);
+ }
+}
+
+export function quotableText(node) {
+ let text = "";
+ collectText(node, (_, data) => (text += data));
+ return text.trim();
+}
+
+function indexText(node) {
+ const index = { haystack: "", targets: [], offsets: [], spacedBefore: [] };
+ let spaced = true;
+
+ collectText(node, (target, data) => {
+ for (let offset = 0; offset < data.length; offset++) {
+ if (WHITESPACE.test(data[offset])) {
+ spaced = true;
+ continue;
+ }
+
+ index.haystack += data[offset];
+ index.targets.push(target);
+ index.offsets.push(offset);
+ index.spacedBefore.push(spaced);
+ spaced = false;
+ }
+ });
+
+ return index;
+}
+
+function wrapMatch(target, from, to) {
+ const parent = target.parentElement;
+ if (
+ parent.classList.contains(HIGHLIGHT_CLASS) &&
+ from === 0 &&
+ to === target.length
+ ) {
+ return parent;
+ }
+
+ const match = target.splitText(from);
+ match.splitText(to - from);
+
+ const span = document.createElement("span");
+ span.className = HIGHLIGHT_CLASS;
+ match.replaceWith(span);
+ span.append(match);
+ return span;
+}
+
+export function highlightQuote(node, text) {
+ const needle = text?.replaceAll(/\s+/g, "");
+ if (!needle) {
+ return [];
+ }
+
+ const { haystack, targets, offsets, spacedBefore } = indexText(node);
+
+ const isBoundary = (index) =>
+ index === haystack.length ||
+ spacedBefore[index] ||
+ !WORD_CHARACTER.test(haystack[index - 1]) ||
+ !WORD_CHARACTER.test(haystack[index]);
+
+ const [start, length] = findLongestPrefix(haystack, needle, isBoundary);
+ if (start === -1) {
+ return [];
+ }
+
+ const matches = new Map();
+ for (let i = start; i < start + length; i++) {
+ const from = matches.get(targets[i])?.[0] ?? offsets[i];
+ matches.set(targets[i], [from, offsets[i] + 1]);
+ }
+
+ return [...matches]
+ .filter(([target]) => !target.parentElement.closest("svg"))
+ .map(([target, [from, to]]) => wrapMatch(target, from, to));
+}
diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.js
index d0e90e7a5fa..3dfe954eacc 100644
--- a/frontend/discourse/app/lib/url.js
+++ b/frontend/discourse/app/lib/url.js
@@ -465,16 +465,15 @@ class DiscourseURL extends EmberObject {
enteredAt: Date.now().toString(),
});
- this.appEvents.trigger("post:highlight", closest);
+ this.appEvents.trigger("post:highlight", closest, {
+ highlightQuote: routeOpts.highlightQuote,
+ });
const jumpOpts = {
skipIfOnScreen: routeOpts.skipIfOnScreen,
jumpEnd: routeOpts.jumpEnd,
};
- const anchorMatch = /#(.+)$/.exec(path);
- if (anchorMatch) {
- jumpOpts.anchor = anchorMatch[1];
- }
+ jumpOpts.anchor = routeOpts.anchor ?? /#(.+)$/.exec(path)?.[1];
this.jumpToPost(closest, jumpOpts);
});
diff --git a/frontend/discourse/app/models/post-stream.js b/frontend/discourse/app/models/post-stream.js
index ea9b697eecd..87e57941b38 100644
--- a/frontend/discourse/app/models/post-stream.js
+++ b/frontend/discourse/app/models/post-stream.js
@@ -1,7 +1,7 @@
import { cached, tracked } from "@glimmer/tracking";
import { get } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
-import { trackedObject } from "@ember/reactive/collections";
+import { trackedMap, trackedObject } from "@ember/reactive/collections";
import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
@@ -98,6 +98,7 @@ export default class PostStream extends RestModel {
@autoTrackedArray stream = [];
@autoTrackedArray userFilters = [];
+ quoteHighlights = trackedMap();
_identityMap = {};
_pendingPostRefreshes = new Map();
@@ -312,6 +313,17 @@ export default class PostStream extends RestModel {
}
}
+ highlightQuoteOnRender(postNumber, quote) {
+ if (quote === undefined) {
+ return;
+ }
+
+ [...this.quoteHighlights.keys()].forEach((key) =>
+ this.quoteHighlights.delete(key)
+ );
+ this.quoteHighlights.set(postNumber, { quote, revealed: false });
+ }
+
cancelFilter() {
this.streamFilters.mixedHiddenPosts = false;
diff --git a/frontend/discourse/tests/unit/lib/lock-on-test.js b/frontend/discourse/tests/unit/lib/lock-on-test.js
index 394f9005515..91b7f6cd2b1 100644
--- a/frontend/discourse/tests/unit/lib/lock-on-test.js
+++ b/frontend/discourse/tests/unit/lib/lock-on-test.js
@@ -2,10 +2,28 @@ import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
import sinon from "sinon";
import LockOn from "discourse/lib/lock-on";
+import { headerOffset } from "discourse/lib/offset-calculator";
+import { fixture } from "discourse/tests/helpers/qunit-helpers";
module("Unit | Utility | lock-on", function (hooks) {
setupTest(hooks);
+ test("keeps the element's scroll margin above it", function (assert) {
+ const target = document.createElement("div");
+ target.id = "lock-on-target";
+ target.style.scrollMarginTop = "100px";
+ fixture().append(target);
+ const top = target.getBoundingClientRect().top + window.scrollY;
+
+ const elementTop = new LockOn("#lock-on-target").elementTop();
+
+ assert.strictEqual(
+ elementTop,
+ top - headerOffset() - 100,
+ "leaves the scroll margin above the element"
+ );
+ });
+
test("stops polling for a missing element once it times out", async function (assert) {
const clock = sinon.useFakeTimers({ toFake: ["Date"] });
const finished = sinon.spy();
diff --git a/frontend/discourse/tests/unit/lib/post-cooked-html-decorators/quote-highlight-test.js b/frontend/discourse/tests/unit/lib/post-cooked-html-decorators/quote-highlight-test.js
new file mode 100644
index 00000000000..eb6aa11c43d
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/post-cooked-html-decorators/quote-highlight-test.js
@@ -0,0 +1,43 @@
+import { run } from "@ember/runloop";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { REVEAL_EVENT } from "discourse/lib/highlight-html";
+import decorateQuoteHighlight from "discourse/lib/post-cooked-html-decorators/quote-highlight";
+import { QUOTE_HIGHLIGHT_ID } from "discourse/lib/quote";
+
+module("Unit | Utility | quote-highlight decorator", function (hooks) {
+ setupTest(hooks);
+
+ test("anchors the post when the quote no longer matches", function (assert) {
+ const post = document.createElement("div");
+ post.className = "topic-post";
+ post.innerHTML =
+ "<div class='cooked'><p>Edited since it was quoted</p></div>";
+
+ run(() =>
+ decorateQuoteHighlight(post.querySelector(".cooked"), {
+ quoteHighlight: { quote: "Original wording", revealed: false },
+ })
+ );
+
+ assert.strictEqual(post.id, QUOTE_HIGHLIGHT_ID, "anchors the whole post");
+ });
+
+ test("anchors the first highlight and reveals it only once", function (assert) {
+ const element = document.createElement("div");
+ element.innerHTML = "<p>Original wording</p>";
+ let reveals = 0;
+ element.addEventListener(REVEAL_EVENT, () => reveals++);
+ const quoteHighlight = { quote: "Original wording", revealed: false };
+
+ run(() => decorateQuoteHighlight(element, { quoteHighlight }));
+ run(() => decorateQuoteHighlight(element, { quoteHighlight }));
+
+ assert.strictEqual(
+ element.querySelector(`#${QUOTE_HIGHLIGHT_ID}`).textContent,
+ "Original wording",
+ "anchors the first highlight"
+ );
+ assert.strictEqual(reveals, 1, "reveals only on the first render");
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/quote-test.js b/frontend/discourse/tests/unit/lib/quote-test.js
new file mode 100644
index 00000000000..14b6acf54fc
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/quote-test.js
@@ -0,0 +1,126 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { highlightQuote } from "discourse/lib/quote";
+
+module("Unit | Utility | quote", function (hooks) {
+ setupTest(hooks);
+
+ test("highlightQuote matches across formatting and paragraphs", function (assert) {
+ const elem = document.createElement("div");
+ elem.innerHTML =
+ "<p>Before. Hello <strong>bold</strong> <a href='#'>link</a></p>\n<p>two</p>\n<p>After.</p>";
+
+ const highlights = highlightQuote(elem, "Hello bold link\n\ntwo");
+
+ assert.deepEqual(
+ highlights.map((highlight) => highlight.textContent),
+ ["Hello", "bold", "link", "two"],
+ "highlights each piece of the quote"
+ );
+ assert.true(
+ highlights.every((h) => h.matches("span.quote-highlight")),
+ "wraps text in highlight spans"
+ );
+ assert.strictEqual(
+ elem.textContent,
+ "Before. Hello bold link\ntwo\nAfter.",
+ "keeps the text intact"
+ );
+ });
+
+ test("highlightQuote prefers whole words", function (assert) {
+ const elem = document.createElement("div");
+ elem.innerHTML = "<p>Start with the artist, then the art section</p>";
+
+ const [highlight] = highlightQuote(elem, "art");
+
+ assert.strictEqual(
+ highlight.previousSibling.textContent.slice(-4),
+ "the ",
+ "starts at the whole word"
+ );
+ assert.strictEqual(
+ highlight.nextSibling.textContent,
+ " section",
+ "ends at the whole word"
+ );
+ });
+
+ test("highlightQuote falls back to part of a word", function (assert) {
+ const elem = document.createElement("div");
+ elem.innerHTML = "<p>artist</p>";
+
+ assert.deepEqual(
+ highlightQuote(elem, "art").map((highlight) => highlight.textContent),
+ ["art"],
+ "falls back to the first occurrence"
+ );
+ });
+
+ test("highlightQuote leaves SVG text alone", function (assert) {
+ const elem = document.createElement("div");
+ elem.innerHTML = "<p>Before</p><svg><text>label</text></svg><p>after</p>";
+
+ const highlights = highlightQuote(elem, "Before label after");
+
+ assert.deepEqual(
+ highlights.map((highlight) => highlight.textContent),
+ ["Before", "after"],
+ "highlights the text around the SVG"
+ );
+ assert
+ .dom("svg .quote-highlight", elem)
+ .doesNotExist("leaves SVG text unwrapped");
+ });
+
+ test("highlightQuote reuses existing highlights", function (assert) {
+ const elem = document.createElement("div");
+ elem.innerHTML = "<p>Hello <strong>bold</strong> world</p>";
+
+ highlightQuote(elem, "Hello bold");
+ const highlights = highlightQuote(elem, "Hello bold");
+
+ assert.strictEqual(highlights.length, 2, "returns both highlights");
+ assert
+ .dom(".quote-highlight .quote-highlight", elem)
+ .doesNotExist("does not nest highlights");
+ });
+
+ test("highlightQuote falls back to the longest matching start of the text", function (assert) {
+ const elem = document.createElement("div");
+ elem.innerHTML =
+ "<p>The launch party starts on <span>Oct 19, 4:00 PM</span> at the park</p>";
+
+ const highlights = highlightQuote(
+ elem,
+ "The launch party starts on 2026-10-19T14:00:00Z at the park"
+ );
+
+ assert.deepEqual(
+ highlights.map((highlight) => highlight.textContent),
+ ["The launch party starts on"],
+ "highlights the matching start"
+ );
+ });
+
+ test("highlightQuote leaves the element untouched without a long enough match", function (assert) {
+ const elem = document.createElement("div");
+ elem.innerHTML = "<p>The <em>dog</em> barked</p>";
+
+ assert.deepEqual(
+ highlightQuote(elem, "The cat sat on the mat all day"),
+ [],
+ "ignores a match shorter than the minimum"
+ );
+ assert.deepEqual(
+ highlightQuote(elem, undefined),
+ [],
+ "ignores a missing quote"
+ );
+ assert.strictEqual(
+ elem.innerHTML,
+ "<p>The <em>dog</em> barked</p>",
+ "leaves the markup untouched"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/unit/models/post-stream-test.js b/frontend/discourse/tests/unit/models/post-stream-test.js
index 8a90861a0c8..15438469510 100644
--- a/frontend/discourse/tests/unit/models/post-stream-test.js
+++ b/frontend/discourse/tests/unit/models/post-stream-test.js
@@ -126,6 +126,26 @@ module("Unit | Model | post-stream", function (hooks) {
);
});
+ test("highlightQuoteOnRender keeps only the latest quote", function (assert) {
+ const postStream = buildStream.call(this, 1232);
+
+ postStream.highlightQuoteOnRender(3, "first quote");
+ postStream.highlightQuoteOnRender(4);
+ assert.strictEqual(
+ postStream.quoteHighlights.get(3).quote,
+ "first quote",
+ "keeps the quote when a jump has nothing to highlight"
+ );
+
+ postStream.highlightQuoteOnRender(5, "second quote");
+ assert.false(postStream.quoteHighlights.has(3), "drops the previous quote");
+ assert.strictEqual(
+ postStream.quoteHighlights.get(5).quote,
+ "second quote",
+ "stores the latest quote"
+ );
+ });
+
test("closestPostNumberFor", function (assert) {
const postStream = buildStream.call(this, 1231);
const store = getOwner(this).lookup("service:store");
diff --git a/plugins/discourse-details/spec/system/quoted_details_spec.rb b/plugins/discourse-details/spec/system/quoted_details_spec.rb
new file mode 100644
index 00000000000..fcc268c2155
--- /dev/null
+++ b/plugins/discourse-details/spec/system/quoted_details_spec.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+describe "Following a quote of text inside details" do
+ fab!(:topic)
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ it "reveals the quoted text hidden in details" do
+ Fabricate(:post, topic:)
+ quoted_post = Fabricate(:post, topic:, raw: "[details=\"Spoiler\"]\nHidden text\n[/details]")
+ quoting_post =
+ Fabricate(
+ :post,
+ topic:,
+ raw:
+ "[quote=\"#{quoted_post.user.username}, post:#{quoted_post.post_number}, topic:#{topic.id}\"]\nHidden text\n[/quote]",
+ )
+
+ topic_page.visit_topic(topic, post_number: quoting_post.post_number)
+ topic_page.follow_quote(quoting_post)
+
+ expect(topic_page).to have_highlighted_text(quoted_post, "Hidden text", inside: "details[open]")
+ end
+end
diff --git a/plugins/discourse-local-dates/spec/system/quoted_local_date_spec.rb b/plugins/discourse-local-dates/spec/system/quoted_local_date_spec.rb
new file mode 100644
index 00000000000..9c81c955475
--- /dev/null
+++ b/plugins/discourse-local-dates/spec/system/quoted_local_date_spec.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+describe "Following a quote containing a local date" do
+ fab!(:topic)
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ it "shows the whole quoted text including the date" do
+ text = "Party on [date=2030-11-20 time=18:00:00 timezone=\"Europe/Paris\"] at the harbour"
+ quoted_post = Fabricate(:post, topic:, raw: text)
+ quoting_post =
+ Fabricate(
+ :post,
+ topic:,
+ raw:
+ "[quote=\"#{quoted_post.user.username}, post:1, topic:#{topic.id}\"]\n#{text}\n[/quote]",
+ )
+
+ topic_page.visit_topic(topic, post_number: quoting_post.post_number)
+ topic_page.follow_quote(quoting_post)
+
+ expect(topic_page).to have_highlighted_text(quoted_post, "harbour")
+ end
+end
diff --git a/plugins/spoiler-alert/assets/javascripts/lib/apply-spoiler.js b/plugins/spoiler-alert/assets/javascripts/lib/apply-spoiler.js
index f00629ef519..261d51735dd 100644
--- a/plugins/spoiler-alert/assets/javascripts/lib/apply-spoiler.js
+++ b/plugins/spoiler-alert/assets/javascripts/lib/apply-spoiler.js
@@ -1,3 +1,4 @@
+import { REVEAL_EVENT } from "discourse/lib/highlight-html";
import { i18n } from "discourse-i18n";
const INTERACTIVE_SELECTOR = [
@@ -97,6 +98,8 @@ export default function applySpoiler(element) {
toggleSpoiler(event, element);
});
+ element.addEventListener(REVEAL_EVENT, () => _setSpoilerVisible(element));
+
element.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
toggleSpoiler(event, element);
diff --git a/plugins/spoiler-alert/test/javascripts/unit/lib/apply-spoiler-test.js b/plugins/spoiler-alert/test/javascripts/unit/lib/apply-spoiler-test.js
index 018cb4bc4f5..bc0a94e771a 100644
--- a/plugins/spoiler-alert/test/javascripts/unit/lib/apply-spoiler-test.js
+++ b/plugins/spoiler-alert/test/javascripts/unit/lib/apply-spoiler-test.js
@@ -1,5 +1,6 @@
import { setupTest } from "ember-qunit";
import { module, test } from "qunit";
+import { REVEAL_EVENT } from "discourse/lib/highlight-html";
import applySpoiler from "discourse/plugins/spoiler-alert/lib/apply-spoiler";
module("Spoiler Alert | Unit | apply-spoiler", function (hooks) {
@@ -113,4 +114,15 @@ module("Spoiler Alert | Unit | apply-spoiler", function (hooks) {
spoiler.remove();
}
});
+
+ test("reveals on the reveal event", function (assert) {
+ const spoiler = buildSpoiler();
+ applySpoiler(spoiler);
+
+ spoiler.dispatchEvent(new Event(REVEAL_EVENT));
+
+ assert
+ .dom(spoiler)
+ .hasAttribute("data-spoiler-state", "revealed", "reveals the spoiler");
+ });
});
diff --git a/spec/system/page_objects/pages/topic.rb b/spec/system/page_objects/pages/topic.rb
index 24a65de332b..4de0731ff91 100644
--- a/spec/system/page_objects/pages/topic.rb
+++ b/spec/system/page_objects/pages/topic.rb
@@ -84,6 +84,22 @@ module PageObjects
within_post(post) { has_no_css?(".embedded-posts") }
end
+ def expand_quote(post)
+ within_post(post) { find("aside.quote .quote-toggle", match: :first).click }
+ end
+
+ def follow_quote(post)
+ within_post(post) { find("aside.quote .quote-controls .back").click }
+ end
+
+ def has_highlighted_text?(post, text, inside: nil)
+ selector = [inside, ".quote-highlight"].compact.join(" ")
+ within_post(post) do
+ has_css?(selector, obscured: false) &&
+ text.split.all? { |word| has_css?(selector, text: word) }
+ end
+ end
+
def post_by_number(post_or_number, wait: Capybara.default_max_wait_time)
post_or_number = post_or_number.is_a?(Post) ? post_or_number.post_number : post_or_number
find(".topic-post:not(.staged) #post_#{post_or_number}", wait: wait)
diff --git a/spec/system/quote_highlight_spec.rb b/spec/system/quote_highlight_spec.rb
new file mode 100644
index 00000000000..da897baf948
--- /dev/null
+++ b/spec/system/quote_highlight_spec.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+describe "Quoted text highlighting" do
+ fab!(:user)
+ fab!(:topic)
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ it "shows the quoted text when expanding or following a quote" do
+ quoted_markdown = "Hello **bold** and [a link](https://example.com)\n\nSecond `code` paragraph"
+ filler = 40.times.map { |i| "Filler paragraph #{i}." }.join("\n\n")
+ quoted_post = Fabricate(:post, topic:, raw: "#{filler}\n\n#{quoted_markdown}")
+ Fabricate.times(30, :post, topic:, user:)
+ quoting_post =
+ Fabricate(
+ :post,
+ topic:,
+ raw:
+ "[quote=\"#{quoted_post.user.username}, post:1, topic:#{topic.id}\"]\n#{quoted_markdown}\n[/quote]",
+ )
+
+ topic_page.visit_topic(topic, post_number: quoting_post.post_number)
+
+ topic_page.expand_quote(quoting_post)
+ expect(topic_page).to have_highlighted_text(
+ quoting_post,
+ "Hello bold and a link Second code paragraph",
+ )
+
+ topic_page.follow_quote(quoting_post)
+ expect(topic_page).to have_highlighted_text(
+ quoted_post,
+ "Hello bold and a link Second code paragraph",
+ )
+ end
+
+ it "shows the quoted text inside a nested quote when expanding" do
+ source = Fabricate(:post, topic:, raw: "Original words from the source")
+ quoted_post =
+ Fabricate(
+ :post,
+ topic:,
+ raw:
+ "[quote=\"#{source.user.username}, post:1, topic:#{topic.id}\"]\nOriginal words from the source\n[/quote]\nA reply",
+ )
+ quoting_post =
+ Fabricate(
+ :post,
+ topic:,
+ raw:
+ "[quote=\"#{quoted_post.user.username}, post:#{quoted_post.post_number}, topic:#{topic.id}\"]\nOriginal words from the source\n[/quote]",
+ )
+
+ topic_page.visit_topic(topic, post_number: quoting_post.post_number)
+ topic_page.expand_quote(quoting_post)
+
+ expect(topic_page).to have_highlighted_text(quoting_post, "Original words from the source")
+ end
+end