A platform for community discussion. Free, open, simple.
FEATURE: Add ProseMirror tab indent/outdent support for code blocks (#42462)
Martin Brennan6e9c3c4d39b6
diff --git a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gtsindex a7e49f8f362..d29a07dbdb9 100644--- a/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts+++ b/frontend/discourse/app/static/prosemirror/components/prosemirror-editor.gts@@ -212,7 +212,10 @@ export default class ProsemirrorEditor extends Component<ProsemirrorEditorSignat}get keymapFromArgs(): Record<string, Command> {- const replacements: Record<string, string> = { tab: "Tab" };+ const replacements: Record<string, string> = {+ shift: "Shift",+ tab: "Tab",+ };const result: Record<string, Command> = {};for (const [key, value] of Object.entries(this.args.keymap ?? {})) {const pmKey = keydiff --git a/frontend/discourse/app/static/prosemirror/core/keymap.js b/frontend/discourse/app/static/prosemirror/core/keymap.jsindex 7cc85efc0e4..a6d12e3e80d 100644--- a/frontend/discourse/app/static/prosemirror/core/keymap.js+++ b/frontend/discourse/app/static/prosemirror/core/keymap.js@@ -23,10 +23,13 @@ export function buildKeymap(params,includeDefault = true) {- const keys = {- ...initialKeymap,- ...extractKeymap(extensions, params),- };+ const keys = { ...initialKeymap };++ for (const [key, command] of Object.entries(+ extractKeymap(extensions, params)+ )) {+ keys[key] = keys[key] ? chainCommands(command, keys[key]) : command;+ }function chainWithExisting(key, ...commands) {if (keys[key]) {diff --git a/frontend/discourse/app/static/prosemirror/extensions/code-block.js b/frontend/discourse/app/static/prosemirror/extensions/code-block.jsindex ef957a638d6..8c90a8da397 100644--- a/frontend/discourse/app/static/prosemirror/extensions/code-block.js+++ b/frontend/discourse/app/static/prosemirror/extensions/code-block.js@@ -4,9 +4,78 @@ import { schema as markdownSchema } from "prosemirror-markdown";import { TextSelection } from "prosemirror-state";import { ensureHighlightJs } from "discourse/lib/highlight-syntax";+const INDENT = " ";+// cached hljs instance with custom plugins/languageslet hljs;+function selectedCodeLines(state) {+ const { selection } = state;+ if (+ !(selection instanceof TextSelection) ||+ selection.empty ||+ selection.$from.parent !== selection.$to.parent ||+ !selection.$from.parent.type.spec.code+ ) {+ return;+ }++ const codeBlock = selection.$from.parent;+ const blockStart = selection.$from.start();+ const from = selection.from - blockStart;+ const to = selection.to - blockStart;+ const text = codeBlock.textContent;+ const firstLineStart = text.lastIndexOf("\n", from - 1) + 1;+ const effectiveTo = text[to - 1] === "\n" ? to - 1 : to;+ const lineStarts = [firstLineStart];++ let nextLineStart = text.indexOf("\n", firstLineStart) + 1;+ while (nextLineStart > 0 && nextLineStart <= effectiveTo) {+ lineStarts.push(nextLineStart);+ nextLineStart = text.indexOf("\n", nextLineStart) + 1;+ }++ return { blockStart, lineStarts, text };+}++function indentCodeBlock(outdent = false) {+ return (state, dispatch) => {+ const selectedLines = selectedCodeLines(state);+ if (!selectedLines) {+ return false;+ }++ if (!dispatch) {+ return true;+ }++ const { blockStart, lineStarts, text } = selectedLines;+ const tr = state.tr;++ for (const lineStart of lineStarts.reverse()) {+ const pos = blockStart + lineStart;+ if (outdent) {+ const line = text.slice(lineStart);+ const spaces = line.startsWith(INDENT)+ ? INDENT.length+ : Number(line.startsWith(" "));+ if (spaces) {+ tr.delete(pos, pos + spaces);+ }+ } else {+ tr.insertText(INDENT, pos);+ }+ }++ if (tr.docChanged) {+ tr.setSelection(state.selection.map(tr.doc, tr.mapping));+ dispatch(tr.scrollIntoView());+ }++ return true;+ };+}+class CodeBlockWithLangSelectorNodeView {#selectAdded = false;@@ -161,6 +230,10 @@ const extension = {},},nodeViews: { code_block: CodeBlockWithLangSelectorNodeView },+ keymap: () => ({+ Tab: indentCodeBlock(),+ "Shift-Tab": indentCodeBlock(true),+ }),commands: ({ schema }) => ({formatCode() {return (state, dispatch) => {diff --git a/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.js b/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.jsindex 0d480decd52..9293ca50c10 100644--- a/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.js+++ b/frontend/discourse/tests/integration/components/prosemirror-editor/code-block-test.js@@ -1,6 +1,11 @@+import { triggerKeyEvent } from "@ember/test-helpers";+import { TextSelection } from "prosemirror-state";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";-import { testMarkdown } from "discourse/tests/helpers/rich-editor-helper";+import {+ setupRichEditor,+ testMarkdown,+} from "discourse/tests/helpers/rich-editor-helper";module("Integration | Component | prosemirror-editor - code-block extension",@@ -71,5 +76,78 @@ module(true);});++ test("Tab indents selected code block lines with two spaces", async function (assert) {+ const markdown =+ '```csharp\n this.board.acl = [\n {\n type: "group",\n },\n ];\n```';+ const [editor] = await setupRichEditor(assert, markdown);+ const { view } = editor;+ const codeBlock = view.state.doc.firstChild;++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(view.state.doc, 7, codeBlock.content.size + 1)+ )+ );+ await triggerKeyEvent(".ProseMirror", "keydown", "Tab");++ assert.strictEqual(+ view.state.doc.firstChild.textContent,+ ' this.board.acl = [\n {\n type: "group",\n },\n ];',+ "all partially selected lines are indented"+ );+ assert.strictEqual(+ view.state.doc.textBetween(+ view.state.selection.from,+ view.state.selection.to+ ),+ 'this.board.acl = [\n {\n type: "group",\n },\n ];',+ "the code remains selected after indenting"+ );+ });++ test("Shift-Tab removes up to two spaces from selected code block lines", async function (assert) {+ const markdown = "```\n one\n two\nthree\n```";+ const [editor] = await setupRichEditor(assert, markdown);+ const { view } = editor;+ const codeBlock = view.state.doc.firstChild;++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(view.state.doc, 1, codeBlock.content.size + 1)+ )+ );+ await triggerKeyEvent(".ProseMirror", "keydown", "Tab", {+ shiftKey: true,+ });++ assert.strictEqual(+ view.state.doc.firstChild.textContent,+ "one\ntwo\nthree",+ "each selected line is outdented as far as possible"+ );+ });++ test("Tab still nests list items", async function (assert) {+ const [editor] = await setupRichEditor(assert, "* first\n* second");+ const { view } = editor;++ view.dispatch(+ view.state.tr.setSelection(TextSelection.create(view.state.doc, 12))+ );+ await triggerKeyEvent(".ProseMirror", "keydown", "Tab");++ assert+ .dom(".ProseMirror > ul > li > ul > li")+ .hasText("second", "the second item is nested under the first");++ await triggerKeyEvent(".ProseMirror", "keydown", "Tab", {+ shiftKey: true,+ });++ assert+ .dom(".ProseMirror > ul > li")+ .exists({ count: 2 }, "Shift-Tab lifts the nested item");+ });});diff --git a/frontend/discourse/tests/integration/components/prosemirror-editor/html-block-test.js b/frontend/discourse/tests/integration/components/prosemirror-editor/html-block-test.jsindex 9f0cb924a05..9322961d91b 100644--- a/frontend/discourse/tests/integration/components/prosemirror-editor/html-block-test.js+++ b/frontend/discourse/tests/integration/components/prosemirror-editor/html-block-test.js@@ -1,6 +1,11 @@+import { triggerKeyEvent } from "@ember/test-helpers";+import { TextSelection } from "prosemirror-state";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";-import { testMarkdown } from "discourse/tests/helpers/rich-editor-helper";+import {+ setupRichEditor,+ testMarkdown,+} from "discourse/tests/helpers/rich-editor-helper";module("Integration | Component | prosemirror-editor - html block extension",@@ -38,5 +43,37 @@ module(await testMarkdown(assert, markdown, html, expectedMarkdown);});});++ test("Tab and Shift-Tab indent selected HTML block lines", async function (assert) {+ const [editor] = await setupRichEditor(+ assert,+ "<div>\n <p>Hello</p>\n</div>"+ );+ const { view } = editor;+ const htmlBlock = view.state.doc.firstChild;++ view.dispatch(+ view.state.tr.setSelection(+ TextSelection.create(view.state.doc, 1, htmlBlock.content.size + 1)+ )+ );+ await triggerKeyEvent(".ProseMirror", "keydown", "Tab");++ assert.strictEqual(+ view.state.doc.firstChild.textContent,+ " <div>\n <p>Hello</p>\n </div>",+ "all selected HTML lines are indented"+ );++ await triggerKeyEvent(".ProseMirror", "keydown", "Tab", {+ shiftKey: true,+ });++ assert.strictEqual(+ view.state.doc.firstChild.textContent,+ "<div>\n <p>Hello</p>\n</div>",+ "all selected HTML lines are outdented"+ );+ });});diff --git a/spec/system/composer/prosemirror_code_spec.rb b/spec/system/composer/prosemirror_code_spec.rbindex 03aa8de97f0..3a53a11f8aa 100644--- a/spec/system/composer/prosemirror_code_spec.rb+++ b/spec/system/composer/prosemirror_code_spec.rb@@ -12,6 +12,23 @@ describe "Composer - ProseMirror - Code formatting" do# 5. Full block selection: create code block with full content selected# 6. Partial text selection: toggle inline code markscontext "when inside code block" do+ it "lets the user indent and outdent selected code with Tab" do+ code = " first line\n second line\nthird line"+ open_composer+ composer.type_content("```#{code}")++ composer.select_code_block+ composer.send_keys(:tab)+ composer.toggle_rich_editor+ expect(composer).to have_value("```\n first line\n second line\n third line\n```")++ composer.toggle_rich_editor+ composer.select_code_block+ composer.send_keys(%i[shift tab])+ composer.toggle_rich_editor+ expect(composer).to have_value("```\n#{code}\n```")+ end+it "converts code block back to single paragraph" doopen_composercomposer.type_content("```\nSingle line of code\n```")diff --git a/spec/system/composer/prosemirror_keymap_spec.rb b/spec/system/composer/prosemirror_keymap_spec.rbindex b20cc94271c..70b15f68d19 100644--- a/spec/system/composer/prosemirror_keymap_spec.rb+++ b/spec/system/composer/prosemirror_keymap_spec.rb@@ -49,6 +49,17 @@ describe "Composer - ProseMirror - Keyboard shortcuts" doexpect(rich).to have_css("ul li", text: "Item 1")end+ it "lets the user nest and lift list items with Tab" do+ open_composer+ composer.type_content("* First\nSecond")++ composer.send_keys(:tab)+ expect(composer).to have_nested_list_item("Second")++ composer.send_keys(%i[shift tab])+ expect(composer).to have_top_level_list_item("Second")+ end+it "supports Ctrl + Shift + 9 to create a blockquote" doopen_composercomposer.type_content("This is a blockquote")diff --git a/spec/system/page_objects/components/composer.rb b/spec/system/page_objects/components/composer.rbindex ead1f3a2599..c73fa6cdf02 100644--- a/spec/system/page_objects/components/composer.rb+++ b/spec/system/page_objects/components/composer.rb@@ -410,6 +410,18 @@ module PageObjectsselect_text_range(RICH_EDITOR, start_index, length)end+ def select_code_block+ select_all_content("#{RICH_EDITOR} pre code")+ end++ def has_nested_list_item?(text)+ has_css?("#{RICH_EDITOR} li > ul > li", text:, exact_text: true)+ end++ def has_top_level_list_item?(text)+ has_css?("#{RICH_EDITOR} > ul > li", text:, exact_text: true)+ end+def submitfind("#{@composer_id} .save-or-cancel .create").clickend