67 lines
2.0 KiB
JavaScript
67 lines
2.0 KiB
JavaScript
window.onload = () => {
|
|
const btnCheck = document.getElementById('btn-check')
|
|
btnCheck.addEventListener('click', checkText)
|
|
|
|
const textArea = document.getElementById('besana-editor')
|
|
let timerId = null
|
|
|
|
// textArea.addEventListener('focus', () => {
|
|
// timerId = setTimeout(checkText, 2000)
|
|
// })
|
|
|
|
// textArea.addEventListener('input', () => {
|
|
// clearTimeout(timerId)
|
|
// timerId = setTimeout(checkText, 2000)
|
|
// })
|
|
}
|
|
|
|
function checkText() {
|
|
const textArea = document.getElementById('besana-editor')
|
|
const textAreaContent = textArea?.innerHTML
|
|
const text = createFirstParagraph(textAreaContent)
|
|
const paragraphs = separateParagraphs(text)
|
|
const modifiedParagraphs = paragraphs.map(paragraph =>
|
|
mockSpellChecker(paragraph)
|
|
)
|
|
console.log(modifiedParagraphs)
|
|
textArea.innerHTML = modifiedParagraphs.join('')
|
|
}
|
|
|
|
function separateParagraphs(text) {
|
|
let paragraphs = text.match(/<div>.*?<\/div>/g)
|
|
return paragraphs
|
|
}
|
|
|
|
function mockSpellChecker(text) {
|
|
const specificWords = ['Tole', 'nov', 'test']
|
|
const words = text.split(/(?=<)|(?<=\>)|\s/g).filter(word => word !== '')
|
|
const modifiedWords = words.map(word => {
|
|
const wordWithoutTags = word.replace(/<[^>]*>/g, '')
|
|
if (specificWords.includes(wordWithoutTags)) {
|
|
return `<span class="typo-mistake">${word}</span>`
|
|
}
|
|
return word
|
|
})
|
|
|
|
// This is necessary to remove spaces between opening and closing tags
|
|
// TODO: improve this or find a better way to do it
|
|
return modifiedWords
|
|
.map((word, index) => {
|
|
if (index === 0 || index === 1 || index === modifiedWords.length - 1) {
|
|
return word
|
|
}
|
|
return ' ' + word
|
|
})
|
|
.join('')
|
|
}
|
|
|
|
function createFirstParagraph(text) {
|
|
const divRegex = /<div\b[^>]*>/i
|
|
const firstDiv = text.match(divRegex)
|
|
if (!firstDiv) return `<div>${text}</div>`
|
|
const slicedText = text?.slice(0, firstDiv.index)
|
|
const firstParagraph = `<div>${slicedText}</div>`
|
|
const newText = firstParagraph + text.slice(firstDiv.index)
|
|
return newText
|
|
}
|