A platform for community discussion. Free, open, simple.
FEATURE: Validate Mentions in Rich Text Editor (#32879)
David Battersbyaf0a65eefdf6
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.jsindex 4f116d912d0..62776d31bdd 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.js@@ -1,6 +1,15 @@import { mentionRegex } from "pretty-text/mentions";+import { ajax } from "discourse/lib/ajax";import { isBoundary } from "discourse/static/prosemirror/lib/markdown-it";+const VALID_MENTIONS = new Set();+const INVALID_MENTIONS = new Set();+const PENDING_MENTIONS = new Set();+const MENTION_REGEXP = new RegExp(+ `(^|\\W)(${mentionRegex().source})(?=\\s|$)`,+ "g"+);+/** @type {RichEditorExtension} */const extension = {nodeSpec: {@@ -29,24 +38,6 @@ const extension = {},},- inputRules: {- // TODO(renato): pass unicodeUsernames?- match: new RegExp(`(^|\\W)(${mentionRegex().source}) $`),- handler: (state, match, start, end) => {- const { $from } = state.selection;- if ($from.nodeBefore?.type === state.schema.nodes.mention) {- return null;- }- const mentionStart = start + match[1].length;- const name = match[2].slice(1);- return state.tr.replaceWith(mentionStart, end, [- state.schema.nodes.mention.create({ name }),- state.schema.text(" "),- ]);- },- options: { undoable: false },- },-parse: {mention: {block: "mention",@@ -74,6 +65,153 @@ const extension = {}},},++ plugins({ pmState: { Plugin, PluginKey } }) {+ const plugin = new PluginKey("mention");++ return new Plugin({+ key: plugin,+ view() {+ return {+ update(view) {+ if (!view._existingMentionsValidated) {+ this.processExistingMentions(view);+ view._existingMentionsValidated = true;+ }++ this.processNewMentions(view);+ },+ processExistingMentions(view) {+ const nodeList = [];++ view.state.doc.descendants((node, pos) => {+ if (node.type.name === "mention") {+ nodeList.push({ node, pos });+ PENDING_MENTIONS.add(node.attrs.name);+ }+ });++ if (!nodeList.length) {+ return;+ }++ // process in reverse to avoid issues with position shifts+ nodeList.sort((a, b) => b.pos - a.pos);++ const invalidateMentions = async () => {+ await fetchMentions([...PENDING_MENTIONS]);++ for (const item of nodeList) {+ const { node, pos } = item;+ const name = node.attrs.name;++ if (VALID_MENTIONS.has(name)) {+ continue;+ }++ view.dispatch(+ view.state.tr+ .delete(pos, pos + node.nodeSize)+ .insertText(`@${name}`, pos)+ );+ }+ };++ invalidateMentions();+ },+ processNewMentions(view) {+ const tr = view.state.tr;++ if (!isBoundary(tr.doc.textContent.slice(-1), 0)) {+ return;+ }++ view.state.doc.descendants((node, pos) => {+ if (node.type.name !== "text") {+ return;+ }++ const mentionList = getMentionsFromTextNode(node, pos);++ if (!mentionList.length) {+ return;+ }++ const processMentions = async () => {+ await fetchMentions([...PENDING_MENTIONS]);++ for (const item of mentionList) {+ const { name, start, end } = item;++ if (!VALID_MENTIONS.has(name)) {+ continue;+ }++ view.dispatch(+ tr.replaceWith(+ start,+ end,+ view.state.schema.nodes.mention.create({+ name,+ })+ )+ );+ }+ };++ processMentions();+ });+ },+ };+ },+ });+ },};+function getMentionsFromTextNode(node, pos) {+ let mentionList = [];+ let match;++ while ((match = MENTION_REGEXP.exec(node.text)) !== null) {+ const name = match[2].slice(1);++ if (VALID_MENTIONS.has(name) || INVALID_MENTIONS.has(name)) {+ continue;+ } else if (!PENDING_MENTIONS.has(name)) {+ PENDING_MENTIONS.add(name);+ }++ const start = pos + match.index + match[1].length;+ const end = start + match[2].length;++ mentionList.push({ name, start, end });+ }++ return mentionList;+}++async function fetchMentions(names) {+ PENDING_MENTIONS.clear();++ names = names.filter(+ (name) => !VALID_MENTIONS.has(name) && !INVALID_MENTIONS.has(name)+ );++ if (names.length === 0) {+ return;+ }++ const response = await ajax("/composer/mentions", {+ data: { names },+ });++ names.forEach((name) => {+ if (response.users.includes(name) || response.groups[name]) {+ VALID_MENTIONS.add(name);+ } else {+ INVALID_MENTIONS.add(name);+ }+ });+}+export default extension;diff --git a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/mention-test.js b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/mention-test.jsindex 1f0667bd513..5a0cddd4c85 100644--- a/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/mention-test.js+++ b/app/assets/javascripts/discourse/tests/integration/components/prosemirror-editor/mention-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,51 @@ module(function (hooks) {setupRenderingTest(hooks);+ hooks.beforeEach(function () {+ pretender.get("/composer/mentions", () =>+ response({+ users: ["eviltrout", "john"],+ user_reasons: {},+ groups: {+ support: { user_count: 1 },+ unmentionable: { user_count: 5 },+ },+ group_reasons: { unmentionable: "not_mentionable" },+ max_users_notified_per_group_mention: 100,+ })+ );+ });+const testCases = {mention: [- "@hello",- '<p><a class="mention" data-name="hello" contenteditable="false" draggable="true">@hello</a></p>',- "@hello",+ "@eviltrout",+ '<p><a class="mention" data-name="eviltrout" contenteditable="false" draggable="true">@eviltrout</a></p>',+ "@eviltrout",],"text with mention": [- "Hello @dude",- '<p>Hello <a class="mention" data-name="dude" contenteditable="false" draggable="true">@dude</a></p>',- "Hello @dude",+ "Hello @eviltrout",+ '<p>Hello <a class="mention" data-name="eviltrout" contenteditable="false" draggable="true">@eviltrout</a></p>',+ "Hello @eviltrout",],"mention after heading": [- "## Hello\n\n@dude",- '<h2>Hello</h2><p><a class="mention" data-name="dude" contenteditable="false" draggable="true">@dude</a></p>',- "## Hello\n\n@dude",+ "## Hello\n\n@eviltrout",+ '<h2>Hello</h2><p><a class="mention" data-name="eviltrout" contenteditable="false" draggable="true">@eviltrout</a></p>',+ "## Hello\n\n@eviltrout",+ ],+ "group mention": [+ "Maybe @support can help",+ '<p>Maybe <a class="mention" data-name="support" contenteditable="false" draggable="true">@support</a> can help</p>',+ "Maybe @support can help",+ ],+ "group and user mention": [+ "Hey @john, I think @support can help here",+ '<p>Hey <a class="mention" data-name="john" contenteditable="false" draggable="true">@john</a>, I think <a class="mention" data-name="support" contenteditable="false" draggable="true">@support</a> can help here</p>',+ "Hey @john, I think @support can help here",+ ],+ "invalid mention": [+ "Hello @invalid, how are you?",+ "<p>Hello @invalid, how are you?</p>",+ "Hello @invalid, how are you?",],};diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rbindex d64ecd8cf96..be6cd31baeb 100644--- a/spec/system/composer/prosemirror_editor_spec.rb+++ b/spec/system/composer/prosemirror_editor_spec.rb@@ -843,4 +843,45 @@ describe "Composer - ProseMirror editor", type: :system doexpect(composer).to have_value("[link text :heart:](https://example.com)")endend++ describe "with mentions" do+ fab!(:post)+ fab!(:topic) { post.topic }++ before do+ Draft.set(+ user,+ topic.draft_key,+ 0,+ { reply: "hey @#{user.username} and @unknown - how are you?" }.to_json,+ )+ end++ it "validates manually typed mentions" do+ open_composer_and_toggle_rich_editor++ composer.type_content("Hey @#{user.username} ")++ expect(rich).to have_css("a.mention", text: user.username)++ composer.type_content("and @invalid_user - how are you?")++ expect(rich).to have_no_css("a.mention", text: "@invalid_user")++ composer.toggle_rich_editor++ expect(composer).to have_value("Hey @#{user.username} and @invalid_user - how are you?")+ end++ it "validates mentions in drafts" do+ page.visit("/t/#{topic.id}")++ expect(composer).to be_opened++ composer.toggle_rich_editor++ expect(rich).to have_css("a.mention", text: user.username)+ expect(rich).to have_no_css("a.mention", text: "@unknown")+ end+ endend