From 5719e408c256724d18513261d5873c7e14caad16 Mon Sep 17 00:00:00 2001 From: Mirone Date: Mon, 27 Nov 2023 20:17:01 +0800 Subject: [PATCH] feat: undo inputrule when backspace (#1175) * feat: undo inputrule when backspace * test: add e2e --- e2e/cypress/e2e/preset-commonmark/input.cy.ts | 7 +++++++ .../core/src/internal-plugin/editor-state.ts | 17 +++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/e2e/cypress/e2e/preset-commonmark/input.cy.ts b/e2e/cypress/e2e/preset-commonmark/input.cy.ts index 983b4c36c39a..fdbff0d010c0 100644 --- a/e2e/cypress/e2e/preset-commonmark/input.cy.ts +++ b/e2e/cypress/e2e/preset-commonmark/input.cy.ts @@ -152,5 +152,12 @@ describe('input:', () => { cy.isMarkdown('The lunatic is `on the grass`\n') }) }) + + it('undo input rule when press backspace', () => { + cy.get('.editor').type('The lunatic is *on the grass*') + cy.get('.editor').get('em').should('have.text', 'on the grass') + cy.get('.editor').type('{backspace}') + cy.isMarkdown('The lunatic is \\*on the grass\\*\n') + }) }) }) diff --git a/packages/core/src/internal-plugin/editor-state.ts b/packages/core/src/internal-plugin/editor-state.ts index 221847a66f61..3b6b0ec0096a 100644 --- a/packages/core/src/internal-plugin/editor-state.ts +++ b/packages/core/src/internal-plugin/editor-state.ts @@ -3,10 +3,12 @@ import type { MilkdownPlugin, TimerType } from '@milkdown/ctx' import { createSlice, createTimer } from '@milkdown/ctx' import { docTypeError } from '@milkdown/exception' import { customInputRules as createInputRules } from '@milkdown/prose' -import { baseKeymap } from '@milkdown/prose/commands' +import { baseKeymap, chainCommands, deleteSelection, joinBackward, selectNodeBackward } from '@milkdown/prose/commands' +import { undoInputRule } from '@milkdown/prose/inputrules' import { keymap as createKeymap } from '@milkdown/prose/keymap' import type { Schema } from '@milkdown/prose/model' import { DOMParser, Node } from '@milkdown/prose/model' +import type { Command } from '@milkdown/prose/state' import { EditorState, Plugin, PluginKey } from '@milkdown/prose/state' import type { JSONRecord, Parser } from '@milkdown/transformer' @@ -55,6 +57,17 @@ export function getDoc(defaultValue: DefaultValue, parser: Parser, schema: Schem const key = new PluginKey('MILKDOWN_STATE_TRACKER') +function overrideBaseKeymap(keymap: Record) { + const handleBackspace = chainCommands( + undoInputRule, + deleteSelection, + joinBackward, + selectNodeBackward, + ) + keymap.Backspace = handleBackspace + return keymap +} + /// The editor state plugin. /// This plugin will create a prosemirror editor state. /// @@ -91,7 +104,7 @@ export const editorState: MilkdownPlugin = (ctx) => { }, }), createInputRules({ rules }), - createKeymap(baseKeymap), + createKeymap(overrideBaseKeymap(baseKeymap)), ] ctx.set(prosePluginsCtx, plugins)