Skip to content

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

FIX: Sync rich editor onebox type with cooked output (#41059)

Renato Atilio536c515c5dcf
diff --git a/frontend/discourse/app/static/prosemirror/extensions/onebox.js b/frontend/discourse/app/static/prosemirror/extensions/onebox.js
index 13d4158eacd..fe60fa2f1ce 100644
--- a/frontend/discourse/app/static/prosemirror/extensions/onebox.js
+++ b/frontend/discourse/app/static/prosemirror/extensions/onebox.js
@@ -3,7 +3,7 @@ import {
cachedInlineOnebox,
} from "pretty-text/inline-oneboxer";
import { load } from "pretty-text/oneboxer";
-import { PluginKey } from "prosemirror-state";
+import { PluginKey, Selection } from "prosemirror-state";
import { ajax } from "discourse/lib/ajax";
import escapeRegExp from "discourse/lib/escape-regexp";
import {
@@ -27,7 +27,9 @@ export function oneboxTypeAtPos(doc, pos) {
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");
+ (!next ||
+ next.type.name === "hard_break" ||
+ hasTrailingWhitespaceOnly(doc, pos));
return $pos.depth === 1 && isAlone ? "full" : "inline";
}
@@ -134,7 +136,18 @@ const extension = {
return;
}
- const oneboxType = oneboxTypeAtPos(doc, pos);
+ let oneboxType = oneboxTypeAtPos(doc, pos);
+
+ // Hold a trailing-whitespace link inline while the cursor is on its
+ // line, so the user can keep typing; appendTransaction promotes it.
+ if (
+ !isForced &&
+ oneboxType === "full" &&
+ hasTrailingWhitespaceOnly(doc, pos) &&
+ selectionInSameBlock(doc, pos, tr.selection)
+ ) {
+ oneboxType = "inline";
+ }
if (
!isForced &&
@@ -389,12 +402,35 @@ const extension = {
});
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);
+ if ($pos.parent.type.name === "paragraph") {
+ const from = $pos.before();
+ const to = $pos.after();
+ const cursorOnLine =
+ view.state.selection.from >= from &&
+ view.state.selection.to <= to;
+ const nodes = splitParagraphAroundOnebox($pos, oneboxNode);
+
+ // Give the cursor somewhere to land after the onebox when it
+ // would otherwise end the document, so it isn't left
+ // selecting the block (where typing would replace it).
+ if (
+ nodes[nodes.length - 1] === oneboxNode &&
+ to === view.state.doc.content.size
+ ) {
+ nodes.push(view.state.schema.nodes.paragraph.create());
+ }
+
+ tr.replaceWith(from, to, nodes);
+
+ if (cursorOnLine) {
+ const afterOnebox =
+ from +
+ (nodes[0] === oneboxNode ? 0 : nodes[0].nodeSize) +
+ oneboxNode.nodeSize;
+ tr.setSelection(
+ Selection.near(tr.doc.resolve(afterOnebox), 1)
+ );
+ }
} else {
tr.replaceWith(decoration.from, decoration.to, oneboxNode);
}
@@ -413,6 +449,64 @@ const extension = {
},
};
},
+
+ // Promote an inline onebox to a full preview once it ends up alone on its
+ // line (e.g. after Enter, or surrounding text is removed), matching how it
+ // cooks. Resets it to a link so scanForOneboxLinks reuses the fetch path.
+ appendTransaction(transactions, prevState, state) {
+ const docChanged = transactions.some((tr) => tr.docChanged);
+ const selectionChanged = !prevState.selection.eq(state.selection);
+
+ if (!docChanged && !selectionChanged) {
+ return;
+ }
+
+ // Re-check the block the cursor just left, mapped to the near side of
+ // any split so it lands in the paragraph left behind (e.g. by Enter).
+ let leftPos = prevState.selection.from;
+ for (const tr of transactions) {
+ leftPos = tr.mapping.map(leftPos, -1);
+ }
+
+ const tr = state.tr;
+ const inspected = new Set();
+
+ for (const position of [state.selection.from, leftPos]) {
+ const { from, to } = topBlockRange(state.doc, position);
+ if (inspected.has(from)) {
+ continue;
+ }
+ inspected.add(from);
+
+ state.doc.nodesBetween(from, to, (node, nodePos) => {
+ if (node.type.name !== "onebox_inline") {
+ return;
+ }
+
+ if (oneboxTypeAtPos(state.doc, nodePos) !== "full") {
+ return;
+ }
+
+ if (selectionInSameBlock(state.doc, nodePos, state.selection)) {
+ return;
+ }
+
+ const { url } = node.attrs;
+ const mark = state.schema.marks.link.create({
+ href: url,
+ markup: "linkify",
+ });
+
+ tr.replaceWith(
+ tr.mapping.map(nodePos),
+ tr.mapping.map(nodePos + node.nodeSize),
+ state.schema.text(url, [mark])
+ );
+ });
+ }
+
+ return tr.steps.length ? tr.setMeta("addToHistory", false) : null;
+ },
});
function showPreviewFailedToast() {
@@ -428,6 +522,85 @@ const extension = {
},
};
+// True when the link at `pos` is followed only by a single whitespace-only text
+// node (a trailing space the markdown parser trims, so it still cooks to full).
+function hasTrailingWhitespaceOnly(doc, pos) {
+ const $pos = doc.resolve(pos);
+ const parent = $pos.parent;
+ const index = $pos.index();
+
+ if (index !== parent.childCount - 2) {
+ return false;
+ }
+
+ const next = parent.child(index + 1);
+ return next.isText && [...next.text].every((char) => isWhiteSpace(char));
+}
+
+// A full onebox is a block node, so it can't stay inside the paragraph. The link
+// can still share its paragraph with other lines via hard breaks (shift+enter),
+// so split those lines into their own paragraphs around the onebox and drop the
+// hard breaks (or trailing space) bounding the link.
+function splitParagraphAroundOnebox($pos, oneboxNode) {
+ const parent = $pos.parent;
+ const index = $pos.index();
+ const isHardBreak = (i) =>
+ i >= 0 &&
+ i < parent.childCount &&
+ parent.child(i).type.name === "hard_break";
+ const childrenBetween = (from, to) => {
+ const children = [];
+ for (let i = from; i < to; i++) {
+ children.push(parent.child(i));
+ }
+ return children;
+ };
+
+ const nodes = [];
+
+ if (isHardBreak(index - 1)) {
+ const before = childrenBetween(0, index - 1);
+ if (before.length) {
+ nodes.push(parent.type.create(parent.attrs, before));
+ }
+ }
+
+ nodes.push(oneboxNode);
+
+ if (isHardBreak(index + 1)) {
+ const after = childrenBetween(index + 2, parent.childCount);
+ if (after.length) {
+ nodes.push(parent.type.create(parent.attrs, after));
+ }
+ }
+
+ return nodes;
+}
+
+function topBlockRange(doc, pos) {
+ const clamped = Math.max(0, Math.min(pos, doc.content.size));
+ const $pos = doc.resolve(clamped);
+
+ if ($pos.depth === 0) {
+ const after = $pos.nodeAfter;
+ if (after) {
+ return { from: clamped, to: clamped + after.nodeSize };
+ }
+ const before = $pos.nodeBefore;
+ if (before) {
+ return { from: clamped - before.nodeSize, to: clamped };
+ }
+ return { from: clamped, to: clamped };
+ }
+
+ return { from: $pos.before(1), to: $pos.after(1) };
+}
+
+function selectionInSameBlock(doc, pos, selection) {
+ const { from, to } = topBlockRange(doc, pos);
+ return selection.from >= from && selection.to <= to;
+}
+
function isOutsideSelection(from, to, tr) {
const { selection, doc } = tr;
diff --git a/frontend/discourse/tests/integration/components/prosemirror-editor/onebox-test.js b/frontend/discourse/tests/integration/components/prosemirror-editor/onebox-test.js
index 1d906bb14b8..a73ff764820 100644
--- a/frontend/discourse/tests/integration/components/prosemirror-editor/onebox-test.js
+++ b/frontend/discourse/tests/integration/components/prosemirror-editor/onebox-test.js
@@ -1,7 +1,30 @@
+import { settled } from "@ember/test-helpers";
import { setLocalCache } from "pretty-text/oneboxer-cache";
+import { NodeSelection, TextSelection } from "prosemirror-state";
import { module, test } from "qunit";
import { buildEngine } from "discourse/static/markdown-it";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender from "discourse/tests/helpers/create-pretender";
+import { setupRichEditor } from "discourse/tests/helpers/rich-editor-helper";
+
+// Mocked by create-pretender for both /inline-onebox and /onebox.
+const URL = "http://www.example.com/has-title.html";
+
+function lastParagraphStart(doc) {
+ let pos = null;
+ doc.descendants((node, nodePos) => {
+ if (node.type.name === "paragraph") {
+ pos = nodePos + 1;
+ }
+ });
+ return pos;
+}
+
+function moveCursorTo(view, pos) {
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(view.state.doc, pos))
+ );
+}
module(
"Integration | Component | prosemirror-editor - onebox extension",
@@ -27,5 +50,127 @@ module(
setLocalCache(testUrl, null);
});
+
+ test("holds a lone link inline while the cursor is on its line", async function (assert) {
+ this.siteSettings.rich_editor = true;
+ const [editor] = await setupRichEditor(assert, "a\n\nb");
+ const { view } = editor;
+
+ // Replace the first paragraph's "a" with the URL + a trailing space, and
+ // put the cursor right after the space (still on the same line).
+ const text = `${URL} `;
+ const tr = view.state.tr.insertText(text, 1, 2);
+ tr.setSelection(TextSelection.create(tr.doc, 1 + text.length));
+ view.dispatch(tr);
+ await settled();
+
+ assert.dom("a.inline-onebox").exists("renders an inline onebox");
+ assert
+ .dom(".onebox-wrapper")
+ .doesNotExist("does not render a full onebox yet");
+ });
+
+ test("promotes a lone inline onebox to a full onebox when the cursor leaves its line", async function (assert) {
+ this.siteSettings.rich_editor = true;
+ const [editor] = await setupRichEditor(assert, "a\n\nb");
+ const { view } = editor;
+
+ const text = `${URL} `;
+ const tr = view.state.tr.insertText(text, 1, 2);
+ tr.setSelection(TextSelection.create(tr.doc, 1 + text.length));
+ view.dispatch(tr);
+ await settled();
+ assert.dom("a.inline-onebox").exists("starts as an inline onebox");
+
+ // Move the cursor into the second paragraph.
+ moveCursorTo(view, lastParagraphStart(view.state.doc));
+ await settled();
+
+ assert.dom(".onebox-wrapper").exists("promotes to a full onebox");
+ assert
+ .dom("a.inline-onebox")
+ .doesNotExist("is no longer an inline onebox");
+ assert.strictEqual(
+ editor.value,
+ `${URL}\n\nb`,
+ "serializes the full onebox on its own line, matching the cooked output"
+ );
+ });
+
+ // Top-level URLs never become inline oneboxes, so they reach the full
+ // onebox via the scan with their trailing space still present. The full
+ // onebox is a block node, so it must replace the whole paragraph rather
+ // than split it and leave an empty paragraph behind.
+ test("a top-level URL alone on its line becomes a full onebox with no empty paragraph before it", async function (assert) {
+ this.siteSettings.rich_editor = true;
+
+ const topLevelUrl = "http://www.example.com";
+ pretender.get("/onebox", () => [
+ 200,
+ { "Content-Type": "text/html" },
+ '<aside class="onebox"><article class="onebox-body"><h3><a href="http://www.example.com">Example</a></h3></article></aside>',
+ ]);
+
+ const [editor] = await setupRichEditor(assert, "x");
+ const { view } = editor;
+
+ // Type the URL + trailing space (held as a plain link while editing)...
+ view.dispatch(view.state.tr.insertText(`${topLevelUrl} `, 1, 2));
+ await settled();
+ assert
+ .dom(".onebox-wrapper")
+ .doesNotExist("stays a plain link while the cursor is on the line");
+
+ // ...then press Enter, which promotes it to a full onebox.
+ view.dispatch(view.state.tr.split(view.state.selection.from));
+ await settled();
+
+ assert.dom(".onebox-wrapper").exists("becomes a full onebox");
+ assert.strictEqual(
+ view.state.doc.firstChild.type.name,
+ "onebox",
+ "the onebox is the first node — no empty paragraph before it"
+ );
+ });
+
+ // A URL alone on a line within a multi-line paragraph (a hard break, e.g.
+ // shift+enter) must split into a clean block onebox plus a paragraph for the
+ // following line — not a stray empty paragraph wrapping the block.
+ test("a URL followed by a hard break and text splits into onebox + paragraph", async function (assert) {
+ this.siteSettings.rich_editor = true;
+ const [editor] = await setupRichEditor(assert, "x");
+ const { view } = editor;
+ const { schema } = view.state;
+
+ // Build "URL<hard break>asd" with the cursor after the break.
+ const linkMark = schema.marks.link.create({
+ href: URL,
+ markup: "linkify",
+ });
+ const tr = view.state.tr.replaceWith(1, 2, [
+ schema.text(URL, [linkMark]),
+ schema.nodes.hard_break.create(),
+ schema.text("asd"),
+ ]);
+ tr.setSelection(TextSelection.create(tr.doc, 1 + URL.length + 1));
+ view.dispatch(tr);
+ await settled();
+
+ assert.dom(".onebox-wrapper").exists("becomes a full onebox");
+ assert.strictEqual(
+ view.state.doc.firstChild.type.name,
+ "onebox",
+ "the onebox is the first node — no empty paragraph before it"
+ );
+ assert.strictEqual(
+ editor.value,
+ `${URL}\n\nasd`,
+ "the trailing line becomes its own paragraph"
+ );
+ assert.false(
+ view.state.selection instanceof NodeSelection,
+ "the cursor lands after the onebox, not selecting the block"
+ );
+ });
}
);