|
| 1 | +const { Plugin } = window.CKEDITOR; |
| 2 | + |
| 3 | + |
| 4 | +export default class MaximumLength extends Plugin { |
| 5 | + static get pluginName() { |
| 6 | + return 'MaximumLength'; |
| 7 | + } |
| 8 | + |
| 9 | + static get requires() { |
| 10 | + return [ 'WordCount' ]; |
| 11 | + } |
| 12 | + |
| 13 | + init() { |
| 14 | + const editor = this.editor; |
| 15 | + const wordCount = editor.plugins.get( 'WordCount' ); |
| 16 | + const characterLimit = editor.config.get( 'maximumLength.characters' ); |
| 17 | + let hasMarker = false; |
| 18 | + |
| 19 | + editor.model.document.registerPostFixer( writer => { |
| 20 | + const currentCharacterCount = wordCount.characters; |
| 21 | + const excessRange = this._calculateExcessRange( characterLimit, currentCharacterCount ); |
| 22 | + |
| 23 | + if ( excessRange ) { |
| 24 | + if ( !hasMarker ) { |
| 25 | + writer.addMarker( 'maximumLengthExcess', { range: excessRange, usingOperation: false } ); |
| 26 | + hasMarker = true; |
| 27 | + } else { |
| 28 | + writer.updateMarker( 'maximumLengthExcess', { range: excessRange, usingOperation: false } ); |
| 29 | + } |
| 30 | + } else if ( hasMarker ) { |
| 31 | + writer.removeMarker( 'maximumLengthExcess' ); |
| 32 | + hasMarker = false; |
| 33 | + } |
| 34 | + } ); |
| 35 | + |
| 36 | + editor.conversion.for( 'editingDowncast' ).markerToHighlight( { |
| 37 | + model: 'maximumLengthExcess', |
| 38 | + view: { |
| 39 | + classes: 'ck-maximum-length-excess' |
| 40 | + } |
| 41 | + } ); |
| 42 | + } |
| 43 | + |
| 44 | + _calculateExcessRange( characterLimit, currentCharacterCount ) { |
| 45 | + if ( characterLimit > currentCharacterCount ) { |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + const editor = this.editor; |
| 50 | + const contentRange = editor.model.createRangeIn( editor.model.document.getRoot() ); |
| 51 | + const walker = contentRange.getWalker( { singleCharacters: true, direction: 'backward' } ); |
| 52 | + |
| 53 | + let characterNumber = currentCharacterCount; |
| 54 | + let endPosition, startPosition; |
| 55 | + |
| 56 | + for ( const value of walker ) { |
| 57 | + if ( value.type == 'text' ) { |
| 58 | + if ( !endPosition ) { |
| 59 | + endPosition = value.previousPosition; |
| 60 | + } |
| 61 | + |
| 62 | + characterNumber--; |
| 63 | + |
| 64 | + if ( characterNumber < characterLimit ) { |
| 65 | + startPosition = value.previousPosition; |
| 66 | + |
| 67 | + return editor.model.createRange( startPosition, endPosition ); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments