Skip to content

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

UX: Show the quoted user's avatar in rich editor quotes (#42446)

Renato Atilio33e34302a9ae
diff --git a/frontend/discourse/app/components/composer-editor.gjs b/frontend/discourse/app/components/composer-editor.gjs
index f9544ff97ce..27289201a0a 100644
--- a/frontend/discourse/app/components/composer-editor.gjs
+++ b/frontend/discourse/app/components/composer-editor.gjs
@@ -183,6 +183,28 @@ export default class ComposerEditor extends Component {
}
}
+ @bind
+ lookupAvatarTemplateByPostNumber(postNumber, topicId) {
+ const topic = this.topic;
+ if (!topic || topicId !== topic.get("id")) {
+ return;
+ }
+
+ const quotedPost = topic
+ .get("postStream.posts")
+ ?.find((p) => p.post_number === postNumber);
+
+ if (!quotedPost) {
+ return;
+ }
+
+ return applyValueTransformer(
+ "composer-editor-quoted-post-avatar-template",
+ quotedPost.get("avatar_template"),
+ { post: quotedPost }
+ );
+ }
+
@computed
get markdownOptions() {
return {
@@ -191,25 +213,16 @@ export default class ComposerEditor extends Component {
formatUsername,
lookupAvatarByPostNumber: (postNumber, topicId) => {
- const topic = this.topic;
- if (!topic) {
- return;
- }
+ const avatarTemplate = this.lookupAvatarTemplateByPostNumber(
+ postNumber,
+ topicId
+ );
- const posts = topic.get("postStream.posts");
- if (posts && topicId === topic.get("id")) {
- const quotedPost = posts.find((p) => p.post_number === postNumber);
- if (quotedPost) {
- const avatarTemplate = applyValueTransformer(
- "composer-editor-quoted-post-avatar-template",
- quotedPost.get("avatar_template"),
- { post: quotedPost }
- );
- return tinyAvatar(avatarTemplate);
- }
- }
+ return avatarTemplate ? tinyAvatar(avatarTemplate) : undefined;
},
+ lookupAvatarTemplateByPostNumber: this.lookupAvatarTemplateByPostNumber,
+
lookupPrimaryUserGroupByPostNumber: (postNumber, topicId) => {
const topic = this.topic;
if (!topic) {
diff --git a/frontend/discourse/app/lib/composer/rich-editor-extensions.ts b/frontend/discourse/app/lib/composer/rich-editor-extensions.ts
index 7ff1d4e2b0f..4dcd4e347bd 100644
--- a/frontend/discourse/app/lib/composer/rich-editor-extensions.ts
+++ b/frontend/discourse/app/lib/composer/rich-editor-extensions.ts
@@ -28,6 +28,15 @@ import type ModalService from "discourse/services/modal";
import type GlimmerNodeView from "discourse/static/prosemirror/lib/glimmer-node-view";
import type { ToolbarBase } from "./toolbar";
+export interface MarkdownOptions {
+ /** Avatar template of a post in the host editor's topic. */
+ lookupAvatarTemplateByPostNumber?: (
+ postNumber: number,
+ topicId: number
+ ) => string | undefined;
+ [key: string]: unknown;
+}
+
export interface PluginContext {
/** Placeholder shown when the document is empty. */
placeholder?: string;
@@ -55,6 +64,8 @@ export interface PluginContext {
dialog: DialogService;
/** Replaces or restores the toolbar displayed by the editor container. */
replaceToolbar?: (toolbar: ToolbarBase | null, owner?: ToolbarBase) => void;
+ /** Markdown cook options provided by the host editor. */
+ markdownOptions?: MarkdownOptions;
/** Registers a rendered component-backed node view. */
addGlimmerNodeView: (nodeView: GlimmerNodeView) => void;
/** Unregisters a rendered component-backed node view. */
diff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts
index d29a07dbdb9..0eca999d249 100644
--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts
+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts
@@ -35,6 +35,7 @@ import type MenuService from "discourse/float-kit/services/menu";
import type ToastsService from "discourse/float-kit/services/toasts";
import {
getExtensions,
+ type MarkdownOptions,
type PluginParams,
type RichEditorExtension,
} from "discourse/lib/composer/rich-editor-extensions";
@@ -102,6 +103,8 @@ interface ProsemirrorEditorSignature {
replaceToolbar?: (toolbar: ToolbarBase | null, owner?: ToolbarBase) => void;
/** Toggles between the rich and plain-text editors. */
toggleRichEditor?: () => void;
+ /** Markdown cook options from the host editor, exposed to extensions. */
+ markdownOptions?: MarkdownOptions;
};
}
@@ -187,6 +190,7 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignat
appEvents: this.appEvents,
dialog: this.dialog,
replaceToolbar: this.args.replaceToolbar,
+ markdownOptions: this.args.markdownOptions,
// TODO(devxp-typescript-pending): remove the cast once GlimmerNodeView's
// component field has a typed invocation signature.
addGlimmerNodeView: (nodeView) =>
diff --git a/frontend/discourse/app/static/prosemirror/extensions/quote.js b/frontend/discourse/app/static/prosemirror/extensions/quote.js
index 6f0fd7fba12..090031143c7 100644
--- a/frontend/discourse/app/static/prosemirror/extensions/quote.js
+++ b/frontend/discourse/app/static/prosemirror/extensions/quote.js
@@ -1,7 +1,125 @@
import { schema } from "prosemirror-markdown";
+import { avatarUrl, translateSize } from "discourse/lib/avatar-utils";
+
+// null values are omitted, both when serialized and applied by the node view
+function quoteDataAttrs(node) {
+ const { username, displayName, postNumber, topicId, full } = node.attrs;
+
+ return {
+ "data-username": username,
+ "data-post": postNumber,
+ "data-topic": topicId,
+ "data-full": full === "true" ? "true" : "false",
+ "data-display-name": displayName,
+ };
+}
+
+function avatarElement(avatarTemplate) {
+ const size = translateSize("tiny");
+ const src = avatarUrl(avatarTemplate, size);
+
+ if (!src) {
+ return null;
+ }
+
+ const img = document.createElement("img");
+ img.className = "avatar";
+ img.alt = "";
+ img.src = src;
+ img.width = size;
+ img.height = size;
+
+ return img;
+}
+
+function createQuoteNodeView({ getContext }) {
+ return class QuoteNodeView {
+ #title;
+
+ constructor(node) {
+ this.node = node;
+
+ this.dom = document.createElement("aside");
+ // set once, as the editor also manages classes on this element
+ this.dom.className = "quote";
+
+ this.contentDOM = document.createElement("blockquote");
+ this.dom.append(this.contentDOM);
+
+ this.#render(node);
+ }
+
+ update(node) {
+ // update() also fires for content edits; the header depends only on markup
+ if (!this.node.sameMarkup(node)) {
+ this.#render(node);
+ }
+
+ this.node = node;
+
+ return true;
+ }
+
+ selectNode() {
+ this.dom.classList.add("ProseMirror-selectednode");
+ }
+
+ deselectNode() {
+ this.dom.classList.remove("ProseMirror-selectednode");
+ }
+
+ #render(node) {
+ for (const [name, value] of Object.entries(quoteDataAttrs(node))) {
+ if (value == null) {
+ this.dom.removeAttribute(name);
+ } else {
+ this.dom.setAttribute(name, value);
+ }
+ }
+
+ this.#title?.remove();
+ this.#title = this.#buildTitle(node);
+
+ if (this.#title) {
+ this.dom.insertBefore(this.#title, this.contentDOM);
+ }
+ }
+
+ #buildTitle(node) {
+ const { username, displayName, postNumber, topicId } = node.attrs;
+
+ if (!username) {
+ return null;
+ }
+
+ const title = document.createElement("div");
+ title.className = "title";
+
+ const avatarTemplate =
+ postNumber &&
+ topicId &&
+ getContext().markdownOptions?.lookupAvatarTemplateByPostNumber?.(
+ parseInt(postNumber, 10),
+ parseInt(topicId, 10)
+ );
+
+ const img = avatarTemplate && avatarElement(avatarTemplate);
+
+ if (img) {
+ title.append(img);
+ }
+
+ title.append(`${displayName || username}:`);
+
+ return title;
+ }
+ };
+}
/** @type {RichEditorExtension} */
const extension = {
+ nodeViews: { quote: createQuoteNodeView },
+
nodeSpec: {
blockquote: {
createGapCursor: true,
@@ -35,17 +153,9 @@ const extension = {
},
],
toDOM(node) {
- const { username, displayName, postNumber, topicId, full } = node.attrs;
- const attrs = { class: "quote" };
- attrs["data-username"] = username;
- attrs["data-post"] = postNumber;
- attrs["data-topic"] = topicId;
- attrs["data-full"] = full === "true" ? "true" : "false";
- if (displayName) {
- attrs["data-display-name"] = displayName;
- }
+ const { username, displayName } = node.attrs;
- const domSpec = ["aside", attrs];
+ const domSpec = ["aside", { class: "quote", ...quoteDataAttrs(node) }];
if (username) {
domSpec.push([
@@ -181,7 +291,7 @@ const extension = {
handleClickOn(view, pos, node, nodePos, event) {
if (
node.type.name === "quote" &&
- event.target.classList.contains("title")
+ event.target.closest("aside.quote > .title")
) {
view.dispatch(
view.state.tr.setSelection(
diff --git a/frontend/discourse/tests/helpers/rich-editor-helper.gjs b/frontend/discourse/tests/helpers/rich-editor-helper.gjs
index 33dae210fee..63d7359322c 100644
--- a/frontend/discourse/tests/helpers/rich-editor-helper.gjs
+++ b/frontend/discourse/tests/helpers/rich-editor-helper.gjs
@@ -2,7 +2,8 @@ import { tracked } from "@glimmer/tracking";
import { click, render, settled, waitFor } from "@ember/test-helpers";
import DEditor from "discourse/ui-kit/d-editor";
-export async function setupRichEditor(assert, markdown, multiToggle = false) {
+export async function setupRichEditor(assert, markdown, opts = {}) {
+ const { multiToggle = false, markdownOptions } = opts;
const self = new (class {
@tracked value = markdown;
@tracked view;
@@ -17,6 +18,7 @@ export async function setupRichEditor(assert, markdown, multiToggle = false) {
@value={{self.value}}
@processPreview={{false}}
@onSetup={{handleSetup}}
+ @markdownOptions={{markdownOptions}}
/>
</template>
);
@@ -76,13 +78,9 @@ export async function testMarkdown(
markdown,
expectedHtml,
expectedMarkdown,
- multiToggle = false
+ opts = {}
) {
- const [editorClass, html] = await setupRichEditor(
- assert,
- markdown,
- multiToggle
- );
+ const [editorClass, html] = await setupRichEditor(assert, markdown, opts);
if (typeof expectedHtml === "function") {
expectedHtml(assert);
diff --git a/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.js b/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.js
index 9293ca50c10..bab26ed2922 100644
--- a/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.js
+++ b/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.js
@@ -52,7 +52,9 @@ module(
],
}).forEach(([name, [markdown, html, expectedMarkdown]]) => {
test(name, async function (assert) {
- await testMarkdown(assert, markdown, html, expectedMarkdown, true);
+ await testMarkdown(assert, markdown, html, expectedMarkdown, {
+ multiToggle: true,
+ });
});
});
@@ -73,7 +75,7 @@ module(
);
},
"```\nconsole.log('Hello, world!');\n```",
- true
+ { multiToggle: true }
);
});
diff --git a/frontend/discourse/tests/integration/components/prosemirror-editor/quote-test.js b/frontend/discourse/tests/integration/components/prosemirror-editor/quote-test.js
index ed0e82b21fb..f9c43a91089 100644
--- a/frontend/discourse/tests/integration/components/prosemirror-editor/quote-test.js
+++ b/frontend/discourse/tests/integration/components/prosemirror-editor/quote-test.js
@@ -1,6 +1,10 @@
+import { click, find, settled, triggerKeyEvent } from "@ember/test-helpers";
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
-import { testMarkdown } from "discourse/tests/helpers/rich-editor-helper";
+import {
+ setupRichEditor,
+ testMarkdown,
+} from "discourse/tests/helpers/rich-editor-helper";
module(
"Integration | Component | prosemirror-editor - quote extension",
@@ -48,5 +52,154 @@ module(
await testMarkdown(assert, markdown, html, expectedMarkdown);
});
});
+
+ test("avatar from the host editor's topic", async function (assert) {
+ const [editor] = await setupRichEditor(
+ assert,
+ `[quote="Full Name, post:123, topic:456, username:quoted_user"]\nQuoted text.\n\n[/quote]`,
+ {
+ markdownOptions: {
+ lookupAvatarTemplateByPostNumber: (postNumber, topicId) =>
+ postNumber === 123 && topicId === 456
+ ? "/images/avatar/{size}.png"
+ : null,
+ },
+ }
+ );
+
+ assert
+ .dom("aside.quote .title img.avatar")
+ .hasAttribute(
+ "src",
+ /^\/images\/avatar\/\d+\.png$/,
+ "the avatar is rendered at a resolved size"
+ );
+ assert
+ .dom("aside.quote .title")
+ .hasText("Full Name:", "the display name is shown");
+
+ assert.strictEqual(
+ editor.value,
+ `[quote="Full Name, post:123, topic:456, username:quoted_user"]\nQuoted text.\n\n[/quote]\n\n`,
+ "avatar does not leak into the serialized markdown"
+ );
+ });
+
+ test("no avatar when the quoted post is not in the topic", async function (assert) {
+ await setupRichEditor(
+ assert,
+ `[quote="User, post:99, topic:11"]\nQuoted text.\n\n[/quote]`,
+ {
+ markdownOptions: {
+ lookupAvatarTemplateByPostNumber: () => undefined,
+ },
+ }
+ );
+
+ assert
+ .dom("aside.quote .title img.avatar")
+ .doesNotExist("no avatar is rendered for an unresolved post");
+ assert
+ .dom("aside.quote .title")
+ .hasText("User:", "the username is still shown");
+ });
+
+ test("quote without a username renders no title", async function (assert) {
+ const [editor] = await setupRichEditor(
+ assert,
+ `[quote="removed_user"]\nQuoted text.\n\n[/quote]`
+ );
+
+ const { view } = editor;
+ // the quote node sits at the document root in this fixture
+ view.dispatch(
+ view.state.tr.setNodeMarkup(0, null, {
+ ...view.state.doc.nodeAt(0).attrs,
+ username: null,
+ })
+ );
+ await settled();
+
+ assert
+ .dom("aside.quote .title")
+ .doesNotExist("the header is removed with the username");
+ assert
+ .dom("aside.quote blockquote")
+ .hasText("Quoted text.", "the quoted content is kept");
+ });
+
+ test("quote can be selected and removed", async function (assert) {
+ await setupRichEditor(assert, `[quote="User"]\nQuoted text.\n\n[/quote]`);
+
+ await click("aside.quote .title");
+
+ assert
+ .dom("aside.quote")
+ .hasClass("ProseMirror-selectednode", "the quote is selected");
+
+ await triggerKeyEvent(".ProseMirror", "keydown", "Backspace");
+
+ assert.dom("aside.quote").doesNotExist("the selected quote is removed");
+ });
+
+ test("the header is not rebuilt while typing in the quote", async function (assert) {
+ const [editor] = await setupRichEditor(
+ assert,
+ `[quote="User, post:1, topic:2"]\nText.\n\n[/quote]`,
+ {
+ markdownOptions: {
+ lookupAvatarTemplateByPostNumber: () => "/a/{size}.png",
+ },
+ }
+ );
+
+ const title = find("aside.quote .title");
+ const avatar = find("aside.quote .title img");
+
+ const { view } = editor;
+ view.dispatch(view.state.tr.insertText("x", 3));
+ await settled();
+
+ assert.strictEqual(
+ title,
+ find("aside.quote .title"),
+ "the title element is reused"
+ );
+ assert.strictEqual(
+ avatar,
+ find("aside.quote .title img"),
+ "the avatar element is reused"
+ );
+ });
+
+ test("a hostile avatar template cannot inject markup", async function (assert) {
+ await setupRichEditor(
+ assert,
+ `[quote="User, post:1, topic:2"]\nQuoted text.\n\n[/quote]`,
+ {
+ markdownOptions: {
+ lookupAvatarTemplateByPostNumber: () =>
+ `/a/{size}.png" onerror="throw new Error('injected')`,
+ },
+ }
+ );
+
+ assert
+ .dom("aside.quote .title img.avatar")
+ .doesNotHaveAttribute("onerror", "the template cannot add attributes");
+ assert
+ .dom("aside.quote .title script")
+ .doesNotExist("the template cannot add elements");
+ });
+
+ test("quote survives repeated node view teardown", async function (assert) {
+ await testMarkdown(
+ assert,
+ `[quote="User"]\nQuoted text.\n\n[/quote]`,
+ `<aside class="quote" data-username="User" data-full="false"><div class="title">User:</div><blockquote><p>Quoted text.</p></blockquote></aside>`,
+ `[quote="User"]\nQuoted text.\n\n[/quote]\n\n`,
+ { multiToggle: true }
+ );
+ });
}
);