diff --git a/src/index.ts b/src/index.ts index 8b5e222..48241e8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ -import { Extension } from "@tiptap/core"; -import { Plugin, PluginKey } from "@tiptap/pm/state"; +import { Extension, combineTransactionSteps, getChangedRanges, findChildrenInRange } from "@tiptap/core"; +import { Plugin, PluginKey, Transaction } from "@tiptap/pm/state"; const RTL = "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC"; const LTR = @@ -40,11 +40,16 @@ function TextDirectionPlugin({ types }: { types: string[] }) { } let modified = false; - const tr = newState.tr; + const { tr } = newState; + const transform = combineTransactionSteps(oldState.doc, transactions as Transaction[]); + const changes = getChangedRanges(transform); + tr.setMeta("addToHistory", false); - newState.doc.descendants((node, pos) => { - if (types.includes(node.type.name)) { + changes.forEach(({ newRange }) => { + const nodes = findChildrenInRange(newState.doc, newRange, node => types.includes(node.type.name)) + + nodes.forEach(({ node, pos }) => { if (node.attrs.dir !== null && node.textContent.length > 0) { return; } @@ -55,7 +60,7 @@ function TextDirectionPlugin({ types }: { types: string[] }) { tr.addStoredMark(mark); } modified = true; - } + }); }); return modified ? tr : null;