A platform for community discussion. Free, open, simple.
FEATURE: auto-link/unlink url-like words on rich editor when typing (#32163)
Renato Atilio6fb8f3ff7afe
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link.jsindex 9f7f371b926..2c922b6aa8c 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/link.js@@ -1,3 +1,9 @@+import { ReplaceAroundStep, ReplaceStep } from "prosemirror-transform";+import { getChangedRanges } from "discourse/static/prosemirror/lib/plugin-utils";++const AUTO_LINKS = ["autolink", "linkify"];+const REPLACE_STEPS = [ReplaceStep, ReplaceAroundStep];+/** @type {RichEditorExtension} */const extension = {markSpec: {@@ -112,7 +118,7 @@ const extension = {return { href: match[2], title: match[3] };}),- plugins: ({ pmState: { Plugin }, utils }) =>+ plugins: ({ pmState: { Plugin }, utils }) => [new Plugin({props: {// Auto-linkify plain-text pasted URLs@@ -159,6 +165,127 @@ const extension = {},},}),+ // plugin for auto-linking during typing+ new Plugin({+ appendTransaction(transactions, prevState, state) {+ const transaction = prevState.tr;+ transactions+ .filter((tr) => tr.docChanged && tr.getMeta("addToHistory") !== false)+ .flatMap((tr) => tr.steps)+ .forEach((step) => {+ if (REPLACE_STEPS.includes(step.constructor)) {+ transaction.step(step);+ }+ });++ const changedRanges = getChangedRanges(transaction);++ const tr = state.tr;++ changedRanges.forEach((change) => {+ let from = change.new.from;+ let to = change.new.to;+ if (from === to) {+ from = Math.max(from - 1, 0);+ to = Math.min(to + 1, state.doc.nodeSize - 2);+ }+ state.doc.nodesBetween(from, to, (node, pos) => {+ if (+ !node.isText ||+ node.marks.some(+ (mark) =>+ mark.type.name === "link" &&+ !AUTO_LINKS.includes(mark.attrs.markup)+ )+ ) {+ return true;+ }++ const text = node.text;++ const changeStart = Math.max(0, change.new.from - pos);+ const changeEnd = Math.min(text.length, change.new.to - pos);++ let wordStart = changeStart;+ while (wordStart > 0 && !utils.isWhiteSpace(text[wordStart - 1])) {+ wordStart--;+ }+ let wordEnd = changeEnd;+ while (+ wordEnd < text.length &&+ !utils.isWhiteSpace(text[wordEnd])+ ) {+ wordEnd++;+ }++ const textSlice = text.slice(wordStart, wordEnd);++ const nodeBefore = state.doc.nodeAt(pos - 1);+ let textBefore = "";+ if (+ wordStart === 0 &&+ nodeBefore?.isText &&+ !utils.isWhiteSpace(+ nodeBefore.text[nodeBefore.text.length - 1]+ ) &&+ !utils.isWhiteSpace(text[0]) &&+ nodeBefore.marks.length === 1 &&+ nodeBefore.marks.some(+ (mark) =>+ mark.type.name === "link" &&+ AUTO_LINKS.includes(mark.attrs.markup)+ )+ ) {+ textBefore = nodeBefore.text;+ }++ const nodeAfter = state.doc.nodeAt(pos + node.nodeSize);+ let textAfter = "";+ if (+ wordEnd === text.length &&+ nodeAfter?.isText &&+ !utils.isWhiteSpace(text[text.length - 1]) &&+ !utils.isWhiteSpace(nodeAfter.text[0]) &&+ nodeAfter.marks.length === 1 &&+ nodeAfter.marks.some(+ (mark) =>+ mark.type.name === "link" &&+ AUTO_LINKS.includes(mark.attrs.markup)+ )+ ) {+ textAfter = nodeAfter.text;+ }++ const fullText = textBefore + textSlice + textAfter;++ const startPos = pos + wordStart - textBefore.length;++ tr.removeMark(+ startPos,+ startPos + fullText.length,+ state.schema.marks.link+ );++ utils+ .getLinkify()+ .match(fullText)+ ?.forEach((match) => {+ tr.addMark(+ startPos + match.index,+ startPos + match.index + match.raw.length,+ state.schema.marks.link.create({+ href: match.url,+ markup: "linkify",+ })+ );+ });+ });+ });++ return tr;+ },+ }),+ ],};function addLinkMark(view, href) {diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/onebox.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/onebox.jsindex 9d303d9b52c..8f930314c99 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/onebox.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/onebox.js@@ -60,7 +60,7 @@ const extension = {{class: "inline-onebox",href: node.attrs.url,- contentEditable: false,+ contentEditable: true,},node.attrs.title,];@@ -167,10 +167,11 @@ const extension = {const decorations = [];tr.doc.descendants((node, pos) => {const link = node.marks.find((mark) => mark.type.name === "link");+if (link?.attrs.markup === "linkify" &&- link?.attrs.href === node.textContent &&- set.find(pos, pos + node.nodeSize).length === 0+ set.find(pos, pos + node.nodeSize).length === 0 &&+ isOutsideSelection(pos, node.nodeSize, tr)) {const resolvedPos = tr.doc.resolve(pos);const isAtRoot = resolvedPos.depth === 1;@@ -293,7 +294,7 @@ const extension = {const hasMatchingLink = nodeAtPos?.marks.find((mark) =>mark.type.name === "link" &&- mark.attrs.href === decoration.spec.oneboxUrl+ mark.attrs.href.endsWith(decoration.spec.oneboxUrl));if (!isTextNode || !hasMatchingLink) {@@ -350,6 +351,31 @@ const extension = {},};+function isOutsideSelection(from, to, tr) {+ const { selection, doc } = tr;++ const nodeEnd = from + to;++ if (selection.from <= nodeEnd && selection.to >= from) {+ return false;+ }++ const text = doc.textBetween(+ selection.to < from ? selection.to : nodeEnd,+ selection.to < from ? from : selection.from,+ " ",+ " "+ );++ for (let i = 0; i < text.length; i++) {+ if (isWhiteSpace(text[i])) {+ return true;+ }+ }++ return false;+}+// Dummy element to pass to the oneboxer// To avoid this, we need to refactor both oneboxer APIsconst dummyElement = {diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.jsindex abc32460012..e0e0093b76d 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/plugin-utils.js@@ -13,10 +13,6 @@ export function markInputRule(regexp, markType, getAttrs) {const attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;const tr = state.tr;- if (state.doc.rangeHasMark(start, end, markType)) {- return null;- }-if (match[1]) {let textStart = start + match[0].indexOf(match[1]);let textEnd = textStart + match[1].length;diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rbindex 8cb260e240e..24b8155b936 100644--- a/spec/system/composer/prosemirror_editor_spec.rb+++ b/spec/system/composer/prosemirror_editor_spec.rb@@ -213,7 +213,7 @@ describe "Composer - ProseMirror editor", type: :system docomposer.type_content("Check out this link ")cdp.write_clipboard("https://example.com")page.send_keys([PLATFORM_KEY_MODIFIER, "v"])- composer.type_content(" in the middle of text")+ composer.type_content(" ").type_content("in the middle of text")expect(rich).to have_css("a.inline-onebox[href='https://example.com']",@@ -249,7 +249,7 @@ describe "Composer - ProseMirror editor", type: :system docomposer.type_content("Some text ")cdp.write_clipboard("https://example.com")page.send_keys([PLATFORM_KEY_MODIFIER, "v"])- composer.type_content(" more text")+ composer.type_content(" ").type_content("more text")expect(rich).to have_no_css("div.onebox-wrapper")expect(rich).to have_css("a.inline-onebox", text: "Example Site 1")@@ -303,6 +303,7 @@ describe "Composer - ProseMirror editor", type: :system dohttps://example3.comOk, that is it https://example3.com+ After a hard breakMARKDOWNcdp.write_clipboard(markdown)page.send_keys([PLATFORM_KEY_MODIFIER, "v"])@@ -334,11 +335,12 @@ describe "Composer - ProseMirror editor", type: :system doit "creates inline oneboxes for repeated links in different paste events" docdp.allow_clipboardopen_composer_and_toggle_rich_editor- composer.type_content("Hey")+ composer.type_content("Hey ")cdp.write_clipboard("https://example.com")page.send_keys([PLATFORM_KEY_MODIFIER, "v"])- composer.type_content("and")+ composer.type_content(" ").type_content("and").type_content(" ")page.send_keys([PLATFORM_KEY_MODIFIER, "v"])+ composer.type_content("\n")expect(rich).to have_css("a.inline-onebox[href='https://example.com']",@@ -527,6 +529,36 @@ describe "Composer - ProseMirror editor", type: :system doendend+ describe "auto-linking/unlinking" do+ it "auto-links non-protocol URLs and removes the link when no longer a URL" do+ open_composer_and_toggle_rich_editor++ composer.type_content("www.example.com")++ expect(rich).to have_css("a", text: "www.example.com")++ composer.send_keys(%i[backspace backspace])++ expect(rich).to have_no_css("a")++ composer.type_content("om")++ expect(rich).to have_css("a", text: "www.example.com")+ end++ it "auto-links protocol URLs" do+ open_composer_and_toggle_rich_editor++ composer.type_content("https://example.com")++ expect(rich).to have_css("a", text: "https://example.com")++ composer.send_keys(%i[backspace backspace])++ expect(rich).to have_css("a", text: "https://example.c")+ end+ end+describe "uploads" doit "handles uploads and disables the editor toggle while uploading" doopen_composer_and_toggle_rich_editor