Skip to content

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

FEATURE: validate hashtags in composer rich text editor (#33272)

David Battersbye89e2bb961e0
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs b/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs
index c0c2b6a056c..8d27d641db5 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/components/prosemirror-editor.gjs
@@ -68,6 +68,7 @@ export default class ProsemirrorEditor extends Component {
@service capabilities;
@service modal;
@service toasts;
+ @service site;
schema = createSchema(this.extensions, this.args.includeDefault);
view;
@@ -99,6 +100,7 @@ export default class ProsemirrorEditor extends Component {
capabilities: this.capabilities,
modal: this.modal,
toasts: this.toasts,
+ site: this.site,
replaceToolbar: this.args.replaceToolbar,
}),
};
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/hashtag.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/hashtag.js
index 0ac0ce0faf0..84bd684b956 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/hashtag.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/hashtag.js
@@ -1,10 +1,19 @@
+import { ajax } from "discourse/lib/ajax";
+import { getHashtagTypeClasses } from "discourse/lib/hashtag-type-registry";
import { isBoundary } from "discourse/static/prosemirror/lib/markdown-it";
+const VALID_HASHTAGS = new Map();
+const INVALID_HASHTAGS = new Set();
+
/** @type {RichEditorExtension} */
const extension = {
nodeSpec: {
hashtag: {
- attrs: { name: {} },
+ attrs: {
+ name: {},
+ processed: { default: false },
+ valid: { default: true },
+ },
inline: true,
group: "inline",
draggable: true,
@@ -14,14 +23,23 @@ const extension = {
tag: "a.hashtag-cooked",
preserveWhitespace: "full",
getAttrs: (dom) => {
- return { name: dom.getAttribute("data-name") };
+ return {
+ name: dom.getAttribute("data-name"),
+ processed: dom.getAttribute("data-processed"),
+ valid: dom.getAttribute("data-valid"),
+ };
},
},
],
toDOM: (node) => {
return [
"a",
- { class: "hashtag-cooked", "data-name": node.attrs.name },
+ {
+ class: "hashtag-cooked",
+ "data-name": node.attrs.name,
+ "data-processed": node.attrs.processed,
+ "data-valid": node.attrs.valid,
+ },
`#${node.attrs.name}`,
];
},
@@ -82,6 +100,109 @@ const extension = {
}
},
},
+ plugins({ pmState: { Plugin, PluginKey }, getContext }) {
+ const key = new PluginKey("hashtag");
+
+ return new Plugin({
+ key,
+ view() {
+ return {
+ update(view) {
+ this.processHashtags(view);
+ },
+ processHashtags(view) {
+ const hashtagNames = [];
+ const hashtagNodes = [];
+
+ view.state.doc.descendants((node, pos) => {
+ if (
+ node.type.name !== "hashtag" ||
+ node.attrs.processed ||
+ !node.attrs.valid
+ ) {
+ return;
+ }
+
+ const name = node.attrs.name;
+ hashtagNodes.push({ name, node, pos });
+ hashtagNames.push(name);
+ });
+
+ if (!hashtagNodes.length) {
+ return;
+ }
+
+ // process in reverse to avoid issues with position shifts
+ hashtagNodes.sort((a, b) => b.pos - a.pos);
+
+ const updateHashtags = async () => {
+ await fetchHashtags(hashtagNames, getContext());
+
+ for (const hashtagNode of hashtagNodes) {
+ const { name, node, pos } = hashtagNode;
+ const validHashtag = VALID_HASHTAGS.get(name.toLowerCase());
+
+ // check if node still exists at this position before updating
+ if (view.state.doc.nodeAt(pos)?.type !== node.type) {
+ continue;
+ }
+
+ view.dispatch(
+ view.state.tr.setNodeMarkup(pos, null, {
+ ...node.attrs,
+ processed: true,
+ valid: !!validHashtag,
+ })
+ );
+
+ const domNode = view.nodeDOM(pos);
+ if (!validHashtag || !domNode) {
+ continue;
+ }
+
+ // decorate valid hashtags based on their type
+ const tagText = validHashtag?.text || name;
+ const hashtagTypeClass =
+ getHashtagTypeClasses()[validHashtag.type];
+ const hashtagIconHTML = hashtagTypeClass
+ .generateIconHTML(validHashtag)
+ .trim();
+
+ domNode.innerHTML = `${hashtagIconHTML}${tagText}`;
+ }
+ };
+
+ updateHashtags();
+ },
+ };
+ },
+ });
+ },
};
+async function fetchHashtags(hashtags, context) {
+ const slugs = hashtags.filter(
+ (tag) => !VALID_HASHTAGS.has(tag) && !INVALID_HASHTAGS.has(tag)
+ );
+
+ if (!slugs.length) {
+ return;
+ }
+
+ const order = context.site.hashtag_configurations["topic-composer"];
+ const response = await ajax("/hashtags", { data: { slugs, order } });
+
+ const validTags = Object.values(response || {})
+ .flat()
+ .filter(Boolean);
+
+ validTags.forEach((tag) => {
+ VALID_HASHTAGS.set(tag.ref, tag);
+ hashtags.splice(hashtags.indexOf(tag.ref), 1);
+ });
+
+ // mark remaining hashtags as invalid to avoid repeated requests
+ hashtags.forEach((tag) => INVALID_HASHTAGS.add(tag));
+}
+
export default extension;
diff --git a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/hashtag-test.js b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/hashtag-test.js
index c28c0007ff2..c9c711df339 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/hashtag-test.js
+++ b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/hashtag-test.js
@@ -1,5 +1,6 @@
import { module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
import { testMarkdown } from "discourse/tests/helpers/rich-editor-helper";
module(
@@ -7,21 +8,78 @@ module(
function (hooks) {
setupRenderingTest(hooks);
+ hooks.beforeEach(function () {
+ pretender.get("/hashtags", () =>
+ response({
+ categories: [
+ {
+ type: "category",
+ ref: "product",
+ style_type: "square",
+ id: 2,
+ },
+ {
+ type: "category",
+ ref: "coffee",
+ emoji: "coffee",
+ style_type: "emoji",
+ id: 3,
+ },
+ {
+ type: "category",
+ ref: "discuss",
+ icon: "comment",
+ style_type: "icon",
+ id: 4,
+ },
+ ],
+ tags: [
+ {
+ type: "tag",
+ ref: "dev",
+ icon: "tag",
+ id: 1,
+ },
+ ],
+ })
+ );
+ });
+
const testCases = {
hashtag: [
- "#hello",
- '<p><a class="hashtag-cooked" data-name="hello" contenteditable="false" draggable="true">#hello</a></p>',
- "#hello",
+ "#product",
+ '<p><a class="hashtag-cooked" data-name="product" data-processed="true" data-valid="true" contenteditable="false" draggable="true"><span class=\"hashtag-category-square hashtag-color--category-2\"></span>product</a></p>',
+ "#product",
],
"text with hashtag": [
- "Hello #category",
- '<p>Hello <a class="hashtag-cooked" data-name="category" contenteditable="false" draggable="true">#category</a></p>',
- "Hello #category",
+ "Hello #product",
+ '<p>Hello <a class="hashtag-cooked" data-name="product" data-processed="true" data-valid="true" contenteditable="false" draggable="true"><span class=\"hashtag-category-square hashtag-color--category-2\"></span>product</a></p>',
+ "Hello #product",
],
"hashtag after heading": [
- "## Hello\n\n#category",
- '<h2>Hello</h2><p><a class="hashtag-cooked" data-name="category" contenteditable="false" draggable="true">#category</a></p>',
- "## Hello\n\n#category",
+ "## Hello\n\n#product",
+ '<h2>Hello</h2><p><a class="hashtag-cooked" data-name="product" data-processed="true" data-valid="true" contenteditable="false" draggable="true"><span class=\"hashtag-category-square hashtag-color--category-2\"></span>product</a></p>',
+ "## Hello\n\n#product",
+ ],
+ "invalid hashtag": [
+ "Hello #invalid, how are you?",
+ '<p>Hello <a class="hashtag-cooked" data-name="invalid" data-processed="true" data-valid="false" contenteditable="false" draggable="true">#invalid</a>, how are you?</p>',
+ "Hello #invalid, how are you?",
+ ],
+ "with regular tags": [
+ "Hello #dev",
+ '<p>Hello <a class="hashtag-cooked" data-name="dev" data-processed="true" data-valid="true" contenteditable="false" draggable="true"><svg class=\"fa d-icon d-icon-tag svg-icon hashtag-color--tag-1 svg-string\" aria-hidden=\"true\" xmlns=\"http://www.w3.org/2000/svg\"><use href=\"#tag\"></use></svg>dev</a></p>',
+ "Hello #dev",
+ ],
+ "hashtag with emoji": [
+ "Time for #coffee",
+ '<p>Time for <a class="hashtag-cooked" data-name="coffee" data-processed="true" data-valid="true" contenteditable="false" draggable="true"><span class=\"hashtag-category-emoji hashtag-color--category-3\"><img width=\"20\" height=\"20\" src=\"/images/emoji/twitter/coffee.png?v=14\" title=\"coffee\" alt=\"coffee\" class=\"emoji\"></span>coffee</a></p>',
+ "Time for #coffee",
+ ],
+ "hashtag with icon": [
+ "Lets #discuss",
+ '<p>Lets <a class="hashtag-cooked" data-name="discuss" data-processed="true" data-valid="true" contenteditable="false" draggable="true"><span class=\"hashtag-category-icon hashtag-color--category-4\"><svg class=\"fa d-icon d-icon-comment svg-icon svg-string\" aria-hidden=\"true\" xmlns=\"http://www.w3.org/2000/svg\"><use href=\"#comment\"></use></svg></span>discuss</a></p>',
+ "Lets #discuss",
],
};