Skip to content

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

FEATURE: Add onebox toolbar and show preview for rich editor (#39054)

Renato Atilioaf0f428164ba
diff --git a/app/assets/stylesheets/common/rich-editor/rich-editor.scss b/app/assets/stylesheets/common/rich-editor/rich-editor.scss
index 56eb38fdbca..2be2bb5d9b0 100644
--- a/app/assets/stylesheets/common/rich-editor/rich-editor.scss
+++ b/app/assets/stylesheets/common/rich-editor/rich-editor.scss
@@ -306,7 +306,8 @@
.fk-d-menu[data-identifier="composer-link-toolbar"],
.fk-d-menu[data-identifier="composer-image-toolbar"],
-.fk-d-menu[data-identifier="composer-image-alt-text"] {
+.fk-d-menu[data-identifier="composer-image-alt-text"],
+.fk-d-menu[data-identifier="composer-onebox-toolbar"] {
user-select: none;
z-index: z("composer", "dropdown");
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 10b64432c44..11150d44d2d 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -3354,6 +3354,14 @@ en:
remove: "Remove link"
visit: "Open link in external tab"
link_copied: "Link copied!"
+ load_preview: "Load preview"
+ preview_failed: "Could not load preview"
+
+ onebox_toolbar:
+ copy: "Copy link"
+ visit: "Open link"
+ remove_preview: "Remove preview"
+ link_copied: "Link copied!"
unsupported_token: "The rich text editor doesn’t support all features used in this post; switching you to the Markdown editor."
diff --git a/frontend/discourse/app/components/d-editor.gjs b/frontend/discourse/app/components/d-editor.gjs
index 2343da605cd..2791c34dca9 100644
--- a/frontend/discourse/app/components/d-editor.gjs
+++ b/frontend/discourse/app/components/d-editor.gjs
@@ -664,7 +664,14 @@ export default class DEditor extends Component {
}
@action
- replaceToolbar(toolbarInstance) {
+ replaceToolbar(toolbarInstance, owner) {
+ if (
+ toolbarInstance === null &&
+ owner &&
+ this.replacedToolbarInstance !== owner
+ ) {
+ return;
+ }
this.replacedToolbarInstance = toolbarInstance;
}
diff --git a/frontend/discourse/app/static/prosemirror/extensions/link-toolbar.js b/frontend/discourse/app/static/prosemirror/extensions/link-toolbar.js
index 58e1ac25e7e..a10630ef5e2 100644
--- a/frontend/discourse/app/static/prosemirror/extensions/link-toolbar.js
+++ b/frontend/discourse/app/static/prosemirror/extensions/link-toolbar.js
@@ -7,6 +7,8 @@ import { ToolbarBase } from "discourse/lib/composer/toolbar";
import { rovingButtonBar } from "discourse/lib/roving-button-bar";
import { clipboardCopy } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
+import { isTopLevel } from "discourse-markdown-it/features/onebox";
+import { oneboxPluginKey, oneboxTypeAtPos } from "./onebox";
const AUTO_LINKS = ["autolink", "linkify"];
const MENU_OFFSET = 12;
@@ -41,8 +43,18 @@ class LinkToolbar extends ToolbarBase {
action: opts.unlinkText,
});
+ this.addButton({
+ id: "link-show-preview",
+ icon: "expand",
+ title: "composer.link_toolbar.load_preview",
+ className: "composer-link-toolbar__show-preview",
+ condition: opts.canShowPreview,
+ action: opts.showPreview,
+ });
+
this.addSeparator({
- condition: () => opts.canVisit() || opts.canUnlink(),
+ condition: () =>
+ opts.canVisit() || opts.canUnlink() || opts.canShowPreview(),
});
this.addButton({
@@ -126,7 +138,7 @@ class LinkToolbarPluginView {
this.#menuInstance = null;
if (this.#toolbarReplaced) {
- this.#getContext().replaceToolbar(null);
+ this.#getContext().replaceToolbar(null, this.#linkToolbar);
this.#toolbarReplaced = false;
}
}
@@ -145,9 +157,11 @@ class LinkToolbarPluginView {
editLink: () => this.#openLinkEditor(),
copyLink: () => this.#copyLink(),
unlinkText: () => this.#unlinkText(),
+ showPreview: () => this.#showPreview(),
canVisit: () => this.#canVisit(),
getHref: () => this.#linkState.href,
canUnlink: () => this.#canUnlink(),
+ canShowPreview: () => this.#canShowPreview(),
});
this.#linkToolbar.rovingButtonBar = this.#rovingButtonBar.bind(this);
@@ -260,6 +274,57 @@ class LinkToolbarPluginView {
return !AUTO_LINKS.includes(this.#linkState.markup);
}
+ #canShowPreview() {
+ if (
+ !AUTO_LINKS.includes(this.#linkState.markup) ||
+ !this.#utils.getLinkify().matchAtStart(this.#linkState.href)
+ ) {
+ return false;
+ }
+
+ // Top-level URLs (e.g. google.com) can only be full-oneboxed, not inline.
+ // Hide "show preview" when the link is inline and top-level.
+ const { range } = this.#linkState;
+ if (
+ range &&
+ isTopLevel(this.#linkState.href) &&
+ oneboxTypeAtPos(this.#view.state.doc, range.from) === "inline"
+ ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ #showPreview() {
+ const { range } = this.#linkState;
+ if (!range) {
+ return;
+ }
+
+ this.#resetToolbar();
+
+ const { state, dispatch } = this.#view;
+ const tr = state.tr;
+
+ // Change markup to linkify so the onebox plugin recognizes it
+ tr.addMark(
+ range.from,
+ range.to,
+ state.schema.marks.link.create({
+ href: this.#linkState.href,
+ markup: "linkify",
+ })
+ );
+
+ // Tell the onebox plugin to pick up this URL immediately,
+ // bypassing the selection proximity check
+ tr.setMeta(oneboxPluginKey, { forceOneboxUrl: this.#linkState.href });
+
+ dispatch(tr);
+ this.#view.focus();
+ }
+
#showFloatingToolbar() {
const element = this.#view.domAtPos(this.#linkState.head).node;
const trigger =
diff --git a/frontend/discourse/app/static/prosemirror/extensions/onebox-toolbar.js b/frontend/discourse/app/static/prosemirror/extensions/onebox-toolbar.js
new file mode 100644
index 00000000000..d18db33c653
--- /dev/null
+++ b/frontend/discourse/app/static/prosemirror/extensions/onebox-toolbar.js
@@ -0,0 +1,323 @@
+import { trackedObject } from "@ember/reactive/collections";
+import { NodeSelection, TextSelection } from "prosemirror-state";
+import ToolbarButtons from "discourse/components/composer/toolbar-buttons";
+import { ToolbarBase } from "discourse/lib/composer/toolbar";
+import { rovingButtonBar } from "discourse/lib/roving-button-bar";
+import { clipboardCopy } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+
+const MENU_PADDING = 8;
+
+class OneboxToolbar extends ToolbarBase {
+ constructor(opts = {}) {
+ super(opts);
+
+ this.addButton({
+ id: "onebox-copy",
+ icon: "copy",
+ title: "composer.onebox_toolbar.copy",
+ className: "composer-onebox-toolbar__copy",
+ action: opts.copyLink,
+ });
+
+ this.addButton({
+ id: "onebox-remove-preview",
+ icon: "compress",
+ title: "composer.onebox_toolbar.remove_preview",
+ className: "composer-onebox-toolbar__remove-preview",
+ action: opts.removePreview,
+ });
+
+ this.addSeparator({});
+
+ this.addButton({
+ id: "onebox-visit",
+ icon: "up-right-from-square",
+ title: "composer.onebox_toolbar.visit",
+ className: "composer-onebox-toolbar__visit",
+ get href() {
+ return opts.getUrl();
+ },
+ });
+ }
+}
+
+class OneboxToolbarPluginView {
+ #menuInstance;
+ #menuType;
+ #toolbarReplaced = false;
+ #toolbar;
+ #state;
+
+ #view;
+ #getContext;
+
+ constructor({ getContext }) {
+ this.#getContext = getContext;
+ }
+
+ update(view) {
+ this.#view = view;
+ const { selection } = view.state;
+
+ if (!(selection instanceof NodeSelection)) {
+ this.#resetToolbar();
+ return;
+ }
+
+ const node = selection.node;
+ if (node.type.name !== "onebox" && node.type.name !== "onebox_inline") {
+ this.#resetToolbar();
+ return;
+ }
+
+ this.#updateState(node, selection);
+ this.#displayToolbar();
+ }
+
+ #resetToolbar() {
+ this.#menuInstance?.destroy();
+ this.#menuInstance = null;
+
+ if (this.#toolbarReplaced) {
+ this.#getContext().replaceToolbar(null, this.#toolbar);
+ this.#toolbarReplaced = false;
+ }
+ }
+
+ #updateState(node, selection) {
+ const attrs = {
+ url: node.attrs.url,
+ type: node.type.name,
+ from: selection.from,
+ to: selection.to,
+ };
+
+ if (!this.#toolbar) {
+ this.#state = trackedObject(attrs);
+
+ this.#toolbar = new OneboxToolbar({
+ copyLink: () => this.#copyLink(),
+ removePreview: () => this.#removePreview(),
+ getUrl: () => this.#state.url,
+ });
+
+ this.#toolbar.rovingButtonBar = this.#rovingButtonBar.bind(this);
+ } else {
+ Object.assign(this.#state, attrs);
+ }
+ }
+
+ #rovingButtonBar(event) {
+ if (event.key === "Tab") {
+ event.preventDefault();
+ this.#view.focus();
+ return false;
+ }
+ return rovingButtonBar(event);
+ }
+
+ #displayToolbar() {
+ if (this.#getContext().capabilities.viewport.sm) {
+ this.#showFloatingToolbar();
+ } else {
+ this.#getContext().replaceToolbar(this.#toolbar);
+ this.#toolbarReplaced = true;
+ }
+ }
+
+ async #copyLink() {
+ await clipboardCopy(this.#state.url);
+ this.#getContext().toasts.success({
+ duration: "short",
+ data: {
+ message: i18n("composer.onebox_toolbar.link_copied"),
+ },
+ });
+ }
+
+ #removePreview() {
+ const { state, dispatch } = this.#view;
+ const { selection } = state;
+ const node = selection.node;
+ const url = node.attrs.url;
+ const href = /^https?:\/\//.test(url) ? url : `https://${url}`;
+ const isBlock = node.type.name === "onebox";
+
+ const linkMark = state.schema.marks.link.create({
+ href,
+ markup: "autolink",
+ });
+ const textNode = state.schema.text(href, [linkMark]);
+
+ const content = isBlock
+ ? state.schema.nodes.paragraph.create(null, textNode)
+ : textNode;
+ const tr = state.tr.replaceWith(selection.from, selection.to, content);
+
+ // Place cursor at end of the new text
+ const cursorPos = isBlock
+ ? selection.from + 1 + href.length
+ : selection.from + href.length;
+ tr.setSelection(
+ TextSelection.create(tr.doc, Math.min(cursorPos, tr.doc.content.size))
+ );
+
+ dispatch(tr);
+ this.#view.focus();
+ }
+
+ #getNodeDOM() {
+ const { from } = this.#state;
+
+ // nodeDOM works for inline nodes, domAtPos for block nodes
+ const nodeDOM = this.#view.nodeDOM(from);
+ if (nodeDOM) {
+ return nodeDOM;
+ }
+
+ const { node, offset } = this.#view.domAtPos(from);
+ if (node.nodeType === Node.ELEMENT_NODE) {
+ return node.childNodes[offset];
+ }
+ return node.parentElement;
+ }
+
+ #showFloatingToolbar() {
+ const trigger = this.#getNodeDOM();
+ if (!trigger) {
+ return;
+ }
+
+ const type = this.#state.type;
+
+ // Reuse existing menu if same type
+ if (this.#menuInstance?.expanded && this.#menuType === type) {
+ this.#menuInstance.trigger = trigger;
+ return;
+ }
+
+ // Destroy and recreate when switching between block/inline
+ this.#menuInstance?.destroy();
+ this.#menuInstance = null;
+ this.#menuType = type;
+
+ if (type === "onebox") {
+ this.#showBlockToolbar(trigger);
+ } else {
+ this.#showInlineToolbar(trigger);
+ }
+ }
+
+ // Image-style positioning, portaled into the onebox element, top-right
+ async #showBlockToolbar(trigger) {
+ this.#menuInstance = await this.#getContext().menu.newInstance(trigger, {
+ identifier: "composer-onebox-toolbar",
+ component: ToolbarButtons,
+ placement: "top-end",
+ fallbackPlacements: ["top-end"],
+ padding: MENU_PADDING,
+ data: this.#toolbar,
+ portalOutletElement: trigger,
+ closeOnClickOutside: false,
+ closeOnEscape: false,
+ closeOnScroll: false,
+ trapTab: false,
+ offset({ rects }) {
+ return {
+ mainAxis: -MENU_PADDING - rects.floating.height,
+ crossAxis: -MENU_PADDING,
+ };
+ },
+ });
+
+ await this.#menuInstance.show();
+ }
+
+ // Link-toolbar-style: anchored below the inline onebox element
+ #showInlineToolbar(trigger) {
+ this.#getContext()
+ .menu.show(trigger, {
+ portalOutletElement: this.#view.dom.parentElement,
+ identifier: "composer-onebox-toolbar",
+ component: ToolbarButtons,
+ placement: "bottom",
+ padding: 0,
+ hide: true,
+ boundary: this.#view.dom.parentElement,
+ fallbackPlacements: [
+ "bottom-end",
+ "bottom-start",
+ "top",
+ "top-end",
+ "top-start",
+ ],
+ closeOnClickOutside: false,
+ onClose: () => this.#view.focus(),
+ data: this.#toolbar,
+ })
+ .then((instance) => {
+ this.#menuInstance = instance;
+ });
+ }
+
+ destroy() {
+ this.#menuInstance?.destroy();
+ this.#menuInstance = null;
+ this.#toolbar = null;
+ }
+}
+
+/** @type {RichEditorExtension} */
+const extension = {
+ plugins: ({ pmState: { Plugin }, getContext }) => {
+ return new Plugin({
+ props: {
+ handleKeyDown(view, event) {
+ if (event.key !== "Tab" || event.shiftKey) {
+ return false;
+ }
+
+ const { selection } = view.state;
+ if (!(selection instanceof NodeSelection)) {
+ return false;
+ }
+
+ const node = selection.node;
+ if (
+ node.type.name !== "onebox" &&
+ node.type.name !== "onebox_inline"
+ ) {
+ return false;
+ }
+
+ const activeMenu = document.querySelector(
+ '[data-identifier="composer-onebox-toolbar"]'
+ );
+ if (!activeMenu) {
+ return false;
+ }
+
+ event.preventDefault();
+
+ const focusable = activeMenu.querySelector(
+ 'button, a, [tabindex]:not([tabindex="-1"]), .select-kit'
+ );
+
+ if (focusable) {
+ focusable.focus();
+ return true;
+ }
+
+ return false;
+ },
+ },
+
+ view() {
+ return new OneboxToolbarPluginView({ getContext });
+ },
+ });
+ },
+};
+
+export default extension;
diff --git a/frontend/discourse/app/static/prosemirror/extensions/onebox.js b/frontend/discourse/app/static/prosemirror/extensions/onebox.js
index 364af7bc1fd..13d4158eacd 100644
--- a/frontend/discourse/app/static/prosemirror/extensions/onebox.js
+++ b/frontend/discourse/app/static/prosemirror/extensions/onebox.js
@@ -3,14 +3,34 @@ import {
cachedInlineOnebox,
} from "pretty-text/inline-oneboxer";
import { load } from "pretty-text/oneboxer";
+import { PluginKey } from "prosemirror-state";
import { ajax } from "discourse/lib/ajax";
import escapeRegExp from "discourse/lib/escape-regexp";
import {
getLinkify,
isWhiteSpace,
} from "discourse/static/prosemirror/lib/markdown-it";
+import { i18n } from "discourse-i18n";
import { isTopLevel } from "discourse-markdown-it/features/onebox";
+export const oneboxPluginKey = new PluginKey("onebox");
+
+/**
+ * Returns "full" if the link at `pos` is alone on its line at the document
+ * root (renders as a block preview), "inline" otherwise (title-only preview).
+ */
+export function oneboxTypeAtPos(doc, pos) {
+ const $pos = doc.resolve(pos);
+ const parent = $pos.parent;
+ const index = $pos.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");
+ return $pos.depth === 1 && isAlone ? "full" : "inline";
+}
+
/** @type {RichEditorExtension} */
const extension = {
nodeSpec: {
@@ -96,13 +116,64 @@ const extension = {
}) {
const failedUrls = { full: new Set(), inline: new Set() };
+ // Scans for linkified URLs and creates onebox loading decorations.
+ // `forceUrl` bypasses selection/topLevel/failed checks for that URL.
+ function scanForOneboxLinks(doc, decoSet, tr, forceUrl) {
+ const decorations = [];
+ doc.descendants((node, pos) => {
+ const link = node.marks.find((mark) => mark.type.name === "link");
+
+ if (
+ link?.attrs.markup === "linkify" &&
+ getLinkify().test(node.text) &&
+ decoSet.find(pos, pos + node.nodeSize).length === 0
+ ) {
+ const isForced = forceUrl === link.attrs.href;
+
+ if (!isForced && !isOutsideSelection(pos, node.nodeSize, tr)) {
+ return;
+ }
+
+ const oneboxType = oneboxTypeAtPos(doc, pos);
+
+ if (
+ !isForced &&
+ isTopLevel(link.attrs.href) &&
+ oneboxType === "inline"
+ ) {
+ return;
+ }
+
+ if (!isForced && failedUrls[oneboxType].has(link.attrs.href)) {
+ return;
+ }
+
+ decorations.push(
+ Decoration.inline(
+ pos,
+ pos + node.nodeSize,
+ { class: "onebox-loading", nodeName: "span" },
+ {
+ oneboxUrl: link.attrs.href,
+ oneboxType,
+ forceRetry: isForced,
+ }
+ )
+ );
+ }
+ });
+ return decorations;
+ }
+
const plugin = new Plugin({
+ key: oneboxPluginKey,
state: {
init() {
return DecorationSet.empty;
},
apply(tr, set) {
const meta = tr.getMeta(plugin);
+
if (meta?.removeDecorations) {
set = set.remove(meta.removeDecorations);
}
@@ -130,6 +201,7 @@ const extension = {
oneboxType: decoration.spec.oneboxType,
oneboxTitle: meta.inlineOneboxes[decoration.spec.oneboxUrl],
oneboxDataLoaded: true,
+ forceRetry: decoration.spec.forceRetry,
}
)
);
@@ -163,53 +235,17 @@ const extension = {
set = set.remove(decosToUpdate).add(tr.doc, newDecorations);
}
- return set;
+ if (!meta?.forceOneboxUrl) {
+ return set;
+ }
}
- const decorations = [];
- tr.doc.descendants((node, pos) => {
- const link = node.marks.find((mark) => mark.type.name === "link");
-
- if (
- link?.attrs.markup === "linkify" &&
- // Excludes watched word links
- getLinkify().test(node.text) &&
- set.find(pos, pos + node.nodeSize).length === 0 &&
- isOutsideSelection(pos, node.nodeSize, tr)
- ) {
- 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";
-
- // inline oneboxes should not be created for top-level links
- if (isTopLevel(link.attrs.href) && isInline) {
- return;
- }
-
- if (failedUrls[oneboxType].has(link.attrs.href)) {
- return;
- }
-
- decorations.push(
- Decoration.inline(
- pos,
- pos + node.nodeSize,
- { class: "onebox-loading", nodeName: "span" },
- { oneboxUrl: link.attrs.href, oneboxType }
- )
- );
- }
- });
+ const decorations = scanForOneboxLinks(
+ tr.doc,
+ set,
+ tr,
+ meta?.forceOneboxUrl
+ );
return set.add(tr.doc, decorations);
},
@@ -242,7 +278,10 @@ const extension = {
);
for (const dec of decorations) {
- if (failedUrls[dec.spec.oneboxType].has(dec.spec.oneboxUrl)) {
+ if (
+ !dec.spec.forceRetry &&
+ failedUrls[dec.spec.oneboxType].has(dec.spec.oneboxUrl)
+ ) {
continue;
}
@@ -250,21 +289,35 @@ const extension = {
// Full onebox, one by one
if (dec.spec.oneboxType === "full") {
- const { oneboxUrl } = dec.spec;
- pendingUrls.full.add(oneboxUrl);
+ const { oneboxUrl, forceRetry } = dec.spec;
- processOnebox(oneboxUrl, getContext()).then((html) => {
- pendingUrls.full.delete(oneboxUrl);
- if (html) {
- view.dispatch(
- view.state.tr.setMeta(plugin, {
- oneboxContent: { url: oneboxUrl, html },
- })
- );
- } else {
+ if (forceRetry) {
+ failedUrls.full.delete(oneboxUrl);
+ }
+
+ processOnebox(oneboxUrl, getContext(), { refresh: forceRetry })
+ .then((html) => {
+ pendingUrls.full.delete(oneboxUrl);
+ if (html) {
+ view.dispatch(
+ view.state.tr.setMeta(plugin, {
+ oneboxContent: { url: oneboxUrl, html },
+ })
+ );
+ } else {
+ failedUrls.full.add(oneboxUrl);
+ if (forceRetry) {
+ showPreviewFailedToast();
+ }
+ }
+ })
+ .catch(() => {
+ pendingUrls.full.delete(oneboxUrl);
failedUrls.full.add(oneboxUrl);
- }
- });
+ if (forceRetry) {
+ showPreviewFailedToast();
+ }
+ });
}
}
@@ -324,6 +377,9 @@ const extension = {
tr.replaceWith(decoration.from, decoration.to, oneboxNode);
} else {
failedUrls.inline.add(decoration.spec.oneboxUrl);
+ if (decoration.spec.forceRetry) {
+ showPreviewFailedToast();
+ }
}
} else if (decoration.spec.oneboxType === "full") {
if (decoration.spec.oneboxHtml) {
@@ -359,6 +415,15 @@ const extension = {
},
});
+ function showPreviewFailedToast() {
+ getContext().toasts.default({
+ duration: "short",
+ data: {
+ message: i18n("composer.link_toolbar.preview_failed"),
+ },
+ });
+ }
+
return plugin;
},
};
@@ -418,7 +483,7 @@ async function loadInlineOneboxes(urls, { categoryId, topicId }) {
return oneboxes;
}
-async function processOnebox(href, { topicId, categoryId }) {
+async function processOnebox(href, { topicId, categoryId }, opts = {}) {
const html = await new Promise((onResolve) => {
load({
topicId,
@@ -426,7 +491,7 @@ async function processOnebox(href, { topicId, categoryId }) {
elem: { ...dummyElement, href },
onResolve,
ajax,
- refresh: false,
+ refresh: opts.refresh ?? false,
});
});
diff --git a/frontend/discourse/app/static/prosemirror/extensions/register-default.js b/frontend/discourse/app/static/prosemirror/extensions/register-default.js
index 5402cae55e9..e93ef385997 100644
--- a/frontend/discourse/app/static/prosemirror/extensions/register-default.js
+++ b/frontend/discourse/app/static/prosemirror/extensions/register-default.js
@@ -17,6 +17,7 @@ import linkToolbar from "./link-toolbar";
import markdownPaste from "./markdown-paste";
import mention from "./mention";
import onebox from "./onebox";
+import oneboxToolbar from "./onebox-toolbar";
import orderedList from "./ordered-list";
import overrideDragGhost from "./override-drag-ghost";
import quote from "./quote";
@@ -38,6 +39,7 @@ const defaultExtensions = [
emoji,
image,
onebox,
+ oneboxToolbar,
code,
link,
linkToolbar,
diff --git a/spec/system/composer/prosemirror_onebox_toolbar_spec.rb b/spec/system/composer/prosemirror_onebox_toolbar_spec.rb
new file mode 100644
index 00000000000..11648f94482
--- /dev/null
+++ b/spec/system/composer/prosemirror_onebox_toolbar_spec.rb
@@ -0,0 +1,180 @@
+# frozen_string_literal: true
+
+describe "Composer - ProseMirror - Onebox Toolbar" do
+ include_context "with prosemirror editor"
+
+ let(:onebox_toolbar) { PageObjects::Components::ComposerOneboxToolbar.new }
+
+ 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
+
+ before do
+ stub_request(:head, %r{https://example\.com.*}).to_return(status: 200)
+ stub_request(:get, %r{https://example\.com.*}).to_return(
+ status: 200,
+ body: body("Example Site"),
+ )
+ end
+
+ context "with full onebox" do
+ it "shows toolbar when selecting a full onebox" do
+ cdp.allow_clipboard
+ open_composer
+ cdp.copy_paste("https://example.com")
+ page.send_keys(:enter)
+
+ expect(rich).to have_css("div.onebox-wrapper")
+ rich.find("div.onebox-wrapper").click
+
+ expect(onebox_toolbar).to have_toolbar
+ expect(onebox_toolbar).to have_copy_button
+ expect(onebox_toolbar).to have_remove_preview_button
+ expect(onebox_toolbar).to have_visit_link
+ end
+
+ it "removes preview and converts to plain link" do
+ cdp.allow_clipboard
+ open_composer
+ cdp.copy_paste("https://example.com")
+ page.send_keys(:enter)
+
+ expect(rich).to have_css("div.onebox-wrapper")
+ rich.find("div.onebox-wrapper").click
+ onebox_toolbar.click_remove_preview
+
+ expect(rich).to have_no_css("div.onebox-wrapper")
+ expect(rich).to have_css("a[href='https://example.com']", text: "https://example.com")
+
+ composer.toggle_rich_editor
+ expect(composer).to have_value("<https://example.com>")
+ end
+
+ it "does not re-onebox after removing preview" do
+ cdp.allow_clipboard
+ open_composer
+ cdp.copy_paste("https://example.com")
+ page.send_keys(:enter)
+
+ expect(rich).to have_css("div.onebox-wrapper")
+ rich.find("div.onebox-wrapper").click
+ onebox_toolbar.click_remove_preview
+
+ expect(rich).to have_no_css("div.onebox-wrapper")
+ expect(rich).to have_css("a[href='https://example.com']")
+
+ # Move cursor away and back — should not re-onebox
+ composer.type_content(:enter)
+ composer.type_content("some more text")
+ expect(rich).to have_no_css("div.onebox-wrapper")
+ end
+ end
+
+ context "with inline onebox" do
+ it "shows toolbar when selecting an inline onebox" do
+ cdp.allow_clipboard
+ open_composer
+ composer.type_content("Check ")
+ cdp.copy_paste("https://example.com/x")
+ composer.type_content(:space)
+
+ expect(rich).to have_css("a.inline-onebox")
+ rich.find("a.inline-onebox").click
+
+ expect(onebox_toolbar).to have_toolbar
+ expect(onebox_toolbar).to have_copy_button
+ expect(onebox_toolbar).to have_remove_preview_button
+ end
+
+ it "removes inline preview and converts to plain link" do
+ cdp.allow_clipboard
+ open_composer
+ composer.type_content("Check ")
+ cdp.copy_paste("https://example.com/x")
+ composer.type_content(:space)
+
+ expect(rich).to have_css("a.inline-onebox", text: "Example Site")
+ rich.find("a.inline-onebox").click
+ onebox_toolbar.click_remove_preview
+
+ expect(rich).to have_no_css("a.inline-onebox")
+ expect(rich).to have_css("a[href='https://example.com/x']", text: "https://example.com/x")
+ end
+ end
+
+ context "with show preview on link toolbar" do
+ it "re-oneboxes a full onebox when clicking show preview" do
+ cdp.allow_clipboard
+ open_composer
+ cdp.copy_paste("https://example.com")
+ page.send_keys(:enter)
+
+ expect(rich).to have_css("div.onebox-wrapper")
+ rich.find("div.onebox-wrapper").click
+ onebox_toolbar.click_remove_preview
+
+ expect(rich).to have_no_css("div.onebox-wrapper")
+ rich.find("a[href='https://example.com']").click
+
+ expect(page).to have_css("button.composer-link-toolbar__show-preview")
+ find("button.composer-link-toolbar__show-preview").click
+ expect(rich).to have_css("div.onebox-wrapper")
+ end
+
+ it "re-oneboxes an inline onebox when clicking show preview" do
+ cdp.allow_clipboard
+ open_composer
+ composer.type_content("Check ")
+ cdp.copy_paste("https://example.com/x")
+ composer.type_content(:space)
+
+ expect(rich).to have_css("a.inline-onebox")
+ rich.find("a.inline-onebox").click
+ onebox_toolbar.click_remove_preview
+
+ expect(rich).to have_no_css("a.inline-onebox")
+ rich.find("a[href='https://example.com/x']").click
+
+ expect(page).to have_css("button.composer-link-toolbar__show-preview")
+ find("button.composer-link-toolbar__show-preview").click
+ expect(rich).to have_css("a.inline-onebox")
+ end
+
+ it "retries full onebox fetch after a failure" do
+ cdp.allow_clipboard
+ open_composer
+
+ stub_request(:get, "https://example.com/fail").to_return(status: 404)
+
+ cdp.copy_paste("https://example.com/fail")
+ page.send_keys(:enter)
+
+ expect(rich).to have_no_css("div.onebox-wrapper")
+ expect(rich).to have_css("a[href='https://example.com/fail']")
+
+ rich.find("a[href='https://example.com/fail']").click
+ expect(page).to have_css("button.composer-link-toolbar__show-preview")
+
+ stub_request(:get, "https://example.com/fail").to_return(
+ status: 200,
+ body: body("Recovered Site"),
+ )
+
+ find("button.composer-link-toolbar__show-preview").click
+
+ expect(rich).to have_css("div.onebox-wrapper")
+ end
+ end
+end
diff --git a/spec/system/page_objects/components/composer_onebox_toolbar.rb b/spec/system/page_objects/components/composer_onebox_toolbar.rb
new file mode 100644
index 00000000000..469ef426cca
--- /dev/null
+++ b/spec/system/page_objects/components/composer_onebox_toolbar.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class ComposerOneboxToolbar < PageObjects::Components::Base
+ TOOLBAR_SELECTOR = "[data-identifier='composer-onebox-toolbar']"
+
+ def has_toolbar?
+ page.has_css?(TOOLBAR_SELECTOR)
+ end
+
+ def has_no_toolbar?
+ page.has_no_css?(TOOLBAR_SELECTOR)
+ end
+
+ def has_copy_button?
+ page.has_css?("button.composer-onebox-toolbar__copy")
+ end
+
+ def has_remove_preview_button?
+ page.has_css?("button.composer-onebox-toolbar__remove-preview")
+ end
+
+ def has_visit_link?
+ page.has_css?("a.composer-onebox-toolbar__visit")
+ end
+
+ def click_remove_preview
+ page.find("button.composer-onebox-toolbar__remove-preview").click
+ self
+ end
+
+ def click_copy
+ page.find("button.composer-onebox-toolbar__copy").click
+ self
+ end
+ end
+ end
+end