Skip to content

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

DEV: simplify composer mentions plugin code (#33174)

David Battersby16f555b477ff
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.js
index 62776d31bdd..748b32135fb 100644
--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.js
+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/mention.js
@@ -4,17 +4,12 @@ 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: {
mention: {
- attrs: { name: {} },
+ attrs: { name: {}, valid: { default: true } },
inline: true,
group: "inline",
draggable: true,
@@ -24,20 +19,46 @@ const extension = {
tag: "a.mention",
preserveWhitespace: "full",
getAttrs: (dom) => {
- return { name: dom.getAttribute("data-name") };
+ return {
+ name: dom.getAttribute("data-name"),
+ valid: dom.getAttribute("data-valid"),
+ };
},
},
],
toDOM: (node) => {
return [
"a",
- { class: "mention", "data-name": node.attrs.name },
+ {
+ class: "mention",
+ "data-name": node.attrs.name,
+ "data-valid": node.attrs.valid,
+ },
`@${node.attrs.name}`,
];
},
},
},
+ 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",
@@ -67,99 +88,59 @@ const extension = {
},
plugins({ pmState: { Plugin, PluginKey } }) {
- const plugin = new PluginKey("mention");
+ const key = new PluginKey("mention");
return new Plugin({
- key: plugin,
+ key,
view() {
return {
update(view) {
- if (!view._existingMentionsValidated) {
- this.processExistingMentions(view);
- view._existingMentionsValidated = true;
+ this.processMentionNodes(view);
+ },
+ processMentionNodes(view) {
+ const mentionNames = [];
+ const mentionNodes = [];
+
+ if (this._processingMentionNodes) {
+ return;
}
- this.processNewMentions(view);
- },
- processExistingMentions(view) {
- const nodeList = [];
+ this._processingMentionNodes = true;
view.state.doc.descendants((node, pos) => {
- if (node.type.name === "mention") {
- nodeList.push({ node, pos });
- PENDING_MENTIONS.add(node.attrs.name);
+ if (node.type.name !== "mention" || !node.attrs.valid) {
+ return;
}
- });
- if (!nodeList.length) {
- return;
- }
+ const name = node.attrs.name;
+ mentionNames.push(name);
+ mentionNodes.push({ name, node, pos });
+ });
// process in reverse to avoid issues with position shifts
- nodeList.sort((a, b) => b.pos - a.pos);
+ mentionNodes.sort((a, b) => b.pos - a.pos);
const invalidateMentions = async () => {
- await fetchMentions([...PENDING_MENTIONS]);
+ await fetchMentions(mentionNames);
- for (const item of nodeList) {
- const { node, pos } = item;
- const name = node.attrs.name;
+ for (const mentionNode of mentionNodes) {
+ const { name, node, pos } = mentionNode;
if (VALID_MENTIONS.has(name)) {
continue;
}
view.dispatch(
- view.state.tr
- .delete(pos, pos + node.nodeSize)
- .insertText(`@${name}`, pos)
+ view.state.tr.setNodeMarkup(pos, null, {
+ ...node.attrs,
+ valid: false,
+ })
);
}
};
- 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();
+ invalidateMentions().then(() => {
+ this._processingMentionNodes = false;
});
},
};
@@ -168,36 +149,13 @@ const extension = {
},
};
-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)
- );
+ // only fetch new mentions that are not already validated
+ names = names.uniq().filter((name) => {
+ return !VALID_MENTIONS.has(name) && !INVALID_MENTIONS.has(name);
+ });
- if (names.length === 0) {
+ if (!names.length) {
return;
}
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.js
index 5a0cddd4c85..e9f3c7c9a0e 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
@@ -26,32 +26,32 @@ module(
const testCases = {
mention: [
"@eviltrout",
- '<p><a class="mention" data-name="eviltrout" contenteditable="false" draggable="true">@eviltrout</a></p>',
+ '<p><a class="mention" data-name="eviltrout" data-valid="true" contenteditable="false" draggable="true">@eviltrout</a></p>',
"@eviltrout",
],
"text with mention": [
"Hello @eviltrout",
- '<p>Hello <a class="mention" data-name="eviltrout" contenteditable="false" draggable="true">@eviltrout</a></p>',
+ '<p>Hello <a class="mention" data-name="eviltrout" data-valid="true" contenteditable="false" draggable="true">@eviltrout</a></p>',
"Hello @eviltrout",
],
"mention after heading": [
"## Hello\n\n@eviltrout",
- '<h2>Hello</h2><p><a class="mention" data-name="eviltrout" contenteditable="false" draggable="true">@eviltrout</a></p>',
+ '<h2>Hello</h2><p><a class="mention" data-name="eviltrout" data-valid="true" 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>',
+ '<p>Maybe <a class="mention" data-name="support" data-valid="true" 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>',
+ '<p>Hey <a class="mention" data-name="john" data-valid="true" contenteditable="false" draggable="true">@john</a>, I think <a class="mention" data-name="support" data-valid="true" 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>",
+ '<p>Hello <a class="mention" data-name="invalid" data-valid="false" contenteditable="false" draggable="true">@invalid</a>, how are you?</p>',
"Hello @invalid, how are you?",
],
};
diff --git a/app/assets/stylesheets/common/foundation/mixins.scss b/app/assets/stylesheets/common/foundation/mixins.scss
index 51a5b4d74d6..ebeda0400ac 100644
--- a/app/assets/stylesheets/common/foundation/mixins.scss
+++ b/app/assets/stylesheets/common/foundation/mixins.scss
@@ -258,6 +258,11 @@ $hpad: 0.65em;
text-wrap: nowrap;
line-height: 1;
+ &[data-valid="false"] {
+ background: unset;
+ padding: 0;
+ }
+
&.--bot {
background: var(--success-low);
}
diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rb
index 038fc3145eb..1844b653991 100644
--- a/spec/system/composer/prosemirror_editor_spec.rb
+++ b/spec/system/composer/prosemirror_editor_spec.rb
@@ -863,11 +863,11 @@ describe "Composer - ProseMirror editor", type: :system do
composer.type_content("Hey @#{user.username} ")
- expect(rich).to have_css("a.mention", text: user.username)
+ expect(rich).to have_css("a.mention[data-valid='true']", text: user.username)
composer.type_content("and @invalid_user - how are you?")
- expect(rich).to have_no_css("a.mention", text: "@invalid_user")
+ expect(rich).to have_css("a.mention[data-valid='false']", text: "@invalid_user")
composer.toggle_rich_editor
@@ -881,8 +881,8 @@ describe "Composer - ProseMirror editor", type: :system do
composer.toggle_rich_editor
- expect(rich).to have_css("a.mention", text: user.username)
- expect(rich).to have_no_css("a.mention", text: "@unknown")
+ expect(rich).to have_css("a.mention[data-valid='true']", text: user.username)
+ expect(rich).to have_css("a.mention[data-valid='false']", text: "@unknown")
end
end