A platform for community discussion. Free, open, simple.
DEV: make formatCode action more context-aware on rich editor (#35362)
Renato Atilio6e714c1ea688
diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/code-block.js b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/code-block.jsindex 9ece156970f..ea45e1828e3 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/extensions/code-block.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/extensions/code-block.js@@ -1,4 +1,6 @@+import { setBlockType, toggleMark } from "prosemirror-commands";import { highlightPlugin } from "prosemirror-highlightjs";+import { TextSelection } from "prosemirror-state";import { ensureHighlightJs } from "discourse/lib/highlight-syntax";// cached hljs instance with custom plugins/languages@@ -75,9 +77,112 @@ class CodeBlockWithLangSelectorNodeView {}}+function convertCodeBlockToParagraphs(schema) {+ return (editorState, dispatch) => {+ const codeBlock = editorState.selection.$from.parent;+ const codeText = codeBlock.textContent;++ // Split by \n\n to create multiple paragraphs+ const paragraphs = codeText+ .split("\n\n")+ .filter((text) => text.trim() !== "");++ if (dispatch) {+ const startPos = editorState.selection.$from.start() - 1;+ const endPos = editorState.selection.$from.end() + 1;++ // Create paragraph nodes+ const paragraphNodes = paragraphs.map((text) =>+ schema.nodes.paragraph.create(null, schema.text(text))+ );++ const tr = editorState.tr.replaceWith(startPos, endPos, paragraphNodes);++ // Select all the resulting paragraphs for easy back-and-forth toggling+ const newEndPos =+ startPos ++ paragraphNodes.reduce((size, node) => size + node.nodeSize, 0);+ tr.setSelection(TextSelection.create(tr.doc, startPos, newEndPos));++ dispatch(tr);+ }+ return true;+ };+}++function isBlockLevelSelection(selection) {+ // Check if we have multiple paragraphs selected or document-level selection+ const hasMultipleBlocks =+ selection.$from.parent !== selection.$to.parent ||+ selection.$from.parent.type.name === "doc";++ // Check if selection encompasses entire block including block boundaries+ const isFullBlockSelection =+ selection.$from.parent === selection.$to.parent &&+ selection.from === selection.$from.start() - 1 &&+ selection.to === selection.$to.end() + 1;++ return hasMultipleBlocks || isFullBlockSelection;+}++function convertSelectionToCodeBlock(schema) {+ return (editorState, dispatch) => {+ const { from, to } = editorState.selection;+ // Extract plain text with proper block separators+ const textContent =+ editorState.doc.textBetween(from, to, "\n\n", "\n") || "code";++ const codeBlock = schema.nodes.code_block.create(+ {},+ schema.text(textContent)+ );++ if (dispatch) {+ const tr = editorState.tr.replaceWith(from, to, codeBlock);+ // Select the entire internal content of the newly created code block+ const codeBlockStart = from + 1;+ const codeBlockEnd = codeBlockStart + codeBlock.content.size;+ tr.setSelection(+ TextSelection.create(tr.doc, codeBlockStart, codeBlockEnd)+ );+ dispatch(tr);+ }+ return true;+ };+}+/** @type {RichEditorExtension} */const extension = {nodeViews: { code_block: CodeBlockWithLangSelectorNodeView },+ commands: ({ schema }) => ({+ formatCode() {+ return (state, dispatch) => {+ const { selection } = state;++ // Case 1: Already in code block - convert back to paragraphs+ if (selection.$from.parent.type === schema.nodes.code_block) {+ return convertCodeBlockToParagraphs(schema)(state, dispatch);+ }++ // Case 2: Empty selection+ if (selection.empty) {+ const isEmptyBlock = selection.$from.parent.content.size === 0;+ const command = isEmptyBlock+ ? setBlockType(schema.nodes.code_block)+ : toggleMark(schema.marks.code);+ return command(state, dispatch);+ }++ // Case 3: Selection spans multiple blocks OR covers entire block content+ if (isBlockLevelSelection(selection)) {+ return convertSelectionToCodeBlock(schema)(state, dispatch);+ }++ // Case 4: Inline text selection - toggle code mark+ return toggleMark(schema.marks.code)(state, dispatch);+ };+ },+ }),async plugins({ getContext }) {return highlightPlugin((hljs = await ensureHighlightJs(getContext().session.highlightJsPath)),diff --git a/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js b/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.jsindex 1b140b5619e..e207cee22b6 100644--- a/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js+++ b/app/assets/javascripts/discourse/app/static/prosemirror/lib/text-manipulation.js@@ -220,23 +220,13 @@ export default class ProsemirrorTextManipulation {this.focus();}+ /**+ * Bridge method from pre-existing API to the new command system+ *+ * @returns {boolean} whether the command was applied+ */formatCode() {- let command;-- const selection = this.view.state.selection;-- if (selection.$from.parent.type === this.schema.nodes.code_block) {- command = setBlockType(this.schema.nodes.paragraph);- } else if (- selection.$from.pos !== selection.$to.pos &&- selection.$from.parent === selection.$to.parent- ) {- command = toggleMark(this.schema.marks.code);- } else {- command = setBlockType(this.schema.nodes.code_block);- }-- command?.(this.view.state, this.view.dispatch);+ return this.commands.formatCode(this.view.state, this.view.dispatch);}emojiSelected(code) {diff --git a/spec/system/composer/prosemirror_editor_spec.rb b/spec/system/composer/prosemirror_editor_spec.rbindex f10431705c3..76261eae0a8 100644--- a/spec/system/composer/prosemirror_editor_spec.rb+++ b/spec/system/composer/prosemirror_editor_spec.rb@@ -514,6 +514,253 @@ describe "Composer - ProseMirror editor", type: :system doendend+ describe "code formatting" do+ # formatCode() behavior is determined by selection type and context:+ # 1. Inside code block: convert back to paragraphs (respecting \n\n splits)+ # 2. Empty selection in empty block: create code block+ # 3. Empty selection in non-empty block: toggle stored inline code mark+ # 4. Multi-block selection: create single code block with full content selected+ # 5. Full block selection: create code block with full content selected+ # 6. Partial text selection: toggle inline code marks++ context "when inside code block" do+ it "converts code block back to single paragraph" do+ open_composer+ composer.type_content("```\nSingle line of code\n```")++ expect(rich).to have_css("pre code", text: "Single line of code")++ composer.send_keys(:up, :end)+ find(".toolbar__button.code").click++ expect(rich).to have_css("p", text: "Single line of code")+ expect(rich).to have_no_css("pre code")+ end++ it "converts code block to multiple paragraphs respecting \\n\\n splits" do+ open_composer+ composer.type_content("First paragraph\n\nSecond paragraph\n\nThird paragraph")+ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css(+ "pre code",+ text: "First paragraph\nSecond paragraph\nThird paragraph",+ )++ composer.send_keys(:left)+ find(".toolbar__button.code").click++ expect(rich).to have_css("p", text: "First paragraph")+ expect(rich).to have_css("p", text: "Second paragraph")+ expect(rich).to have_css("p", text: "Third paragraph")+ expect(rich).to have_no_css("pre code")+ end++ it "selects all resulting paragraphs for easy back-and-forth toggling" do+ open_composer+ composer.type_content("```\nFirst\n\nSecond\n```")++ composer.send_keys(:up, :end)+ find(".toolbar__button.code").click+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", text: "First\nSecond")+ end+ end++ context "with empty selection (cursor only)" do+ it "creates code block when in empty block" do+ open_composer+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code")+ expect(rich).to have_css("p", count: 1)+ end++ it "toggles stored inline code mark when in non-empty block" do+ open_composer+ composer.type_content("Before ")++ find(".toolbar__button.code").click+ expect(page).to have_css(".toolbar__button.code.--active")++ composer.type_content("code")+ expect(rich).to have_css("code", text: "code")++ find(".toolbar__button.code").click+ expect(page).to have_no_css(".toolbar__button.code.--active")++ composer.type_content(" after")+ expect(rich).to have_css("code", text: "code")+ expect(rich).to have_content("Before code after")+ end+ end++ context "with multi-block selection" do+ it "creates single code block from multiple paragraphs" do+ open_composer+ composer.type_content("First paragraph\n\nSecond paragraph")+ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", count: 1)+ expect(rich).to have_css("pre code", text: "First paragraph\nSecond paragraph")+ end++ it "creates single code block from mixed block types" do+ open_composer+ composer.type_content("# Heading\n\nParagraph text\n\n> Quote text")+ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", count: 1)+ expect(rich).to have_css("pre code", text: "Heading\nParagraph text\nQuote text")+ end++ it "selects entire content of newly created code block" do+ open_composer+ composer.type_content("First\n\nSecond")+ composer.select_all+ find(".toolbar__button.code").click+ find(".toolbar__button.code").click++ expect(rich).to have_css("p", text: "First")+ expect(rich).to have_css("p", text: "Second")+ end++ it "preserves plain text content without markdown conversion" do+ open_composer+ composer.type_content("**Bold text** and *italic text*")+ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", text: "Bold text and italic text")+ expect(rich).to have_no_css("pre code", text: "**Bold text** and *italic text*")+ end+ end++ context "with single-block text selection" do+ it "creates inline code marks for partial text selection" do+ open_composer+ composer.type_content("This is a test")++ rich.find("p").double_click+ page.execute_script(<<~JS)+ const selection = window.getSelection();+ const range = document.createRange();+ const textNode = document.querySelector('.ProseMirror p').firstChild;+ range.setStart(textNode, 5);+ range.setEnd(textNode, 9);+ selection.removeAllRanges();+ selection.addRange(range);+ JS++ find(".toolbar__button.code").click++ expect(rich).to have_css("code", text: "is a")+ expect(rich).to have_content("This is a test")+ end++ it "creates inline code marks when selecting all text content within paragraph" do+ open_composer+ composer.type_content("Hello world")++ page.execute_script(<<~JS)+ const selection = window.getSelection();+ const range = document.createRange();+ const textNode = document.querySelector('.ProseMirror p').firstChild;+ range.setStart(textNode, 0);+ range.setEnd(textNode, textNode.textContent.length);+ selection.removeAllRanges();+ selection.addRange(range);+ JS++ find(".toolbar__button.code").click++ expect(rich).to have_css("code", text: "Hello world")+ end++ it "removes inline code marks from selection that has them" do+ open_composer+ composer.type_content("This `is a` test")++ page.execute_script(<<~JS)+ const selection = window.getSelection();+ const range = document.createRange();+ const codeElement = document.querySelector('.ProseMirror code');+ range.selectNodeContents(codeElement);+ selection.removeAllRanges();+ selection.addRange(range);+ JS++ find(".toolbar__button.code").click++ expect(rich).to have_no_css("code")+ expect(rich).to have_content("This is a test")+ end+ end++ context "with full block selection" do+ it "creates code block from fully selected paragraph" do+ open_composer+ composer.type_content("Full paragraph text")+ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", text: "Full paragraph text")+ end++ it "creates code block from fully selected heading" do+ open_composer+ composer.type_content("# Full heading text")+ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", text: "Full heading text")+ end++ it "creates code block from fully selected list item" do+ open_composer+ composer.type_content("1. List item")+ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", text: "List item")+ end+ end++ context "with round-trip conversion" do+ it "converts multiple paragraphs to code block and back preserving structure" do+ open_composer+ composer.type_content("First paragraph ")+ composer.send_keys(:shift, :enter)+ composer.type_content("Second line\nSecond paragraph\nThird paragraph")++ expect(rich).to have_css("p", count: 3)+ expect(rich).to have_css("p", text: "First paragraph \nSecond line")+ expect(rich).to have_css("p", text: "Second paragraph")+ expect(rich).to have_css("p", text: "Third paragraph")++ composer.select_all+ find(".toolbar__button.code").click++ expect(rich).to have_css("pre code", count: 1)+ expect(rich).to have_css(+ "pre code",+ text: "First paragraph \nSecond line\nSecond paragraph\nThird paragraph",+ )++ composer.send_keys(:left)+ find(".toolbar__button.code").click++ expect(rich).to have_css("p", text: "First paragraph \nSecond line")+ expect(rich).to have_css("p", text: "Second paragraph")+ expect(rich).to have_css("p", text: "Third paragraph")+ end+ end+ end+context "with keymap" doPLATFORM_KEY_MODIFIER = SystemHelpers::PLATFORM_KEY_MODIFIERit "supports Ctrl + B to create a bold text" do