devexpress-richedit
Version:
DevExpress Rich Text Editor is an advanced word-processing tool designed for working with rich text documents.
106 lines (105 loc) • 3.96 kB
JavaScript
import { StringUtils } from '@devexpress/utils/lib/utils/string';
import { RichUtils } from './rich-utils';
export class SimpleSentenceWord {
constructor(position, text) {
this.position = position;
this.text = text;
}
}
export class SimpleSentence {
constructor() {
this.words = [];
}
}
export class SimpleSentenceStructureBuilder {
constructor(text) {
this.sentences = [];
this.charIndex = 0;
this.currSentence = null;
this.currWord = null;
this.text = text;
}
build() {
for (; this.charIndex < this.text.length; this.charIndex++) {
this.currChar = this.text[this.charIndex];
switch (this.currChar) {
case "?":
case ".":
case ";":
case "!":
case RichUtils.specialCharacters.SectionMark:
case RichUtils.specialCharacters.ParagraphMark: {
if (this.currSentence) {
this.finishSentence();
}
else {
if (this.prevChar == '!' && this.currChar == '?' ||
this.prevChar == '"' ||
this.prevChar == '`' ||
this.prevChar == '?' && this.currChar == '?' ||
((this.prevChar == '!' || this.prevChar == '?' || this.prevChar == '.' || this.prevChar == ';') &&
(this.currChar == RichUtils.specialCharacters.ParagraphMark || this.currChar == RichUtils.specialCharacters.SectionMark))) {
}
else {
this.addSentence();
this.finishSentence();
}
}
break;
}
default:
if (/[\p{L}\p{N}_'’-]/u.test(this.currChar))
this.addNewWordPart();
else
this.finishWord();
break;
}
this.prevChar = this.currChar;
}
this.postprocessing();
return this.sentences;
}
finishSentence() {
this.finishWord();
this.currSentence = null;
}
finishWord() {
this.currWord = null;
}
addSentence() {
this.currSentence = new SimpleSentence();
this.sentences.push(this.currSentence);
this.currWord = null;
}
addWord() {
if (!this.currSentence)
this.addSentence();
this.currWord = new SimpleSentenceWord(this.charIndex, "");
this.currSentence.words.push(this.currWord);
}
addNewWordPart() {
if (!this.currWord)
this.addWord();
this.currWord.text += this.currChar;
}
postprocessing() {
const separators = [RichUtils.specialCharacters.LeftSingleQuote, RichUtils.specialCharacters.RightSingleQuote, "'"];
for (let sentInd = 0, sentence; sentence = this.sentences[sentInd];) {
for (let wordInd = 0, word; word = sentence.words[wordInd];) {
const trimmedFromStart = StringUtils.trimStart(word.text, separators);
word.position -= word.text.length - trimmedFromStart.length;
const trimmedFromBothSides = StringUtils.trimEnd(trimmedFromStart, separators);
if (trimmedFromBothSides.length) {
word.text = trimmedFromBothSides;
wordInd++;
}
else
sentence.words.splice(wordInd, 1);
}
if (sentence.words.length)
sentInd++;
else
this.sentences.splice(sentInd, 1);
}
}
}