Skip to content

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

DEV: generic applySurround and applyList in rich editor (#38909)

Renato Atilio8c0391597798
diff --git a/frontend/discourse/app/lib/composer/text-manipulation.ts b/frontend/discourse/app/lib/composer/text-manipulation.ts
index abb3bf04988..d1e86c9d2c3 100644
--- a/frontend/discourse/app/lib/composer/text-manipulation.ts
+++ b/frontend/discourse/app/lib/composer/text-manipulation.ts
@@ -71,15 +71,18 @@ export interface ReplaceTextOptions {
}
export interface SurroundOptions {
- /** Apply formatting independently across multiple lines. */
+ /** Apply the delimiters independently to each selected line. */
multiline?: boolean;
- /** Put multiline content on lines between the delimiters. */
+ /**
+ * Separate multiline content from the delimiters with newlines when wrapping
+ * the whole selection. This controls spacing; it does not force a block node.
+ */
useBlockMode?: boolean;
/** Apply formatting to empty lines. */
applyEmptyLines?: boolean;
- /** Leave the leading marker outside the restored selection. */
+ /** Leave the leading marker outside the restored selection (plain-text editor only). */
excludeHeadInSelection?: boolean;
- /** Expand the selection to whole lines before applying. */
+ /** Expand the selection to whole lines before applying (plain-text editor only). */
wholeLine?: boolean;
}
@@ -128,7 +131,10 @@ export interface TextManipulation {
): SelectedText;
/** Selects a text range. */
selectText(from: number, length: number, options?: SelectTextOptions): void;
- /** Surrounds a supplied selection with formatting text. */
+ /**
+ * Applies delimiters to a selection. The rich editor parses the markup;
+ * use extension commands for node-specific toggling.
+ */
applySurround(
selected: SelectedText,
head: string | ((previous?: string) => string),
diff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts
index c2dcdf5447c..24e80d82cdc 100644
--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts
+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts
@@ -358,6 +358,7 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignat
schema: this.schema,
view: this.view,
convertFromMarkdown: this.convertFromMarkdown,
+ tryConvertFromMarkdown: this.tryConvertFromMarkdown,
convertToMarkdown: this.convertToMarkdown,
splitNonEmptyLines: this.splitNonEmptyLines,
buildListNode: this.buildListNode,
@@ -380,28 +381,39 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignat
@bind
convertFromMarkdown(markdown: string): Node {
+ const doc = this.tryConvertFromMarkdown(markdown);
+ if (doc) {
+ return doc;
+ }
+
+ this.dialog.alert({
+ message: i18n("composer.unsupported_token"),
+ didConfirm: this.args.toggleRichEditor,
+ didCancel: this.args.toggleRichEditor,
+ });
+
+ return this.schema.nodes.paragraph.create(
+ null,
+ markdown
+ // our html_block avoids double newlines
+ // because markdown-it closes the html block parsing at double newlines
+ .split("\n\n")
+ .filter(Boolean)
+ .map((line) =>
+ // this creates a dependency on having a html_block in the schema
+ this.schema.nodes.html_block.create(null, this.schema.text(line))
+ )
+ );
+ }
+
+ /** Parses markdown, returning null instead of alerting on unsupported tokens. */
+ @bind
+ tryConvertFromMarkdown(markdown: string): Node | null {
try {
return this.parser.convert(this.schema, markdown);
} catch (e) {
if (e instanceof UnsupportedTokenError) {
- this.dialog.alert({
- message: i18n("composer.unsupported_token"),
- didConfirm: this.args.toggleRichEditor,
- didCancel: this.args.toggleRichEditor,
- });
-
- return this.schema.nodes.paragraph.create(
- null,
- markdown
- // our html_block avoids double newlines
- // because markdown-it closes the html block parsing at double newlines
- .split("\n\n")
- .filter(Boolean)
- .map((line) =>
- // this creates a dependency on having a html_block in the schema
- this.schema.nodes.html_block.create(null, this.schema.text(line))
- )
- );
+ return null;
}
throw e;
diff --git a/frontend/discourse/app/static/prosemirror/core/serializer.js b/frontend/discourse/app/static/prosemirror/core/serializer.js
index 34b67515cc9..1157a92375b 100644
--- a/frontend/discourse/app/static/prosemirror/core/serializer.js
+++ b/frontend/discourse/app/static/prosemirror/core/serializer.js
@@ -2,6 +2,7 @@ import {
defaultMarkdownSerializer,
MarkdownSerializerState,
} from "prosemirror-markdown";
+import { Fragment, Node } from "prosemirror-model";
import expelBoundaryPunctuation from "../lib/expel-boundary-punctuation.ts";
export default class Serializer {
@@ -24,7 +25,21 @@ export default class Serializer {
convert(doc) {
const state = new MarkdownSerializerState(this.nodes, this.marks, {});
- state.renderContent(expelBoundaryPunctuation(doc).content);
+ const normalized = expelBoundaryPunctuation(doc);
+ const content =
+ normalized instanceof Fragment ? normalized : normalized.content;
+ if (content.firstChild?.isInline) {
+ const parent =
+ normalized instanceof Node
+ ? normalized
+ : content.firstChild.type.schema.nodes.paragraph.create(
+ null,
+ content
+ );
+ state.renderInline(parent);
+ } else {
+ state.renderContent(content);
+ }
if (this.#afterSerializers) {
for (const afterSerializer of this.#afterSerializers) {
diff --git a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts
index cac833af787..e56ee215e09 100644
--- a/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts
+++ b/frontend/discourse/app/static/prosemirror/lib/text-manipulation.ts
@@ -7,8 +7,8 @@ import { isEmpty } from "@ember/utils";
import { lookupCachedUploadUrl } from "pretty-text/upload-short-url";
import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands";
import {
- type Fragment,
- type MarkType,
+ Fragment,
+ type Mark,
type Node,
type NodeType,
type Schema,
@@ -18,13 +18,14 @@ import {
liftListItem,
sinkListItem,
wrapInList,
+ wrapRangeInList,
} from "prosemirror-schema-list";
import {
- type Command,
type EditorState,
NodeSelection,
Selection,
TextSelection,
+ type Transaction,
} from "prosemirror-state";
import type { EditorView } from "prosemirror-view";
import type {
@@ -34,6 +35,7 @@ import type {
ReplaceTextOptions,
SelectedText,
SelectTextOptions,
+ SurroundOptions,
TextManipulation,
ToolbarState,
UppyFile,
@@ -53,6 +55,7 @@ interface ProsemirrorTextManipulationOptions {
schema: Schema;
view: EditorView;
convertFromMarkdown: (markdown: string) => Node;
+ tryConvertFromMarkdown: (markdown: string) => Node | null;
convertToMarkdown: (doc: Node | Fragment | Slice) => string;
splitNonEmptyLines: (text: string) => string[];
buildListNode: (
@@ -75,6 +78,52 @@ interface FoundPlaceholder {
pos: number;
}
+// A private-use character has no meaning in markdown, so it can't turn into
+// syntax such as a checkbox or an emoji the way a letter could.
+const PROBE_TEXT = "\uE000";
+
+/** Reuses a resolved head for the first line so function heads run once per line. */
+function headWithFirst(
+ head: string | ((previous?: string) => string),
+ first: string
+): (previous?: string) => string {
+ return (previous) =>
+ previous === undefined
+ ? first
+ : typeof head === "function"
+ ? head(previous)
+ : head;
+}
+
+function singleChild(content: Node | Fragment | null | undefined): Node | null {
+ return content?.childCount === 1 ? content.firstChild : null;
+}
+
+function flattenSelection(
+ doc: Node | Fragment,
+ from = 0,
+ to = doc instanceof Fragment ? doc.size : doc.content.size
+) {
+ const nodes: Node[] = [];
+ const segments: { start: number; end: number; pos: number }[] = [];
+ let size = 0;
+ doc.nodesBetween(from, to, (node, pos) => {
+ if (!node.isText && !node.isAtom) {
+ return true;
+ }
+ if (node.isText) {
+ const lower = Math.max(from - pos, 0);
+ node = node.cut(lower, Math.min(to - pos, node.nodeSize));
+ pos += lower;
+ }
+ nodes.push(node.mark([]));
+ segments.push({ start: size, end: size + node.nodeSize, pos });
+ size += node.nodeSize;
+ return false;
+ });
+ return { content: Fragment.fromArray(nodes), segments };
+}
+
function isPlainTextFragment(fragment: Fragment, schema: Schema): boolean {
return fragment.content.every((node) => {
if (node.isText) {
@@ -114,6 +163,7 @@ export default class ProsemirrorTextManipulation implements TextManipulation {
autocompleteHandler: AutocompleteHandler;
state = trackedObject<ToolbarState & Record<string, unknown>>({});
convertFromMarkdown: (markdown: string) => Node;
+ tryConvertFromMarkdown: (markdown: string) => Node | null;
convertToMarkdown: (doc: Node | Fragment | Slice) => string;
splitNonEmptyLines: (text: string) => string[];
buildListNode: (
@@ -130,6 +180,7 @@ export default class ProsemirrorTextManipulation implements TextManipulation {
schema,
view,
convertFromMarkdown,
+ tryConvertFromMarkdown,
convertToMarkdown,
splitNonEmptyLines,
buildListNode,
@@ -141,6 +192,7 @@ export default class ProsemirrorTextManipulation implements TextManipulation {
this.schema = schema;
this.view = view;
this.convertFromMarkdown = convertFromMarkdown;
+ this.tryConvertFromMarkdown = tryConvertFromMarkdown;
this.convertToMarkdown = convertToMarkdown;
this.splitNonEmptyLines = splitNonEmptyLines;
this.buildListNode = buildListNode;
@@ -159,10 +211,33 @@ export default class ProsemirrorTextManipulation implements TextManipulation {
});
}
- getSelected(): SelectedText {
+ getSelected(trimLeading?: boolean | null | ""): SelectedText {
const { state } = this.view;
- const { from, to } = state.selection;
- const value = this.convertToMarkdown(state.selection.content());
+ const { to } = state.selection;
+ let { from } = state.selection;
+ if (trimLeading && state.selection instanceof TextSelection) {
+ let found = false;
+ state.doc.nodesBetween(from, to, (node, pos) => {
+ if (found) {
+ return false;
+ }
+ if (node.isText) {
+ const start = Math.max(from - pos, 0);
+ const text = node.text!.slice(start, to - pos);
+ const whitespace = /^\s*/.exec(text)![0].length;
+ from = pos + start + whitespace;
+ found = whitespace < text.length;
+ } else if (node.isInline) {
+ found = true;
+ }
+ return !found;
+ });
+ }
+ const selection =
+ from === state.selection.from
+ ? state.selection
+ : TextSelection.create(state.doc, from, to);
+ const value = this.convertToMarkdown(selection.content());
// Document-absolute pre/post to match textarea semantics
const pre = state.doc.textBetween(0, from, "\n", "\n");
@@ -217,46 +292,37 @@ export default class ProsemirrorTextManipulation implements TextManipulation {
applySurroundSelection(
head: string | ((previous?: string) => string),
tail: string,
- exampleKey: string
+ exampleKey: string,
+ opts?: SurroundOptions
): void {
- this.applySurround(this.getSelected(), head, tail, exampleKey);
+ this.applySurround(this.getSelected(), head, tail, exampleKey, opts);
}
applySurround(
sel: SelectedText,
head: string | ((previous?: string) => string),
tail: string,
- exampleKey: string
+ exampleKey: string,
+ opts?: SurroundOptions
): void {
- const applySurroundMap: Partial<Record<string, MarkType>> = {
- italic_text: this.schema.marks.em,
- bold_text: this.schema.marks.strong,
- code_title: this.schema.marks.code,
- };
+ this.#restoreSelection(sel);
+ const hval = typeof head === "function" ? head() : head;
+ const needsBlockSpacing =
+ opts?.useBlockMode &&
+ !opts.multiline &&
+ !this.view.state.selection.empty &&
+ this.#selectedMarkdownOr(exampleKey).includes("\n");
+ const mark = needsBlockSpacing ? null : this.#probeMark(hval, tail);
- const mark = applySurroundMap[exampleKey];
if (mark) {
- toggleMark(mark)(this.view.state, this.view.dispatch);
-
- return;
- }
-
- const { state } = this.view;
- const { from, to, empty } = state.selection;
-
- let text;
- if (empty) {
- text = i18n(`composer.${exampleKey}`);
+ toggleMark(mark.type, mark.attrs)(this.view.state, this.view.dispatch);
+ } else if (opts?.multiline && !this.view.state.selection.empty) {
+ this.#applySurroundLines(headWithFirst(head, hval), tail, opts);
} else {
- const selectedFragment = state.doc.slice(from, to).content;
- text = this.convertToMarkdown(selectedFragment);
+ this.#applySurroundFallback(hval, tail, exampleKey, opts);
}
- const block = firstBlockOf(this.convertFromMarkdown(head + text + tail));
-
- this.view.dispatch(
- this.view.state.tr.replaceWith(sel.start, sel.end, block)
- );
+ this.focus();
}
applyLink(url: string): void {
@@ -298,111 +364,59 @@ export default class ProsemirrorTextManipulation implements TextManipulation {
}
applyList(
- _selection: SelectedText,
+ sel: SelectedText,
head: string | ((previous?: string) => string),
- exampleKey: string
+ exampleKey: string,
+ opts?: SurroundOptions
): void {
- let command: Command | undefined;
-
- const findParentList = () => {
- const $from = this.view.state.selection.$from;
- for (let depth = $from.depth; depth > 0; depth--) {
- const node = $from.node(depth);
- if (
- node.type === this.schema.nodes.bullet_list ||
- node.type === this.schema.nodes.ordered_list
- ) {
- return {
- node,
- pos: $from.before(depth),
- type: node.type,
- };
- }
- }
- return null;
- };
-
- const replaceSelectionWithList = (targetType: NodeType) => {
- const { state } = this.view;
- const selectedContent = state.selection.content().content;
-
- if (!isPlainTextFragment(selectedContent, this.schema)) {
- return false;
- }
-
- const selectedText = state.doc.textBetween(
- state.selection.from,
- state.selection.to,
- "\n",
- "\n"
- );
- const lines = this.splitNonEmptyLines(selectedText);
-
- if (lines.length <= 1) {
- return false;
- }
-
- const listNode = this.buildListNode(this.schema, targetType, lines);
-
- this.view.dispatch(
- state.tr.replaceSelectionWith(listNode).scrollIntoView()
- );
+ this.#restoreSelection(sel);
+ const hval = typeof head === "function" ? head() : head;
+ const nextHead = headWithFirst(head, hval);
+ const doc =
+ hval == null ? null : this.tryConvertFromMarkdown(hval + PROBE_TEXT);
+ const probe = singleChild(doc);
+
+ if (!probe) {
+ this.#applyListFallback(nextHead, exampleKey, opts);
+ return;
+ }
- return true;
- };
+ const isList =
+ probe.type === this.schema.nodes.bullet_list ||
+ probe.type === this.schema.nodes.ordered_list;
+ const container = isList ? singleChild(probe) : probe;
+ const paragraph = singleChild(container);
+ if (
+ (isList && container?.type !== this.schema.nodes.list_item) ||
+ paragraph?.type !== this.schema.nodes.paragraph
+ ) {
+ this.#applyListFallback(nextHead, exampleKey, opts);
+ return;
+ }
+ const isPlainProbe = singleChild(paragraph)?.eq(
+ this.schema.text(PROBE_TEXT)
+ );
- if (exampleKey === "list_item") {
- const targetType =
- head === "* "
- ? this.schema.nodes.bullet_list
- : this.schema.nodes.ordered_list;
-
- const parentList = findParentList();
-
- if (parentList) {
- if (parentList.type === targetType) {
- // Same list type - toggle off (lift)
- command = liftListItem(this.schema.nodes.list_item);
- } else {
- // Different list type - convert selection
- // We achieve this by lifting out of the current list, then wrapping in the new type
- command = (state, dispatch) => {
- if (dispatch) {
- const liftCmd = liftListItem(this.schema.nodes.list_item);
- let lifted = false;
- liftCmd(state, (tr) => {
- dispatch(tr);
- lifted = true;
- });
-
- if (lifted) {
- // If lift succeeded, now wrap in the new list type
- // We need to re-fetch state from view since dispatch updated it
- wrapInList(targetType)(this.view.state, dispatch);
- }
- }
- return true;
- };
- }
- } else {
- if (replaceSelectionWithList(targetType)) {
- this.focus();
- return;
- }
+ if (
+ isPlainProbe &&
+ isList &&
+ (probe.type !== this.schema.nodes.ordered_list || probe.attrs.order === 1)
+ ) {
+ this.#toggleListType(probe.type);
+ this.focus();
+ return;
+ }
- // Not in a list - wrap in the target type
- command = wrapInList(targetType);
- }
- } else if (exampleKey === "blockquote_text") {
- command = inNode(this.view.state, this.schema.nodes.blockquote)
+ if (isPlainProbe && probe.type === this.schema.nodes.blockquote) {
+ const command = inNode(this.view.state, this.schema.nodes.blockquote)
? lift
: wrapIn(this.schema.nodes.blockquote);
- } else {
- throw new Error("Unknown exampleKey");
+ command(this.view.state, this.view.dispatch);
+ this.focus();
+ return;
}
- command?.(this.view.state, this.view.dispatch);
- this.focus();
+ this.#applyListFallback(nextHead, exampleKey, opts);
}
applyHeading(_selection: SelectedText, level: number): void {
@@ -677,6 +691,442 @@ export default class ProsemirrorTextManipulation implements TextManipulation {
...this.customState(this.view.state),
});
}
+
+ #probeMark(head: string, tail: string): Mark | null {
+ const doc = this.tryConvertFromMarkdown(head + PROBE_TEXT + tail);
+ const paragraph = singleChild(doc);
+ const text =
+ paragraph?.type === this.schema.nodes.paragraph
+ ? singleChild(paragraph)
+ : null;
+
+ return text?.isText && text.text === PROBE_TEXT && text.marks.length === 1
+ ? text.marks[0]!
+ : null;
+ }
+
+ #restoreSelection(sel: SelectedText): void {
+ const { state } = this.view;
+ if (sel.start !== state.selection.from || sel.end !== state.selection.to) {
+ this.view.dispatch(
+ state.tr.setSelection(
+ TextSelection.between(
+ state.doc.resolve(sel.start),
+ state.doc.resolve(sel.end)
+ )
+ )
+ );
+ }
+ }
+
+ #applySurroundLines(
+ head: (previous?: string) => string,
+ tail: string,
+ opts: SurroundOptions
+ ): void {
+ const { state } = this.view;
+ const { from, to } = state.selection;
+ const lines: { from: number; to: number; head: string }[] = [];
+ let previous: string | undefined;
+ const addLine = (start: number, end: number) => {
+ if (start < end || opts.applyEmptyLines) {
+ previous = head(previous);
+ lines.push({ from: start, to: end, head: previous });
+ }
+ };
+
+ state.doc.nodesBetween(from, to, (node, pos) => {
+ if (!node.isTextblock) {
+ return true;
+ }
+ let start = Math.max(from, pos + 1);
+ const end = Math.min(to, pos + 1 + node.content.size);
+ node.forEach((child, offset) => {
+ const childPos = pos + 1 + offset;
+ if (
+ child.type === this.schema.nodes.hard_break &&
+ childPos >= start &&
+ childPos < end
+ ) {
+ addLine(start, childPos);
+ start = childPos + child.nodeSize;
+ }
+ });
+ addLine(start, end);
+ return false;
+ });
+
+ const tr = state.tr;
+ for (const line of lines.reverse()) {
+ const text = this.convertToMarkdown(state.doc.slice(line.from, line.to));
+ this.#surroundRange(tr, line.from, line.to, text, line.head, tail, opts);
+ }
+ tr.setSelection(
+ TextSelection.between(
+ tr.doc.resolve(tr.mapping.map(from, -1)),
+ tr.doc.resolve(tr.mapping.map(to, 1))
+ )
+ );
+ this.view.dispatch(tr);
+ }
+
+ #applySurroundFallback(
+ head: string,
+ tail: string,
+ exampleKey: string,
+ opts?: SurroundOptions
+ ): void {
+ const { state } = this.view;
+ const { from, to } = state.selection;
+ const text = this.#selectedMarkdownOr(exampleKey);
+ const { tr, prefix } = this.#surroundRange(
+ state.tr,
+ from,
+ to,
+ text,
+ head,
+ tail,
+ opts
+ );
+ this.#selectInserted(tr, from, to, text, prefix);
+ this.view.dispatch(tr);
+ }
+
+ #surroundRange(
+ tr: Transaction,
+ from: number,
+ to: number,
+ text: string,
+ head: string,
+ tail: string,
+ opts?: SurroundOptions
+ ): { tr: Transaction; prefix: Fragment } {
+ const $from = tr.doc.resolve(from);
+ const $to = tr.doc.resolve(to);
+ const withinTextblock = $from.sameParent($to) && $from.parent.isTextblock;
+ const startsLine =
+ $from.parentOffset === 0 ||
+ $from.nodeBefore?.type === this.schema.nodes.hard_break;
+ let replacementFrom = from;
+ let replacementTo = to;
+
+ if (!tail && from !== to && withinTextblock && startsLine) {
+ replacementTo = $to.end();
+ if (opts?.multiline) {
+ $from.parent.forEach((child, offset) => {
+ const pos = $from.start() + offset;
+ if (child.type === this.schema.nodes.hard_break && pos >= from) {
+ replacementTo = Math.min(replacementTo, pos);
+ }
+ });
+ }
+ text = this.convertToMarkdown(tr.doc.slice(from, replacementTo));
+ }
+
+ const useBlockMode =
+ opts?.useBlockMode || (tail.length > 0 && !withinTextblock);
+ if (useBlockMode && text.includes("\n")) {
+ if (!head.endsWith("\n")) {
+ head += "\n";
+ }
+ if (!tail.startsWith("\n")) {
+ tail = "\n" + tail;
+ }
+ }
+
+ const markdown = head + text + tail;
+ const partialTextblock =
+ withinTextblock &&
+ (!startsLine ||
+ (tail.length > 0 && $from.parentOffset > 0) ||
+ (tail.length > 0 && $to.parentOffset < $from.parent.content.size));
+ const inlineContent = partialTextblock
+ ? this.#convertInlineMarkdown(markdown)
+ : null;
+ if (inlineContent) {
+ return {
+ tr: tr.replaceWith(replacementFrom, replacementTo, inlineContent),
+ prefix: this.#surroundPrefix(head, tail, true),
+ };
+ }
+ const parsed = this.convertFromMarkdown(markdown);
+ if (
+ !tail &&
+ withinTextblock &&
+ startsLine &&
+ (parsed.childCount !== 1 ||
+ parsed.firstChild?.type !== this.schema.nodes.paragraph)
+ ) {
+ if ($from.nodeBefore?.type === this.schema.nodes.hard_break) {
+ replacementFrom--;
+ }
+ if (
+ tr.doc.resolve(replacementTo).nodeAfter?.type ===
+ this.schema.nodes.hard_break
+ ) {
+ replacementTo++;
+ }
+ }
+ return {
+ tr: this.#replaceWithParsed(tr, replacementFrom, replacementTo, parsed),
+ prefix: this.#surroundPrefix(head, tail),
+ };
+ }
+
+ // Leading text keeps block rules from claiming the markup, like mid-line
+ // markdown when cooked.
+ #convertInlineMarkdown(markdown: string): Fragment | null {
+ const lead = PROBE_TEXT + " ";
+ const doc = this.tryConvertFromMarkdown(lead + markdown);
+ const paragraph = singleChild(doc);
+ const first =
+ paragraph?.type === this.schema.nodes.paragraph
+ ? paragraph.firstChild
+ : null;
+
+ return first?.isText && first.text!.startsWith(lead)
+ ? paragraph!.content.cut(lead.length)
+ : null;
+ }
+
+ #replaceWithParsed(
+ tr: Transaction,
+ from: number,
+ to: number,
+ doc: Node
+ ): Transaction {
+ const paragraph =
+ doc.childCount === 1 &&
+ doc.firstChild?.type === this.schema.nodes.paragraph
+ ? doc.firstChild
+ : null;
+
+ if (paragraph) {
+ return tr.replaceWith(from, to, paragraph.content);
+ }
+
+ // replaceRange would also swallow covered non-defining ancestors such as
+ // a blockquote, so a fully covered textblock is replaced explicitly.
+ const $from = tr.doc.resolve(from);
+ const $to = tr.doc.resolve(to);
+ const wholeTextblock =
+ $from.sameParent($to) &&
+ $from.parent.isTextblock &&
+ $from.parentOffset === 0 &&
+ $to.parentOffset === $to.parent.content.size &&
+ $from
+ .node(-1)
+ .canReplace($from.index(-1), $from.indexAfter(-1), doc.content);
+
+ return wholeTextblock
+ ? tr.replaceWith($from.before(), $to.after(), doc.content)
+ : tr.replaceRange(from, to, new Slice(doc.content, 0, 0));
+ }
+
+ #surroundPrefix(head: string, tail: string, inline = false): Fragment {
+ const markdown = head + PROBE_TEXT + tail;
+ const doc = inline
+ ? this.#convertInlineMarkdown(markdown)
+ : this.tryConvertFromMarkdown(markdown);
+ if (!doc) {
+ return Fragment.empty;
+ }
+
+ const { content } = flattenSelection(doc);
+ let prefix = Fragment.empty;
+ content.forEach((node, offset) => {
+ const index = node.isText ? node.text!.indexOf(PROBE_TEXT) : -1;
+ if (index >= 0) {
+ prefix = content.cut(0, offset + index);
+ }
+ });
+ return prefix;
+ }
+
+ #selectInserted(
+ tr: Transaction,
+ from: number,
+ to: number,
+ text: string,
+ prefix = Fragment.empty
+ ): void {
+ // The replace step knows where the content landed, even when it was
+ // placed before the selection's textblock.
+ let start = from;
+ let end = to;
+ tr.mapping.maps.at(-1)?.forEach((_, __, newStart, newEnd) => {
+ start = newStart;
+ end = newEnd;
+ });
+ const parsed = this.tryConvertFromMarkdown(text);
+ const expected = parsed
+ ? flattenSelection(parsed).content
+ : Fragment.from(text ? this.schema.text(text) : null);
+ const { content, segments } = flattenSelection(tr.doc, start, end);
+ const firstNode = expected.firstChild;
+ // A wrapper can repeat the selected text, so prefer the parsed inner boundary.
+ let match: number | undefined =
+ prefix.size > 0 &&
+ content.cut(0, prefix.size).eq(prefix) &&
+ content.cut(prefix.size, prefix.size + expected.size).eq(expected)
+ ? prefix.size
+ : undefined;
+ if (firstNode) {
+ content.forEach((node, offset) => {
+ if (match !== undefined) {
+ return;
+ }
+ let index =
+ node.isText && firstNode.isText
+ ? node.text!.indexOf(firstNode.text!)
+ : node.eq(firstNode)
+ ? 0
+ : -1;
+ while (index >= 0) {
+ if (
+ content
+ .cut(offset + index, offset + index + expected.size)
+ .eq(expected)
+ ) {
+ match = offset + index;
+ return;
+ }
+ if (!node.isText || !firstNode.isText) {
+ break;
+ }
+ index = node.text!.indexOf(firstNode.text!, index + 1);
+ }
+ });
+ }
+
+ if (firstNode && match !== undefined) {
+ const matchStart = match;
+ const first = segments.find((segment) => segment.end > matchStart)!;
+ const lastIndex = matchStart + expected.size - 1;
+ const last = segments.find((segment) => segment.end > lastIndex)!;
+ const selectionFrom = first.pos + matchStart - first.start;
+ tr.setSelection(
+ expected.childCount === 1 && NodeSelection.isSelectable(firstNode)
+ ? NodeSelection.create(tr.doc, selectionFrom)
+ : TextSelection.create(
+ tr.doc,
+ selectionFrom,
+ last.pos + lastIndex - last.start + 1
+ )
+ );
+ } else if (
+ content.childCount === 1 &&
+ NodeSelection.isSelectable(content.firstChild!)
+ ) {
+ tr.setSelection(NodeSelection.create(tr.doc, segments[0]!.pos));
+ } else {
+ tr.setSelection(
+ TextSelection.between(tr.doc.resolve(start), tr.doc.resolve(end))
+ );
+ }
+ }
+
+ #toggleListType(targetType: NodeType): void {
+ const { state } = this.view;
+ const { $from } = state.selection;
+ const { bullet_list, ordered_list, list_item } = this.schema.nodes;
+
+ let currentListType: NodeType | null = null;
+ for (let depth = $from.depth; depth > 0; depth--) {
+ const { type } = $from.node(depth);
+ if (type === bullet_list || type === ordered_list) {
+ currentListType = type;
+ break;
+ }
+ }
+
+ if (!currentListType) {
+ const content = state.selection.content().content;
+ const lines = this.splitNonEmptyLines(
+ state.doc.textBetween(
+ state.selection.from,
+ state.selection.to,
+ "\n",
+ "\n"
+ )
+ );
+ if (isPlainTextFragment(content, this.schema) && lines.length > 1) {
+ const list = this.buildListNode(this.schema, targetType, lines);
+ this.view.dispatch(
+ state.tr.replaceSelectionWith(list).scrollIntoView()
+ );
+ return;
+ }
+ wrapInList(targetType)(state, this.view.dispatch);
+ return;
+ }
+
+ if (currentListType === targetType) {
+ liftListItem(list_item)(state, this.view.dispatch);
+ return;
+ }
+
+ // Lifting and re-wrapping in one transaction keeps the switch a single undo step.
+ liftListItem(list_item)(state, (tr) => {
+ const range = tr.selection.$from.blockRange(tr.selection.$to);
+ if (range && wrapRangeInList(tr, range, targetType)) {
+ this.view.dispatch(tr);
+ }
+ });
+ }
+
+ #applyListFallback(
+ head: (previous?: string) => string,
+ exampleKey: string,
+ opts?: SurroundOptions
+ ): void {
+ const { state } = this.view;
+ const { from, to } = state.selection;
+ const text = this.#selectedMarkdownOr(exampleKey);
+ const firstHead = head();
+ if (opts?.multiline === false) {
+ this.#applySurroundFallback(firstHead, "", exampleKey, opts);
+ this.focus();
+ return;
+ }
+
+ let previous: string | undefined;
+ const result = text
+ .split("\n")
+ .map((line) => {
+ if (!opts?.applyEmptyLines && !line.length) {
+ return line;
+ }
+ previous = head(previous);
+ return previous + line;
+ })
+ .join("\n");
+
+ const tr = this.#replaceWithParsed(
+ state.tr,
+ from,
+ to,
+ this.convertFromMarkdown(result)
+ );
+
+ this.#selectInserted(
+ tr,
+ from,
+ to,
+ text,
+ this.#surroundPrefix(firstHead, "")
+ );
+
+ this.view.dispatch(tr);
+ this.focus();
+ }
+
+ #selectedMarkdownOr(exampleKey: string): string {
+ const { from, to, empty } = this.view.state.selection;
+ return empty
+ ? i18n(`composer.${exampleKey}`)
+ : this.convertToMarkdown(this.view.state.doc.slice(from, to));
+ }
}
class ProsemirrorAutocompleteHandler implements AutocompleteHandler {
diff --git a/frontend/discourse/tests/helpers/rich-editor-helper.gjs b/frontend/discourse/tests/helpers/rich-editor-helper.gjs
index 145aaa05a2f..42e6b11b7b8 100644
--- a/frontend/discourse/tests/helpers/rich-editor-helper.gjs
+++ b/frontend/discourse/tests/helpers/rich-editor-helper.gjs
@@ -9,6 +9,7 @@ export async function setupRichEditor(assert, markdown, opts = {}) {
disabled = false,
multiToggle = false,
markdownOptions,
+ onSetup,
withMenus = false,
} = opts;
const self = new (class {
@@ -17,6 +18,7 @@ export async function setupRichEditor(assert, markdown, opts = {}) {
})();
const handleSetup = (textManipulation) => {
self.view = textManipulation.view;
+ onSetup?.(textManipulation);
};
await render(
diff --git a/frontend/discourse/tests/integration/components/prosemirror-editor/text-manipulation-test.gjs b/frontend/discourse/tests/integration/components/prosemirror-editor/text-manipulation-test.gjs
new file mode 100644
index 00000000000..681e6f88c1f
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/prosemirror-editor/text-manipulation-test.gjs
@@ -0,0 +1,922 @@
+import { tracked } from "@glimmer/tracking";
+import { render, settled, waitFor } from "@ember/test-helpers";
+import { closeHistory, undo } from "prosemirror-history";
+import { NodeSelection, TextSelection } from "prosemirror-state";
+import { module, test } from "qunit";
+import ProsemirrorEditor from "discourse/static/prosemirror/components/prosemirror-editor";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+async function setupEditor() {
+ const state = new (class {
+ @tracked value = "";
+ textManipulation = null;
+ })();
+
+ const handleSetup = (tm) => {
+ state.textManipulation = tm;
+ };
+
+ await render(
+ <template>
+ <ProsemirrorEditor @onSetup={{handleSetup}} @value={{state.value}} />
+ </template>
+ );
+
+ await waitFor(".ProseMirror");
+ await settled();
+
+ return state;
+}
+
+function setContent(state, markdown) {
+ const { view, convertFromMarkdown } = state.textManipulation;
+ const doc = convertFromMarkdown(markdown);
+ view.dispatch(
+ view.state.tr.replaceWith(0, view.state.doc.content.size, doc.content)
+ );
+}
+
+function selectAll(state) {
+ const { view } = state.textManipulation;
+ const { doc } = view.state;
+
+ const from = TextSelection.atStart(doc).from;
+ const to = TextSelection.atEnd(doc).to;
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(doc, from, to))
+ );
+}
+
+function placeCursor(state) {
+ const { view } = state.textManipulation;
+ const pos = TextSelection.atStart(view.state.doc).from;
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(view.state.doc, pos))
+ );
+}
+
+function countNodes(state, typeName) {
+ let count = 0;
+ state.textManipulation.view.state.doc.descendants((node) => {
+ if (node.type.name === typeName) {
+ count++;
+ }
+ });
+ return count;
+}
+
+function getMarkdown(state) {
+ const { view, convertToMarkdown } = state.textManipulation;
+ return convertToMarkdown(view.state.doc);
+}
+
+module(
+ "Integration | Component | ProsemirrorEditor | Text manipulation | applySurround",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("surrounds formatted lines independently in multiline mode", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "**one**\n_two_");
+ selectAll(state);
+ state.textManipulation.applySurroundSelection(
+ "<kbd>",
+ "</kbd>",
+ "code_text",
+ { multiline: true }
+ );
+ assert
+ .dom(".ProseMirror kbd")
+ .exists({ count: 2 }, "each line has its own wrapper");
+ assert
+ .dom(".ProseMirror kbd strong, .ProseMirror strong kbd")
+ .hasText("one", "bold survives");
+ assert
+ .dom(".ProseMirror kbd em, .ProseMirror em kbd")
+ .hasText("two", "italic survives");
+ assert.false(
+ state.textManipulation.view.state.selection.empty,
+ "the formatted content stays selected"
+ );
+ });
+
+ for (const [name, head, tail] of [
+ ["bare delimiters", "```", "```"],
+ ["delimiters with newlines", "```\n", "\n```"],
+ ]) {
+ test(`useBlockMode separates multiline content with ${name}`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "first\nsecond");
+ selectAll(state);
+
+ state.textManipulation.applySurroundSelection(head, tail, "code_text", {
+ multiline: false,
+ useBlockMode: true,
+ });
+
+ assert
+ .dom(".ProseMirror pre code")
+ .hasText(
+ "first\nsecond",
+ "both lines are inside the code block without extra blank lines"
+ );
+ });
+ }
+
+ test("useBlockMode keeps single-line code inline", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "before secret after");
+ state.textManipulation.selectText(8, 6);
+
+ state.textManipulation.applySurroundSelection("```", "```", "wrap_text", {
+ multiline: false,
+ useBlockMode: true,
+ });
+
+ assert
+ .dom(".ProseMirror p code")
+ .hasText("secret", "the selection is wrapped");
+ assert
+ .dom(".ProseMirror br")
+ .doesNotExist("no boundary breaks are added");
+ assert
+ .dom(".ProseMirror p")
+ .hasText("before secret after", "surrounding text is preserved");
+ });
+
+ test("multiline surround preserves text outside the selection and undoes in one step", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello one\ntwo world");
+ const { view } = state.textManipulation;
+ view.dispatch(
+ closeHistory(
+ view.state.tr.setSelection(
+ TextSelection.create(view.state.doc, 7, 14)
+ )
+ )
+ );
+ state.textManipulation.applySurroundSelection(
+ "<kbd>",
+ "</kbd>",
+ "code_text",
+ { multiline: true }
+ );
+ assert
+ .dom(".ProseMirror kbd:first-of-type")
+ .hasText("one", "only the selected first line is wrapped");
+ assert
+ .dom(".ProseMirror kbd:last-of-type")
+ .hasText("two", "only the selected last line is wrapped");
+ undo(view.state, view.dispatch);
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "hello one\ntwo world",
+ "one undo restores both lines"
+ );
+ });
+
+ test("multiline surround preserves the containing blockquote", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "> one\n> two");
+ selectAll(state);
+ state.textManipulation.applySurroundSelection(
+ "<kbd>",
+ "</kbd>",
+ "code_text",
+ { multiline: true }
+ );
+ assert
+ .dom(".ProseMirror blockquote kbd")
+ .exists({ count: 2 }, "both lines stay inside the quote");
+ });
+
+ test("applies a multiline heading prefix across hard breaks", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "one\ntwo");
+ selectAll(state);
+ state.textManipulation.applySurroundSelection("# ", "", "heading_text", {
+ multiline: true,
+ });
+ assert
+ .dom(".ProseMirror h1")
+ .exists({ count: 2 }, "each selected line becomes a heading");
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "# one\n\n# two",
+ "both lines retain their content without literal prefixes"
+ );
+ });
+
+ test("multiline heading prefixes preserve unselected boundary text", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello\nworld\nafter");
+ state.textManipulation.selectText(4, 5);
+ state.textManipulation.applySurroundSelection("# ", "", "heading_text", {
+ multiline: true,
+ });
+ assert
+ .dom(".ProseMirror > p:first-child")
+ .hasText("hel# lo", "a prefix in the middle of a line stays literal");
+ assert
+ .dom(".ProseMirror h1")
+ .hasText("world", "a heading includes the rest of its line");
+ assert
+ .dom(".ProseMirror > p:last-child")
+ .hasText("after", "the following line is preserved");
+ assert
+ .dom(".ProseMirror br")
+ .doesNotExist("block boundaries replace the original hard breaks");
+ });
+
+ test("honors a caller-adjusted surround selection", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+ const selected = state.textManipulation.getSelected();
+ selected.start = 7;
+ selected.value = "world";
+ state.textManipulation.applySurround(
+ selected,
+ "<small>",
+ "</small>",
+ "wrap_text"
+ );
+ assert
+ .dom(".ProseMirror small")
+ .hasText("world", "only the supplied range is wrapped");
+ assert
+ .dom(".ProseMirror p")
+ .hasText("hello world", "the preceding text is retained");
+ });
+
+ for (const [head, tail] of [
+ ["hello ", " suffix"],
+ ["prefix ", " hello"],
+ ["hello ", " hello"],
+ ]) {
+ test(`restores the original content selection with repeated wrapper text (${head}, ${tail})`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello");
+ selectAll(state);
+
+ state.textManipulation.applySurroundSelection(head, tail, "wrap_text", {
+ multiline: false,
+ });
+
+ const { view } = state.textManipulation;
+ view.dispatch(view.state.tr.insertText("replacement"));
+
+ assert
+ .dom(".ProseMirror p")
+ .hasText(
+ `${head}replacement${tail}`,
+ "typing replaces the original content and preserves the wrapper"
+ );
+ });
+ }
+
+ for (const head of ["# hello "]) {
+ test(`restores the content selection with a repeated inline prefix (${head})`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "before hello after");
+ state.textManipulation.selectText(8, 5);
+
+ state.textManipulation.applySurroundSelection(
+ head,
+ " suffix",
+ "wrap_text",
+ { multiline: false }
+ );
+
+ const { view } = state.textManipulation;
+ view.dispatch(view.state.tr.insertText("replacement"));
+
+ assert
+ .dom(".ProseMirror p")
+ .hasText(
+ `before ${head}replacement suffix after`,
+ "typing preserves the literal inline prefix and surrounding text"
+ );
+ });
+ }
+
+ test("preserves formatting and selection after an inline surround", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello **world**");
+ state.textManipulation.selectText(7, 5);
+ state.textManipulation.applySurroundSelection(
+ "<small>",
+ "</small>",
+ "wrap_text",
+ { multiline: false }
+ );
+ assert
+ .dom(".ProseMirror small strong, .ProseMirror strong small")
+ .hasText("world", "existing formatting is preserved");
+ const { view } = state.textManipulation;
+ assert.strictEqual(
+ view.state.doc.textBetween(
+ view.state.selection.from,
+ view.state.selection.to
+ ),
+ "world",
+ "the content remains selected"
+ );
+ });
+
+ test("selects an image created from a selected URL", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "https://example.com/image.png");
+ selectAll(state);
+ state.textManipulation.applySurroundSelection(
+ '<img src="',
+ '" alt="">',
+ "wrap_text",
+ { multiline: false }
+ );
+ await settled();
+ assert
+ .dom(".ProseMirror img")
+ .hasAttribute(
+ "src",
+ "https://example.com/image.png",
+ "the selected URL becomes an image"
+ );
+ assert.strictEqual(
+ state.textManipulation.view.state.selection.node?.type.name,
+ "image",
+ "the image is selected"
+ );
+ });
+
+ for (const [edge, markdown] of [
+ ["leading", "![a](https://example.com/image.png) hello"],
+ ["trailing", "hello ![a](https://example.com/image.png)"],
+ ]) {
+ test(`preserves a selected ${edge} image when surrounding text`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, markdown);
+ selectAll(state);
+ state.textManipulation.applySurroundSelection(
+ "<small>",
+ "</small>",
+ "wrap_text",
+ {
+ multiline: false,
+ }
+ );
+ await settled();
+ const { view } = state.textManipulation;
+ assert
+ .dom(".ProseMirror small img")
+ .exists("the image is inside the wrapper");
+ const { from, to } = view.state.selection;
+ assert.strictEqual(
+ view.state.doc.textBetween(from, to).trim(),
+ "hello",
+ "the text remains selected"
+ );
+ view.dispatch(view.state.tr.insertText("replacement"));
+ assert
+ .dom(".ProseMirror img")
+ .doesNotExist("replacing the selection removes the image too");
+ assert
+ .dom(".ProseMirror")
+ .hasText(
+ "replacement",
+ "typing replaces the complete selected content"
+ );
+ });
+ }
+
+ test("trims leading whitespace in toolbar selections", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ state.textManipulation.selectText(6, 6);
+ const selected = state.textManipulation.getSelected(true);
+ state.textManipulation.applySurround(
+ selected,
+ "<small>",
+ "</small>",
+ "wrap_text"
+ );
+ assert
+ .dom(".ProseMirror small")
+ .hasText("world", "leading whitespace stays outside the wrapper");
+ assert.strictEqual(
+ selected.start,
+ 7,
+ "the selection starts after whitespace"
+ );
+ });
+
+ test("keeps a selected block whole when trimming leading whitespace", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "```\n indented\n```");
+ const { view } = state.textManipulation;
+ view.dispatch(
+ view.state.tr.setSelection(NodeSelection.create(view.state.doc, 0))
+ );
+ const selected = state.textManipulation.getSelected(true);
+ assert.strictEqual(selected.start, 0, "the selection is not trimmed");
+ assert.strictEqual(
+ selected.end,
+ view.state.doc.firstChild.nodeSize,
+ "the selection still covers the block"
+ );
+ });
+
+ for (const [name, head] of [
+ ["bold", "**"],
+ ["strikethrough", "~~"],
+ ]) {
+ test(`toggles the ${name} mark via parser detection`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+ state.textManipulation.applySurroundSelection(
+ head,
+ head,
+ `${name}_text`
+ );
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ `${head}hello world${head}`,
+ "the mark is applied"
+ );
+
+ selectAll(state);
+ state.textManipulation.applySurroundSelection(
+ head,
+ head,
+ `${name}_text`
+ );
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "hello world",
+ "the mark is removed"
+ );
+ });
+ }
+
+ test("preserves combined marks in the fallback", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+
+ state.textManipulation.applySurroundSelection("**_", "_**", "bold_text");
+
+ assert
+ .dom(".ProseMirror strong em, .ProseMirror em strong")
+ .hasText("hello world", "both marks are applied");
+ });
+
+ for (const [head, tail, selector, text] of [
+ ["> **", "**", "blockquote strong", "hello world"],
+ ["> prefix ", " suffix", "blockquote", "prefix hello world suffix"],
+ ["> > ", "", "blockquote blockquote", "hello world"],
+ ]) {
+ test(`preserves the content of the "${head}" block wrapper`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+
+ state.textManipulation.applySurroundSelection(
+ head,
+ tail,
+ "blockquote_text"
+ );
+
+ assert
+ .dom(`.ProseMirror ${selector}`)
+ .hasText(text, "the wrapper keeps its content");
+ assert
+ .dom(".ProseMirror > blockquote:first-child")
+ .exists("the replaced paragraph is not left behind");
+ });
+ }
+
+ test("uses the inline variant of block-capable markup inside a paragraph", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ const { view } = state.textManipulation;
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(view.state.doc, 7, 12))
+ );
+
+ state.textManipulation.applySurroundSelection(
+ "[wrap=note]",
+ "[/wrap]",
+ "wrap_text"
+ );
+
+ assert.strictEqual(countNodes(state, "wrap_inline"), 1);
+ assert.strictEqual(countNodes(state, "wrap_block"), 0);
+ assert.dom(".ProseMirror p").hasText("hello world");
+ });
+
+ test("uses the block variant of block-capable markup for a whole paragraph", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+
+ state.textManipulation.applySurroundSelection(
+ "[wrap=note]",
+ "[/wrap]",
+ "wrap_text"
+ );
+
+ assert.strictEqual(countNodes(state, "wrap_block"), 1);
+ assert.strictEqual(countNodes(state, "wrap_inline"), 0);
+ assert.dom(".ProseMirror p").hasText("hello world");
+ });
+
+ test("wraps a multi-paragraph selection as a block", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "first\n\nsecond");
+ selectAll(state);
+
+ state.textManipulation.applySurroundSelection(
+ "[wrap=note]",
+ "[/wrap]",
+ "wrap_text"
+ );
+
+ assert.strictEqual(countNodes(state, "wrap_block"), 1);
+ assert.strictEqual(
+ state.textManipulation.view.state.doc.firstChild.childCount,
+ 2,
+ "both paragraphs are inside the wrapper"
+ );
+ });
+
+ test("keeps a blockquote around a fully selected quoted paragraph", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "> quoted");
+ const { view } = state.textManipulation;
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(view.state.doc, 2, 8))
+ );
+
+ state.textManipulation.applySurroundSelection(
+ "[wrap=note]",
+ "[/wrap]",
+ "wrap_text"
+ );
+
+ assert.strictEqual(countNodes(state, "blockquote"), 1);
+ assert.strictEqual(countNodes(state, "wrap_block"), 1);
+ assert.dom(".ProseMirror blockquote p").hasText("quoted");
+ });
+
+ test("keeps a fully selected table cell when wrapping it as a block", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "| a | b |\n|---|---|\n| one | two |");
+ const { view } = state.textManipulation;
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(view.state.doc, 14, 17))
+ );
+
+ state.textManipulation.applySurroundSelection(
+ "[wrap=note]",
+ "[/wrap]",
+ "wrap_text"
+ );
+
+ const rowSizes = [];
+ view.state.doc.descendants((node) => {
+ if (node.type.name === "table_row") {
+ rowSizes.push(node.childCount);
+ }
+ });
+ assert.true(
+ rowSizes.every((size) => size === 2),
+ "every row keeps both cells"
+ );
+ assert.strictEqual(countNodes(state, "wrap_block"), 1);
+ });
+
+ for (const [where, pos] of [
+ ["after", 12],
+ ["before", 1],
+ ]) {
+ test(`selects the placeholder of a block inserted ${where} a paragraph`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ const { view } = state.textManipulation;
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(view.state.doc, pos))
+ );
+
+ state.textManipulation.applySurroundSelection(
+ "\n[wrap=note]\n",
+ "\n[/wrap]\n",
+ "wrap_text"
+ );
+
+ const { from, to } = view.state.selection;
+ assert.strictEqual(
+ view.state.doc.textBetween(from, to),
+ "Wrap content"
+ );
+ assert.strictEqual(countNodes(state, "wrap_block"), 1);
+ assert
+ .dom(".ProseMirror > p")
+ .hasText("hello world", "the paragraph is kept");
+ });
+ }
+
+ test("falls back to round-trip for unrecognized markup", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+
+ const sel = state.textManipulation.getSelected();
+ state.textManipulation.applySurround(sel, "<big>", "</big>", "big_text");
+
+ assert.strictEqual(getMarkdown(state).trim(), "<big>hello world</big>");
+ });
+
+ test("toggles stored marks when nothing is selected", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ placeCursor(state);
+ const { view } = state.textManipulation;
+
+ state.textManipulation.applySurroundSelection("**", "**", "bold_text");
+ view.dispatch(view.state.tr.insertText("bold "));
+
+ assert.dom(".ProseMirror strong").hasText("bold", "typing is bold");
+ assert.false(
+ getMarkdown(state).includes("strong text"),
+ "no placeholder is inserted"
+ );
+
+ state.textManipulation.applySurroundSelection("**", "**", "bold_text");
+ view.dispatch(view.state.tr.insertText("plain "));
+
+ assert
+ .dom(".ProseMirror strong")
+ .hasText("bold", "the stored mark is toggled off again");
+ });
+
+ test("inserts and selects a placeholder when nothing is selected in the fallback", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ placeCursor(state);
+ const { view } = state.textManipulation;
+
+ state.textManipulation.applySurroundSelection("**_", "_**", "bold_text");
+
+ const { from, to } = view.state.selection;
+ assert.strictEqual(
+ view.state.doc.textBetween(from, to),
+ "strong text",
+ "the placeholder is selected"
+ );
+ assert
+ .dom(".ProseMirror strong em, .ProseMirror em strong")
+ .hasText("strong text");
+ });
+ }
+);
+
+module(
+ "Integration | Component | ProsemirrorEditor | Text manipulation | applyList",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("honors inline mode for a custom prefix across paragraphs", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "one\n\ntwo");
+ selectAll(state);
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ "? ",
+ "list_item",
+ { multiline: false }
+ );
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "? one\n\ntwo",
+ "the prefix is applied once"
+ );
+ });
+
+ test("honors a caller-adjusted list selection", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+ const selected = state.textManipulation.getSelected();
+ selected.start = 7;
+ state.textManipulation.applyList(selected, "? ", "list_item");
+ assert
+ .dom(".ProseMirror p")
+ .hasText("hello ? world", "only the supplied range is prefixed");
+ });
+
+ for (const [name, head, exampleKey, applied] of [
+ ["bullet list", "* ", "list_item", "* hello world"],
+ [
+ "ordered list",
+ (i) => (!i ? "1. " : `${parseInt(i, 10) + 1}. `),
+ "list_item",
+ "1. hello world",
+ ],
+ ["blockquote", "> ", "blockquote_text", "> hello world"],
+ ]) {
+ test(`applies and removes a ${name} via parser detection`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ head,
+ exampleKey
+ );
+ assert.strictEqual(getMarkdown(state).trim(), applied, "it is applied");
+
+ placeCursor(state);
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ head,
+ exampleKey
+ );
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "hello world",
+ "it is removed"
+ );
+ });
+ }
+
+ test("creates a list item for each selected line", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "first line\nsecond line");
+ selectAll(state);
+
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ "* ",
+ "list_item"
+ );
+
+ assert
+ .dom(".ProseMirror li")
+ .exists({ count: 2 }, "each line becomes a separate list item");
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "* first line\n* second line",
+ "both lines are preserved"
+ );
+ });
+
+ test("switching list type is undone in one step", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "* first\n* second");
+ const { view } = state.textManipulation;
+ const list = view.state.doc.firstChild;
+ const from = TextSelection.atStart(list).from + 1;
+ const to = TextSelection.atEnd(list).to + 1;
+ view.dispatch(
+ closeHistory(
+ view.state.tr.setSelection(
+ TextSelection.create(view.state.doc, from, to)
+ )
+ )
+ );
+
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ "1. ",
+ "list_item"
+ );
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "1. first\n2. second",
+ "switching preserves both items"
+ );
+ assert
+ .dom(".ProseMirror ol li")
+ .exists({ count: 2 }, "both items change type");
+ undo(view.state, view.dispatch);
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "* first\n* second",
+ "one undo restores the original list"
+ );
+ });
+
+ test("switches from ordered list to bullet list", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "1. hello world");
+ placeCursor(state);
+
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ "* ",
+ "list_item"
+ );
+
+ assert.dom(".ProseMirror ul li").hasText("hello world");
+ assert.dom(".ProseMirror ol").doesNotExist();
+ });
+
+ test("falls back to markdown round-trip for unrecognized list head", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+
+ const sel = state.textManipulation.getSelected();
+ state.textManipulation.applyList(sel, "? ", "list_item");
+
+ assert.strictEqual(getMarkdown(state).trim(), "? hello world");
+ assert.strictEqual(
+ state.textManipulation.view.state.doc.childCount,
+ 1,
+ "the replaced paragraph is not left behind"
+ );
+ });
+
+ test("passes the previous head to function heads in the fallback", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "first\n\nsecond");
+ selectAll(state);
+
+ let calls = 0;
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ (previous) => {
+ calls++;
+ return previous === undefined
+ ? "?1 "
+ : `?${parseInt(previous.slice(1), 10) + 1} `;
+ },
+ "list_item"
+ );
+
+ assert.strictEqual(
+ getMarkdown(state).trim(),
+ "?1 first\n\n?2 second",
+ "each head derives from the previous one and blank lines do not advance it"
+ );
+ assert.strictEqual(calls, 2, "the head is computed once per line");
+ });
+
+ for (const [head, exampleKey, selector, text] of [
+ ["* [x] ", "list_item", "li", "[x] hello world"],
+ ["> prefix ", "blockquote_text", "blockquote", "prefix hello world"],
+ ]) {
+ test(`preserves additional content in the "${head}" prefix`, async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ head,
+ exampleKey
+ );
+
+ assert
+ .dom(`.ProseMirror ${selector}`)
+ .hasText(text, "the prefix content is retained");
+ });
+ }
+
+ test("preserves the starting number of an ordered list", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "hello world");
+ selectAll(state);
+
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ "3. ",
+ "list_item"
+ );
+
+ assert
+ .dom(".ProseMirror ol")
+ .hasAttribute("start", "3", "the parsed starting number is retained");
+ });
+
+ test("selects the inserted placeholder rather than an earlier copy of its text", async function (assert) {
+ const state = await setupEditor();
+ setContent(state, "List item and more");
+ const { view } = state.textManipulation;
+ view.dispatch(
+ view.state.tr.setSelection(TextSelection.create(view.state.doc, 19))
+ );
+
+ state.textManipulation.applyList(
+ state.textManipulation.getSelected(),
+ "? ",
+ "list_item"
+ );
+
+ const { from, to } = view.state.selection;
+ assert.strictEqual(view.state.doc.textBetween(from, to), "List item");
+ assert.strictEqual(from, 21, "the new occurrence is selected");
+ });
+ }
+);
diff --git a/frontend/discourse/tests/unit/static/prosemirror/serializer-test.js b/frontend/discourse/tests/unit/static/prosemirror/serializer-test.js
new file mode 100644
index 00000000000..950d88bc496
--- /dev/null
+++ b/frontend/discourse/tests/unit/static/prosemirror/serializer-test.js
@@ -0,0 +1,46 @@
+import { Schema } from "prosemirror-model";
+import { module, test } from "qunit";
+import { createSchema } from "discourse/static/prosemirror/core/schema";
+import Serializer from "discourse/static/prosemirror/core/serializer";
+
+module("Unit | Static | ProseMirror | serializer", function () {
+ test("preserves marks in inline slices and fragments", function (assert) {
+ const schema = createSchema([]);
+ const serializer = new Serializer([]);
+ const doc = schema.node("doc", null, [
+ schema.node("paragraph", null, [
+ schema.text("bold", [schema.marks.strong.create()]),
+ schema.text(" and "),
+ schema.text("italic", [schema.marks.em.create()]),
+ ]),
+ ]);
+ const slice = doc.slice(1, doc.content.size - 1);
+ assert.strictEqual(
+ serializer.convert(slice),
+ "**bold** and *italic*",
+ "an inline slice retains both marks"
+ );
+ assert.strictEqual(
+ serializer.convert(slice.content),
+ "**bold** and *italic*",
+ "an inline fragment retains both marks"
+ );
+ assert.strictEqual(
+ serializer.convert(doc.content),
+ "**bold** and *italic*",
+ "a block fragment is still serialized correctly"
+ );
+ });
+
+ test("supports an inline document without a paragraph type", function (assert) {
+ const schema = new Schema({
+ nodes: { doc: { content: "text*" }, text: {} },
+ });
+ const serializer = new Serializer([]);
+ assert.strictEqual(
+ serializer.convert(schema.node("doc", null, schema.text("hello"))),
+ "hello",
+ "minimal schemas can serialize inline documents"
+ );
+ });
+});
diff --git a/plugins/checklist/test/javascripts/integration/rich-editor-text-manipulation-test.gjs b/plugins/checklist/test/javascripts/integration/rich-editor-text-manipulation-test.gjs
new file mode 100644
index 00000000000..c8367316316
--- /dev/null
+++ b/plugins/checklist/test/javascripts/integration/rich-editor-text-manipulation-test.gjs
@@ -0,0 +1,50 @@
+import { settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import {
+ registerRichEditorExtension,
+ resetRichEditorExtensions,
+} from "discourse/lib/composer/rich-editor-extensions";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { setupRichEditor } from "discourse/tests/helpers/rich-editor-helper";
+import richEditorExtension from "discourse/plugins/checklist/lib/rich-editor-extension";
+
+module(
+ "Integration | Component | ProsemirrorEditor | Checklist text manipulation",
+ function (hooks) {
+ setupRenderingTest(hooks);
+ hooks.beforeEach(async function () {
+ await resetRichEditorExtensions();
+ registerRichEditorExtension(richEditorExtension);
+ });
+
+ for (const [name, markdown] of [
+ ["paragraph", "**one**\n\ntwo"],
+ ["line", "**one**\ntwo"],
+ ]) {
+ test(`applies a checklist prefix to each selected ${name}`, async function (assert) {
+ let textManipulation;
+ await setupRichEditor(assert, markdown, {
+ onSetup: (value) => (textManipulation = value),
+ });
+ const { view } = textManipulation;
+ textManipulation.selectText(1, view.state.doc.content.size - 2);
+ textManipulation.applyList(
+ textManipulation.getSelected(),
+ "* [ ] ",
+ "list_item",
+ { multiline: true }
+ );
+ await settled();
+ assert
+ .dom(".ProseMirror li .chcklst-box")
+ .exists({ count: 2 }, "each item has a checkbox");
+ assert
+ .dom(".ProseMirror li strong")
+ .hasText("one", "formatting is retained");
+ assert
+ .dom(".ProseMirror li:last-child p")
+ .hasText("two", "the second paragraph is retained");
+ });
+ }
+ }
+);
diff --git a/plugins/footnote/test/javascripts/integration/rich-editor-text-manipulation-test.gjs b/plugins/footnote/test/javascripts/integration/rich-editor-text-manipulation-test.gjs
new file mode 100644
index 00000000000..fd3e3b5951f
--- /dev/null
+++ b/plugins/footnote/test/javascripts/integration/rich-editor-text-manipulation-test.gjs
@@ -0,0 +1,73 @@
+import { settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import {
+ registerRichEditorExtension,
+ resetRichEditorExtensions,
+} from "discourse/lib/composer/rich-editor-extensions";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { setupRichEditor } from "discourse/tests/helpers/rich-editor-helper";
+import richEditorExtension from "discourse/plugins/footnote/lib/rich-editor-extension";
+
+module(
+ "Integration | Component | ProsemirrorEditor | Footnote text manipulation",
+ function (hooks) {
+ setupRenderingTest(hooks);
+ hooks.beforeEach(async function () {
+ await resetRichEditorExtensions();
+ registerRichEditorExtension(richEditorExtension);
+ });
+
+ test("surrounds selected text with an editable footnote", async function (assert) {
+ let textManipulation;
+ const onSetup = (value) => {
+ textManipulation = value;
+ };
+ await setupRichEditor(assert, "note", { onSetup });
+ textManipulation.selectText(1, 4);
+ textManipulation.applySurroundSelection("^[", "]", "wrap_text", {
+ multiline: false,
+ });
+ await settled();
+ assert.dom(".footnote").exists("a footnote is inserted");
+ assert.strictEqual(
+ textManipulation.view.state.selection.node?.type.name,
+ "footnote",
+ "the atomic node is selected to open its editor"
+ );
+ assert
+ .dom(".footnote-tooltip .ProseMirror")
+ .hasText("note", "the selected text can be edited in the footnote");
+ });
+
+ test("keeps text around an existing footnote selected after surrounding", async function (assert) {
+ let textManipulation;
+ const onSetup = (value) => {
+ textManipulation = value;
+ };
+ await setupRichEditor(assert, "before ^[note] after", { onSetup });
+ const { view } = textManipulation;
+ textManipulation.selectText(1, view.state.doc.content.size - 2);
+ textManipulation.applySurroundSelection(
+ "<small>",
+ "</small>",
+ "wrap_text",
+ {
+ multiline: false,
+ }
+ );
+ await settled();
+ assert.strictEqual(
+ view.state.doc
+ .textBetween(view.state.selection.from, view.state.selection.to)
+ .trimEnd(),
+ "before note after",
+ "the entire original content remains selected"
+ );
+ assert
+ .dom(".footnote-tooltip")
+ .doesNotExist(
+ "formatting the range does not open the existing footnote"
+ );
+ });
+ }
+);
diff --git a/plugins/spoiler-alert/spec/system/composer_spoiler_spec.rb b/plugins/spoiler-alert/spec/system/composer_spoiler_spec.rb
index 0c4c777348b..f247a1b64d9 100644
--- a/plugins/spoiler-alert/spec/system/composer_spoiler_spec.rb
+++ b/plugins/spoiler-alert/spec/system/composer_spoiler_spec.rb
@@ -79,6 +79,65 @@ describe "Composer - ProseMirror editor - Spoiler extension" do
expect(composer).to have_value("This is [spoiler]**secret**[/spoiler] text here")
end
+ it "wraps inline selection in inline spoiler via applySurround (plugin API path)" do
+ open_composer
+
+ composer.type_content("This is secret text here")
+
+ select_text_range(".ProseMirror p", 8, 6)
+
+ page.execute_script(<<~JS)
+ const appEvents = Discourse.__container__.lookup("service:app-events");
+ appEvents.trigger("composer:apply-surround", "[spoiler]", "[/spoiler]", "spoiler_text", { multiline: false });
+ JS
+
+ expect(rich).to have_css("span.spoiled", text: "secret")
+ expect(rich).to have_content("This is secret text here")
+
+ composer.toggle_rich_editor
+ expect(composer).to have_value("This is [spoiler]secret[/spoiler] text here")
+ end
+
+ it "inserts a selected placeholder in an inline spoiler when nothing is selected via applySurround" do
+ open_composer
+
+ composer.type_content("This is a test ")
+
+ page.execute_script(<<~JS)
+ const appEvents = Discourse.__container__.lookup("service:app-events");
+ appEvents.trigger("composer:apply-surround", "[spoiler]", "[/spoiler]", "spoiler_text", { multiline: false });
+ JS
+
+ expect(rich).to have_css("span.spoiled", text: I18n.t("js.composer.spoiler_text"))
+
+ composer.type_content("spoiler")
+
+ expect(rich).to have_css("span.spoiled", text: "spoiler")
+ expect(rich).to have_no_content(I18n.t("js.composer.spoiler_text"))
+ end
+
+ it "preserves paragraphs when applying a block spoiler through the plugin API" do
+ open_composer
+ composer.type_content("First paragraph")
+ composer.send_keys(:enter)
+ composer.type_content("Second paragraph")
+ composer.select_all
+
+ page.execute_script(<<~JS)
+ const appEvents = Discourse.__container__.lookup("service:app-events");
+ appEvents.trigger("composer:apply-surround", "[spoiler]", "[/spoiler]", "spoiler_text", { multiline: false });
+ JS
+
+ expect(rich).to have_css("div.spoiled p", text: "First paragraph")
+ expect(rich).to have_css("div.spoiled p", text: "Second paragraph")
+ expect(rich).to have_no_css("span.spoiled")
+
+ composer.toggle_rich_editor
+ expect(composer).to have_value(
+ "[spoiler]\nFirst paragraph\n\nSecond paragraph\n\n[/spoiler]\n\n",
+ )
+ end
+
it "wraps selected text in block spoiler when selection spans multiple paragraphs" do
open_composer