-
-
Notifications
You must be signed in to change notification settings - Fork 169
/
Copy pathindex.ts
47 lines (44 loc) · 1.93 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { trimTextContentFromAnchor } from '@lexical/selection'
import { $restoreEditorState } from '@lexical/utils'
import { $getSelection, $isRangeSelection, EditorState, RootNode } from 'lexical'
import { realmPlugin } from '../../RealmWithPlugins'
import { createRootEditorSubscription$ } from '../core'
/**
* A plugin that limits the maximum length of the text content of the editor.
* Adapted from the Lexical plugin. https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/plugins/MaxLengthPlugin/index.tsx
* @example
* ```tsx
* <MDXEditor plugins={[maxLengthPlugin(100)]} markdown={'hello world'} />
* ```
* @group Utilities
*/
export const maxLengthPlugin = realmPlugin<number>({
init: (realm, maxLength = Infinity) => {
realm.pub(createRootEditorSubscription$, (editor) => {
let lastRestoredEditorState: EditorState | null = null
return editor.registerNodeTransform(RootNode, (rootNode: RootNode) => {
const selection = $getSelection()
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
return
}
const prevEditorState = editor.getEditorState()
const prevTextContentSize = prevEditorState.read(() => rootNode.getTextContentSize())
const textContentSize = rootNode.getTextContentSize()
if (prevTextContentSize !== textContentSize) {
const delCount = textContentSize - maxLength
const anchor = selection.anchor
if (delCount > 0) {
// Restore the old editor state instead if the last
// text content was already at the limit.
if (prevTextContentSize === maxLength && lastRestoredEditorState !== prevEditorState) {
lastRestoredEditorState = prevEditorState
$restoreEditorState(editor, prevEditorState)
} else {
trimTextContentFromAnchor(editor, anchor, delCount)
}
}
}
})
})
}
})