Ionaru / Ionaru/easy-markdown-editor
Enforce maxLength attribute
- Dominant language
- JavaScript
- Stars
- 3.1k
- Forks
- 363
- PR merge metrics
- No merged PRs in 30d
Description
**Is your feature request related to a problem? Please describe.**
Enforce the TextArea maxLength attribute.
**Describe the solution you'd like**
MaxLength enforcement can be accomplished by adding code that modifies editor.codemirror after it is created, but it would be simpler if the editor handled it internally.
The following code is working for me.
```javascript
let editor = new EasyMDE(easyMDESettings)
// Enforce textarea maxLength by attaching a function to the
// CodeMirror beforeChange event.
let maxLength = control.maxLength
if (maxLength > 0) {
editor.codemirror.on("beforeChange", function (cm, change) {
if (change.update) {
let str = change.text.join("\n")
let delta = str.length - (cm.indexFromPos(change.to) - cm.indexFromPos(change.from))
if (delta <= 0) { return true }
delta = cm.getValue().length + delta - maxLength
if (delta > 0) {
str = str.substr(0, str.length - delta)
change.update(change.from, change.to, str.split("\n"))
}
}
return true
})
}
```
Note that TextArea.maxLength is automatically reported as -1 if the attribute is not set, so this code will only apply the rule if the developer has specifically set the maxLength attribute.
**Additional context**
Easy MDE is fantastic component. Thanks for all the work.
Contributor guide
Research direction
Start at the EasyMDE initialization and its editor.codemirror integration, focusing on the CodeMirror beforeChange event described in the issue. Verify behavior with and without a textarea maxLength attribute, including insertions, replacements, and deletions; done means the editor enforces the limit only when maxLength is greater than zero.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- frontend
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100