A platform for community discussion. Free, open, simple.
FEATURE: add onebox rich editor extension (#31691)
Renato Atilioc9518f2384f4
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/onebox.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/onebox.jsnew file mode 100644index 00000000000..9d303d9b52c--- /dev/null+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/onebox.js@@ -0,0 +1,407 @@+import {+ applyInlineOneboxes,+ cachedInlineOnebox,+} from "pretty-text/inline-oneboxer";+import { load } from "pretty-text/oneboxer";+import { ajax } from "discourse/lib/ajax";+import escapeRegExp from "discourse/lib/escape-regexp";+import { isWhiteSpace } from "discourse/static/prosemirror/lib/markdown-it";++/** @type {RichEditorExtension} */+const extension = {+ nodeSpec: {+ onebox: {+ attrs: { url: {}, html: {} },+ selectable: true,+ group: "block",+ atom: true,+ draggable: true,+ parseDOM: [+ {+ tag: "div.onebox-wrapper",+ getAttrs(dom) {+ return { url: dom.dataset.oneboxSrc, html: dom.innerHTML };+ },+ },+ {+ tag: "aside.onebox",+ getAttrs(dom) {+ return { url: dom.dataset.oneboxSrc, html: dom.outerHTML };+ },+ },+ ],+ toDOM(node) {+ const dom = document.createElement("div");+ dom.dataset.oneboxSrc = node.attrs.url;+ dom.classList.add("onebox-wrapper");+ dom.innerHTML = node.attrs.html;+ return dom;+ },+ },+ onebox_inline: {+ attrs: { url: {}, title: {} },+ inline: true,+ group: "inline",+ selectable: true,+ atom: true,+ draggable: true,+ parseDOM: [+ {+ tag: "a.inline-onebox",+ getAttrs(dom) {+ return { url: dom.getAttribute("href"), title: dom.textContent };+ },+ priority: 60,+ },+ ],+ toDOM(node) {+ return [+ "a",+ {+ class: "inline-onebox",+ href: node.attrs.url,+ contentEditable: false,+ },+ node.attrs.title,+ ];+ },+ },+ },+ serializeNode: {+ onebox(state, node) {+ state.ensureNewLine();+ state.write(`${node.attrs.url}\n\n`);+ },+ onebox_inline(state, node, parent, index) {+ if (!isWhiteSpace(state.out, state.out.length - 1)) {+ state.write(" ");+ }++ state.text(node.attrs.url);++ const nextSibling =+ parent.childCount > index + 1 ? parent.child(index + 1) : null;+ if (nextSibling?.isText && !isWhiteSpace(nextSibling.text, 0)) {+ state.write(" ");+ }+ },+ },++ plugins({+ pmState: { Plugin },+ pmView: { Decoration, DecorationSet },+ getContext,+ }) {+ const failedUrls = { full: new Set(), inline: new Set() };++ const plugin = new Plugin({+ state: {+ init() {+ return DecorationSet.empty;+ },+ apply(tr, set) {+ const meta = tr.getMeta(plugin);+ if (meta?.removeDecorations) {+ set = set.remove(meta.removeDecorations);+ }++ set = set.map(tr.mapping, tr.doc);++ if (!tr.docChanged) {+ if (meta?.inlineOneboxes) {+ const decosToUpdate = set.find(+ undefined,+ undefined,+ (spec) =>+ spec.oneboxType === "inline" &&+ spec.oneboxUrl &&+ meta.inlineOneboxes.hasOwnProperty(spec.oneboxUrl)+ );++ const newDecorations = decosToUpdate.map((decoration) =>+ Decoration.inline(+ decoration.from,+ decoration.to,+ { class: "onebox-loading", nodeName: "span" },+ {+ oneboxUrl: decoration.spec.oneboxUrl,+ oneboxType: decoration.spec.oneboxType,+ oneboxTitle: meta.inlineOneboxes[decoration.spec.oneboxUrl],+ oneboxDataLoaded: true,+ }+ )+ );++ set = set.remove(decosToUpdate).add(tr.doc, newDecorations);+ }++ if (meta?.oneboxContent) {+ const { url, html } = meta.oneboxContent;++ const decosToUpdate = set.find(+ undefined,+ undefined,+ (spec) => spec.oneboxType === "full" && spec.oneboxUrl === url+ );++ const newDecorations = decosToUpdate.map((decoration) => {+ return Decoration.inline(+ decoration.from,+ decoration.to,+ { class: "onebox-loading", nodeName: "span" },+ {+ oneboxUrl: decoration.spec.oneboxUrl,+ oneboxType: decoration.spec.oneboxType,+ oneboxDataLoaded: true,+ oneboxHtml: html,+ }+ );+ });++ set = set.remove(decosToUpdate).add(tr.doc, newDecorations);+ }++ return set;+ }++ 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+ ) {+ const resolvedPos = tr.doc.resolve(pos);+ const isAtRoot = resolvedPos.depth === 1;+ const parent = resolvedPos.parent;+ const index = resolvedPos.index();+ const prev = index > 0 ? parent.child(index - 1) : null;+ const next =+ index < parent.childCount - 1 ? parent.child(index + 1) : null;+ const isAlone =+ (!prev || prev.type.name === "hard_break") &&+ (!next || next.type.name === "hard_break");+ const isInline = !isAtRoot || !isAlone;++ const oneboxType = isInline ? "inline" : "full";++ if (!failedUrls[oneboxType].has(node.textContent)) {+ decorations.push(+ Decoration.inline(+ pos,+ pos + node.nodeSize,+ { class: "onebox-loading", nodeName: "span" },+ { oneboxUrl: node.textContent, oneboxType }+ )+ );+ }+ }+ });++ return set.add(tr.doc, decorations);+ },+ },++ props: {+ decorations(state) {+ return plugin.getState(state);+ },+ },++ view() {+ const pendingUrls = { inline: new Set(), full: new Set() };++ return {+ update(view) {+ const decorations = plugin.getState(view.state);++ this.processNew(view, decorations);+ this.processLoaded(view, decorations);+ },++ processNew(view, allDecorations) {+ const decorations = allDecorations.find(+ undefined,+ undefined,+ (spec) =>+ !spec.oneboxDataLoaded &&+ !pendingUrls[spec.oneboxType].has(spec.oneboxUrl)+ );++ for (const dec of decorations) {+ if (failedUrls[dec.spec.oneboxType].has(dec.spec.oneboxUrl)) {+ continue;+ }++ pendingUrls[dec.spec.oneboxType].add(dec.spec.oneboxUrl);++ // Full onebox, one by one+ if (dec.spec.oneboxType === "full") {+ const { oneboxUrl } = dec.spec;+ pendingUrls.full.add(oneboxUrl);++ processOnebox(oneboxUrl, getContext()).then((html) => {+ pendingUrls.full.delete(oneboxUrl);+ if (html) {+ view.dispatch(+ view.state.tr.setMeta(plugin, {+ oneboxContent: { url: oneboxUrl, html },+ })+ );+ } else {+ failedUrls.full.add(oneboxUrl);+ }+ });+ }+ }++ // Inline oneboxes, batched+ if (pendingUrls.inline.size) {+ const inlineUrls = pendingUrls.inline;+ loadInlineOneboxes(inlineUrls, getContext()).then(+ (inlineOneboxes) => {+ for (const url of inlineUrls) {+ pendingUrls.inline.delete(url);+ }++ if (Object.keys(inlineOneboxes).length > 0) {+ view.dispatch(+ view.state.tr.setMeta(plugin, { inlineOneboxes })+ );+ }+ }+ );+ }+ },++ processLoaded(view, allDecorations) {+ const decorations = allDecorations.find(+ undefined,+ undefined,+ (spec) => spec.oneboxDataLoaded+ );++ const removeDecorations = [];+ const sortedDecos = decorations.sort((a, b) => b.from - a.from);+ const tr = view.state.tr;++ for (const decoration of sortedDecos) {+ const nodeAtPos = view.state.doc.nodeAt(decoration.from);++ const isTextNode = nodeAtPos?.isText;+ const hasMatchingLink = nodeAtPos?.marks.find(+ (mark) =>+ mark.type.name === "link" &&+ mark.attrs.href === decoration.spec.oneboxUrl+ );++ if (!isTextNode || !hasMatchingLink) {+ continue;+ }++ if (decoration.spec.oneboxType === "inline") {+ if (decoration.spec.oneboxTitle) {+ const oneboxNode =+ view.state.schema.nodes.onebox_inline.create({+ url: decoration.spec.oneboxUrl,+ title: decoration.spec.oneboxTitle,+ });++ tr.replaceWith(decoration.from, decoration.to, oneboxNode);+ } else {+ failedUrls.inline.add(decoration.spec.oneboxUrl);+ }+ } else if (decoration.spec.oneboxType === "full") {+ if (decoration.spec.oneboxHtml) {+ const oneboxNode = view.state.schema.nodes.onebox.create({+ url: decoration.spec.oneboxUrl,+ html: decoration.spec.oneboxHtml,+ });++ const $pos = view.state.doc.resolve(decoration.from);+ const paragraph = $pos.parent;+ if (+ paragraph.type.name === "paragraph" &&+ paragraph.childCount === 1+ ) {+ tr.replaceWith($pos.before(), $pos.after(), oneboxNode);+ } else {+ tr.replaceWith(decoration.from, decoration.to, oneboxNode);+ }+ } else {+ failedUrls.full.add(decoration.spec.oneboxUrl);+ }+ }++ removeDecorations.push(decoration);+ }++ if (removeDecorations.length || tr.docChanged) {+ tr.setMeta(plugin, { removeDecorations });+ view.dispatch(tr);+ }+ },+ };+ },+ });++ return plugin;+ },+};++// Dummy element to pass to the oneboxer+// To avoid this, we need to refactor both oneboxer APIs+const dummyElement = {+ replaceWith() {},+ classList: { remove() {}, add() {}, contains: () => false },+ dataset: {},+};++async function loadInlineOneboxes(urls, { categoryId, topicId }) {+ const oneboxes = {};+ const elems = {};++ for (const url of urls) {+ const cached = cachedInlineOnebox(url);+ if (cached) {+ oneboxes[url] = cached.title;+ } else {+ elems[url] = [{ ...dummyElement }];+ }+ }++ await applyInlineOneboxes(elems, ajax, { categoryId, topicId });++ for (const [url, [onebox]] of Object.entries(elems)) {+ oneboxes[url] = onebox.innerText;+ }++ return oneboxes;+}++async function processOnebox(href, { topicId, categoryId }) {+ const html = await new Promise((onResolve) => {+ load({+ topicId,+ categoryId,+ elem: { ...dummyElement, href },+ onResolve,+ ajax,+ refresh: false,+ });+ });++ // Not a <a href="url">url</a> onebox response+ if (+ new RegExp(+ `^<a href=["']${escapeRegExp(href)}["'].*>${escapeRegExp(href)}</a>$`+ ).test(html)+ ) {+ return;+ }++ return html;+}++export default extension;diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.jsindex 05cc32993d9..89458271bb5 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/register-default.js@@ -9,6 +9,7 @@ import image from "./image";import link from "./link";import markdownPaste from "./markdown-paste";import mention from "./mention";+import onebox from "./onebox";import quote from "./quote";import strikethrough from "./strikethrough";import table from "./table";@@ -24,6 +25,7 @@ import underline from "./underline";const defaultExtensions = [emoji,image,+ onebox,link,heading,codeBlock,diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/markdown-it.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/markdown-it.jsindex e9cc3979172..2f35335e526 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/lib/markdown-it.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/markdown-it.js@@ -19,6 +19,9 @@ export const parse = (text) => getEngine().parse(text);export const getLinkify = () => getEngine().linkify;+export const isWhiteSpace = (str, index) =>+ !str || getEngine().options.engine.utils.isWhiteSpace(str.charCodeAt(index));+export const isBoundary = (str, index) =>!str ||getEngine().options.engine.utils.isWhiteSpace(str.charCodeAt(index)) ||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 050e9102540..7c2033c3034 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@@ -1 +1 @@-export { getLinkify, isBoundary } from "../lib/markdown-it";+export { getLinkify, isBoundary, isWhiteSpace } from "../lib/markdown-it";diff --git a/app/assets/javascripts/pretty-text/addon/oneboxer.js b/app/assets/javascripts/pretty-text/addon/oneboxer.jsindex ec2eb6ed00e..7740bcfa0bc 100644--- a/app/assets/javascripts/pretty-text/addon/oneboxer.js+++ b/app/assets/javascripts/pretty-text/addon/oneboxer.js@@ -62,7 +62,8 @@ function loadNext(ajax) {let timeoutMs = 150;let removeLoading = true;- const { url, refresh, elem, categoryId, topicId } = loadingQueue.shift();+ const { url, refresh, elem, categoryId, topicId, onResolve } =+ loadingQueue.shift();// Retrieve the oneboxreturn ajax("/onebox", {@@ -78,6 +79,7 @@ function loadNext(ajax) {(template) => {const node = domFromString(template)[0];setLocalCache(normalize(url), node);+ onResolve?.(template);elem.replaceWith(node);applySquareGenericOnebox(node);},@@ -110,6 +112,7 @@ export function load({refresh = true,offline = false,synchronous = false,+ onResolve,}) {// If the onebox has loaded or is loading, return@@ -128,6 +131,7 @@ export function load({// If we have it in our cache, return it.const cached = lookupCache(url);if (cached) {+ onResolve?.(cached);return cached;}@@ -146,7 +150,7 @@ export function load({elem.classList.add(LOADING_ONEBOX_CSS_CLASS);// Add to the loading queue- loadingQueue.push({ url, refresh, elem, categoryId, topicId });+ loadingQueue.push({ url, refresh, elem, categoryId, topicId, onResolve });// Load next url in queueif (synchronous) {diff --git a/app/assets/stylesheets/common/rich-editor/rich-editor.scss b/app/assets/stylesheets/common/rich-editor/rich-editor.scssindex 06d18aa9257..3ac6c5655e6 100644--- a/app/assets/stylesheets/common/rich-editor/rich-editor.scss+++ b/app/assets/stylesheets/common/rich-editor/rich-editor.scss@@ -162,6 +162,29 @@z-index: 1;}}++ .onebox-loading {+ border-radius: var(--d-border-radius);+ padding: 0 0.125rem;+ background: linear-gradient(+ 90deg,+ var(--primary-very-low) 0%,+ var(--primary-low) 50%,+ var(--primary-very-low) 100%+ );+ background-size: 200% 100%;+ animation: loading-pulse 1.5s ease-in-out infinite;+ }++ @keyframes loading-pulse {+ 0% {+ background-position: 200% 0;+ }++ 100% {+ background-position: -200% 0;+ }+ }}/*********************************************************diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rbindex 28fa57f596d..cd9c7b5044c 100644--- a/spec/system/composer/prosemirror_editor_spec.rb+++ b/spec/system/composer/prosemirror_editor_spec.rb@@ -16,6 +16,7 @@ describe "Composer - ProseMirror editor", type: :system dopage.visit "/new-topic"expect(composer).to be_openedcomposer.toggle_rich_editor+ composer.focusendit "hides the Composer container's preview button" do@@ -127,11 +128,7 @@ describe "Composer - ProseMirror editor", type: :system doendit "supports typographer replacements" do- page.visit "/new-topic"-- expect(composer).to be_opened-- composer.toggle_rich_editor+ open_composer_and_toggle_rich_editorcomposer.type_content("foo +- bar.. test???? wow!!!! x,, y-- a--> b<-- c-> d<- e<-> f<--> (tm) (pa)",)@@ -143,6 +140,187 @@ describe "Composer - ProseMirror editor", type: :system doendend+ context "with oneboxing" do+ let(:cdp) { PageObjects::CDP.new }++ before do+ def body(title)+ <<~HTML+ <html>+ <head>+ <title>#{title}</title>+ <meta property="og:title" content="#{title}">+ <meta property="og:description" content="This is an example site">+ </head>+ <body>+ <h1>#{title}</h1>+ <p>This domain is for use in examples.</p>+ </body>+ </html>+ HTML+ end++ stub_request(:head, "https://example.com").to_return(status: 200)+ stub_request(:get, "https://example.com").to_return(status: 200, body: body("Example Site 1"))++ stub_request(:head, "https://example2.com").to_return(status: 200)+ stub_request(:get, "https://example2.com").to_return(+ status: 200,+ body: body("Example Site 2"),+ )++ stub_request(:head, "https://example3.com").to_return(status: 200)+ stub_request(:get, "https://example3.com").to_return(+ status: 200,+ body: body("Example Site 3"),+ )+ end++ it "creates an inline onebox for links within text" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ composer.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")++ expect(rich).to have_css(+ "a.inline-onebox[href='https://example.com']",+ text: "Example Site 1",+ )++ composer.toggle_rich_editor++ expect(composer).to have_value(+ "Check out this link https://example.com in the middle of text",+ )+ end++ it "creates a full onebox for standalone links" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ cdp.write_clipboard("https://example.com")+ page.send_keys([PLATFORM_KEY_MODIFIER, "v"])+ page.send_keys(:enter, :enter)++ expect(rich).to have_css("div.onebox-wrapper[data-onebox-src='https://example.com']")+ expect(rich).to have_content("Example Site 1")+ expect(rich).to have_content("This is an example site")++ composer.toggle_rich_editor++ expect(composer).to have_value("https://example.com\n\n")+ end++ it "creates an inline onebox for links that are part of a paragraph" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ composer.type_content("Some text ")+ cdp.write_clipboard("https://example.com")+ page.send_keys([PLATFORM_KEY_MODIFIER, "v"])+ composer.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")++ composer.toggle_rich_editor++ expect(composer).to have_value("Some text https://example.com more text")+ end++ it "does not create oneboxes inside code blocks" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ composer.type_content("```")+ cdp.write_clipboard("https://example.com")+ page.send_keys([PLATFORM_KEY_MODIFIER, "v"])++ expect(rich).to have_css("pre code")+ expect(rich).to have_no_css("div.onebox-wrapper")+ expect(rich).to have_no_css("a.inline-onebox")+ expect(rich).to have_content("https://example.com")++ composer.toggle_rich_editor++ expect(composer).to have_value("```\nhttps://example.com\n```")+ end++ it "creates oneboxes for mixed content" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ markdown = <<~MARKDOWN+ https://example.com++ Check this https://example.com and see if it fits you++ https://example2.com++ An inline to https://example2.com with text around it++ https://example3.com++ Another one for https://example3.com then++ https://example.com++ Phew, repeating https://example.com now++ https://example2.com++ And some text again https://example2.com++ https://example3.com++ Ok, that is it https://example3.com+ MARKDOWN+ cdp.write_clipboard(markdown)+ page.send_keys([PLATFORM_KEY_MODIFIER, "v"])++ expect(rich).to have_css("a.inline-onebox", count: 6)+ expect(rich).to have_css(+ "a.inline-onebox[href='https://example.com']",+ text: "Example Site 1",+ )+ expect(rich).to have_css(+ "a.inline-onebox[href='https://example2.com']",+ text: "Example Site 2",+ )+ expect(rich).to have_css(+ "a.inline-onebox[href='https://example3.com']",+ text: "Example Site 3",+ )++ expect(rich).to have_css("div.onebox-wrapper", count: 6)+ expect(rich).to have_css("div.onebox-wrapper[data-onebox-src='https://example.com']")+ expect(rich).to have_css("div.onebox-wrapper[data-onebox-src='https://example2.com']")+ expect(rich).to have_css("div.onebox-wrapper[data-onebox-src='https://example3.com']")++ composer.toggle_rich_editor++ expect(composer).to have_value(markdown[0..-2])+ end++ it "creates inline oneboxes for repeated links in different paste events" do+ cdp.allow_clipboard+ open_composer_and_toggle_rich_editor+ composer.type_content("Hey")+ cdp.write_clipboard("https://example.com")+ page.send_keys([PLATFORM_KEY_MODIFIER, "v"])+ composer.type_content("and")+ page.send_keys([PLATFORM_KEY_MODIFIER, "v"])++ expect(rich).to have_css(+ "a.inline-onebox[href='https://example.com']",+ text: "Example Site 1",+ count: 2,+ )++ composer.toggle_rich_editor++ expect(composer).to have_value("Hey https://example.com and https://example.com")+ end+ end+context "with keymap" doPLATFORM_KEY_MODIFIER = SystemHelpers::PLATFORM_KEY_MODIFIERit "supports Ctrl + B to create a bold text" do@@ -162,7 +340,8 @@ describe "Composer - ProseMirror editor", type: :system doendxit "supports Ctrl + K to create a link" do- open_composer_and_toggle_rich_editor page.send_keys([PLATFORM_KEY_MODIFIER, "k"])+ open_composer_and_toggle_rich_editor+ page.send_keys([PLATFORM_KEY_MODIFIER, "k"])page.send_keys("https://www.example.com\t")page.send_keys("This is a link")page.send_keys(:enter)@@ -235,9 +414,9 @@ describe "Composer - ProseMirror editor", type: :system do# The example is a bit convoluted, but it's the simplest way to reproduce the issue.cdp.write_clipboard <<~MARKDOWN- ```- puts SiteSetting.all_settings(filter_categories: ["uncategorized"]).map { |setting| setting[:setting] }.join("\n")- ```+ ```+ puts SiteSetting.all_settings(filter_categories: ["uncategorized"]).map { |setting| setting[:setting] }.join("\n")+ ```MARKDOWNcomposer.type_content("This is a test\n\n")page.send_keys([PLATFORM_KEY_MODIFIER, "v"])diff --git a/spec/system/page_objects/components/composer.rb b/spec/system/page_objects/components/composer.rbindex fa630e52d97..50824137751 100644--- a/spec/system/page_objects/components/composer.rb+++ b/spec/system/page_objects/components/composer.rb@@ -34,6 +34,11 @@ module PageObjectsselfend+ def focus+ find(COMPOSER_INPUT_SELECTOR).click+ self+ end+def fill_title(title)find("#{COMPOSER_ID} #reply-title").fill_in(with: title)self@@ -73,6 +78,10 @@ module PageObjectscomposer_input.value == contentend+ def has_value?(value)+ expect(composer_input.value).to eq(value)+ end+def has_popup_content?(content)composer_popup.has_content?(content)end