js: add support for maxlength attribute (#80287)
gitea/godo.js/pipeline/head This commit looks good Details

This commit is contained in:
Corentin Sechet 2024-01-10 13:13:19 +01:00
parent 13cda5a452
commit ca2956c581
3 changed files with 60 additions and 0 deletions

View File

@ -13,6 +13,7 @@ import fontMarks from './components/font-marks.mjs'
import heading from './components/heading.mjs'
import link from './components/link.mjs'
import list from './components/list.mjs'
import maxLengthPlugin from './plugins/max-length.mjs'
function menuPlugin (menu) {
return new Plugin({
@ -100,6 +101,11 @@ export default class Godo extends window.HTMLElement {
if (options.schema !== 'basic' && !this.textarea.readOnly) this.pluginsList.push(this.blocksMenu)
if (options.instantUpdate) this.pluginsList.push(changeEventPlugin(this))
const maxLength = this.getAttribute('maxLength')
if (maxLength) {
this.pluginsList.push(maxLengthPlugin(parseInt(maxLength)))
}
const label = this.id ? document.querySelector(`label[for=${this.id}]`) : undefined
this.view = new EditorView(this.editorWrapper, {
state: this._resetState(initialContent),

View File

@ -0,0 +1,40 @@
import {Plugin} from 'prosemirror-state'
function getNodeLength (node) {
const text = node.textBetween(0, node.content.size, undefined, ' ')
return text.length
}
export default function (maxLength) {
return new Plugin({
filterTransaction: (transaction, state) => {
if (!transaction.docChanged) {
return true
}
const oldLength = getNodeLength(state.doc)
const newLength = getNodeLength(transaction.doc)
if (newLength <= maxLength) {
return true
}
if (newLength <= maxLength || newLength < oldLength) {
return true
}
if (oldLength > maxLength && newLength > maxLength) {
return false
}
const pos = transaction.selection.$head.pos
const over = newLength - maxLength
const from = pos - over
const to = pos
transaction.deleteRange(from, to)
return true
},
})
}

View File

@ -61,3 +61,17 @@ test('test godo-edior value property', async () => {
expect(editor.value).toBe('<p>Inserted content & Modified content</p>')
expect(editor.querySelector('.ProseMirror').innerHTML).toBe('<p>Inserted content & Modified content</p>')
})
test('test godo-editor maxlength property', async () => {
document.write(`
<form>
<godo-editor maxlength="10">
</godo-editor>
</form>
`)
const editor = document.querySelector('godo-editor')
editor.view.dispatch(editor.view.state.tr.insertText('This is too long'))
expect(editor.value).toBe('<p>This is to</p>')
})