From 2f7a6adca54290b65467121e55838e5cfcf9ea8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20Ku=CC=88hn?= Date: Wed, 19 May 2021 00:25:36 +0200 Subject: [PATCH] feat: allow number for setTextSelection and insertContentAt --- packages/core/src/commands/insertContentAt.ts | 9 ++++++--- packages/core/src/commands/setTextSelection.ts | 13 ++++++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/core/src/commands/insertContentAt.ts b/packages/core/src/commands/insertContentAt.ts index 10af8e38..e5174a4c 100644 --- a/packages/core/src/commands/insertContentAt.ts +++ b/packages/core/src/commands/insertContentAt.ts @@ -13,16 +13,19 @@ declare module '@tiptap/core' { /** * Insert a node or string of HTML at a specific position. */ - insertContentAt: (range: Range, value: Content) => Command, + insertContentAt: (position: number | Range, value: Content) => Command, } } } -export const insertContentAt: RawCommands['insertContentAt'] = (range, value) => ({ tr, dispatch, editor }) => { +export const insertContentAt: RawCommands['insertContentAt'] = (position, value) => ({ tr, dispatch, editor }) => { if (dispatch) { const content = createNodeFromContent(value, editor.schema) + const { from, to } = typeof position === 'number' + ? { from: position, to: position } + : position - tr.replaceWith(range.from, range.to, content) + tr.replaceWith(from, to, content) // set cursor at end of inserted content selectionToInsertionEnd(tr, tr.steps.length - 1, 1) diff --git a/packages/core/src/commands/setTextSelection.ts b/packages/core/src/commands/setTextSelection.ts index 068ad105..bf4a56d9 100644 --- a/packages/core/src/commands/setTextSelection.ts +++ b/packages/core/src/commands/setTextSelection.ts @@ -8,17 +8,20 @@ declare module '@tiptap/core' { /** * Creates a TextSelection. */ - setTextSelection: (range: Range) => Command, + setTextSelection: (position: number | Range) => Command, } } } -export const setTextSelection: RawCommands['setTextSelection'] = range => ({ tr, dispatch }) => { +export const setTextSelection: RawCommands['setTextSelection'] = position => ({ tr, dispatch }) => { if (dispatch) { const { doc } = tr - const from = minMax(range.from, 0, doc.content.size) - const to = minMax(range.to, 0, doc.content.size) - const selection = TextSelection.create(doc, from, to) + const { from, to } = typeof position === 'number' + ? { from: position, to: position } + : position + const boundedFrom = minMax(from, 0, doc.content.size) + const boundedTo = minMax(to, 0, doc.content.size) + const selection = TextSelection.create(doc, boundedFrom, boundedTo) tr.setSelection(selection) }