Rename classes to follow 'bes-xyz' naming convention and apply JavaScript formatter

This commit is contained in:
Aljaž Grilc 2024-02-02 11:03:37 +01:00
parent 218bac6ece
commit 5aaf30934a
3 changed files with 106 additions and 84 deletions

View File

@ -9,15 +9,31 @@
<script src="popup.js"></script> <script src="popup.js"></script>
</head> </head>
<body> <body>
<!--<div id="ed1" class="online-editor" contenteditable="true">Tukaj vpišite besedilo ki ga želite popraviti.</div> <!--<div id="ed1" class="bes-online-editor" contenteditable="true">Tukaj vpišite besedilo ki ga želite popraviti.</div>
<div id="ed2" class="online-editor" contenteditable="true"></div> <div id="ed2" class="bes-online-editor" contenteditable="true"></div>
<div id="ed3" class="online-editor" contenteditable="true"><div>Popravite kar želite.</div></div> <div id="ed3" class="bes-online-editor" contenteditable="true"><div>Popravite kar želite.</div></div>
<div id="ed4" class="online-editor" contenteditable="true"><div>Popravite <a href=".">kar želite</a>.</div><div>Na mizo nisem položil knjigo. Popravite kar želite.</div></div> <div id="ed4" class="bes-online-editor" contenteditable="true"><div>Popravite <a href=".">kar želite</a>.</div><div>Na mizo nisem položil knjigo. Popravite kar želite.</div></div>
<div id="ed5" class="online-editor" contenteditable="true">To je preiskus.</div>--> <div id="ed5" class="bes-online-editor" contenteditable="true">To je preiskus.</div>-->
<!-- <div id="ed6" class="online-editor" contenteditable="true"><div class="contextual"><p>Madžarski premier Orban je tako očitno vendarle pristal na nadaljnjo makrofinančno pomoč Ukrajini v okviru revizije dolgoročnega proračuna unije 2021-2027. Ta vključuje 50 milijard evrov za Ukrajino za prihodnja štiri leta, od tega 33 milijard evrov posojil in 17 milijard evrov nepovratnih sredstev.</p></div></div> --> <!-- <div id="ed6" class="bes-online-editor" contenteditable="true"><div class="contextual"><p>Madžarski premier Orban je tako očitno vendarle pristal na nadaljnjo makrofinančno pomoč Ukrajini v okviru revizije dolgoročnega proračuna unije 2021-2027. Ta vključuje 50 milijard evrov za Ukrajino za prihodnja štiri leta, od tega 33 milijard evrov posojil in 17 milijard evrov nepovratnih sredstev.</p></div></div> -->
<!-- TODO: Insert correction-panel in DOM with JavaScript and include editor ID in its ID to support multiple editors. --> <!-- TODO: Insert correction-panel in DOM with JavaScript and include editor ID in its ID to support multiple editors. -->
<div id="correction-panel"></div> <div id="correction-panel"></div>
<div id="ed7" class="online-editor" contenteditable="true"><div>Popravite kar želite.</div><div>Na mizo nisem položil knjigo. Popravite kar želite.</div></div> <div id="ed7" class="bes-online-editor" contenteditable="true"><div>Popravite kar želite.</div><div>Na mizo nisem položil knjigo. Popravite kar želite.</div></div>
<my-component></my-component> <my-component></my-component>
</body> </body>
</html> </html>
<style>
.bes-online-editor {
width: 80%;
height: 300px;
margin: 0 auto;
padding: 20px;
border-radius: 10px;
background-color: #f5f5f5;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
line-height: 1.6;
white-space: pre-wrap;
overflow-y: auto;
font-family: Arial, Helvetica, sans-serif;
z-index: 2;
}
</style>

View File

@ -4,21 +4,24 @@ let besEditors = {} // Collection of all editors on page
window.onload = () => { window.onload = () => {
// Search and prepare all our editors found in the document. // Search and prepare all our editors found in the document.
document.querySelectorAll('.online-editor').forEach(edit => { document.querySelectorAll('.bes-online-editor').forEach(edit => {
let editor = { let editor = {
timer: null timer: null
} }
besEditors[edit.id] = editor besEditors[edit.id] = editor
besProof(edit) besProof(edit)
edit.addEventListener('beforeinput', e => besHandleBeforeInput(edit.id, e), false) edit.addEventListener(
'beforeinput',
e => besHandleBeforeInput(edit.id, e),
false
)
edit.addEventListener('click', e => besHandleClick(e)) edit.addEventListener('click', e => besHandleClick(e))
// TODO: Handle editor resizes. // TODO: Handle editor resizes.
}) })
} }
// Recursively grammar-proofs one node. // Recursively grammar-proofs one node.
async function besProof(el) async function besProof(el) {
{
switch (el.nodeType) { switch (el.nodeType) {
case Node.TEXT_NODE: case Node.TEXT_NODE:
return [{ text: el.textContent, el: el, markup: false }] return [{ text: el.textContent, el: el, markup: false }]
@ -27,7 +30,7 @@ async function besProof(el)
if (besIsBlockElement(el)) { if (besIsBlockElement(el)) {
// Block elements are grammar-proofed independently. // Block elements are grammar-proofed independently.
if (besIsProofed(el)) { if (besIsProofed(el)) {
return [{ text: '<'+el.tagName+'/>', el: el, markup: true }] return [{ text: '<' + el.tagName + '/>', el: el, markup: true }]
} }
besClearAllMistakes(el) besClearAllMistakes(el)
let data = [] let data = []
@ -37,7 +40,11 @@ async function besProof(el)
if (data.some(x => !x.markup && !/^\s*$/.test(x.text))) { if (data.some(x => !x.markup && !/^\s*$/.test(x.text))) {
const requestData = { const requestData = {
format: 'plain', format: 'plain',
data: JSON.stringify({annotation: data.map(x => x.markup ? { markup: x.text } : { text: x.text })}), data: JSON.stringify({
annotation: data.map(x =>
x.markup ? { markup: x.text } : { text: x.text }
)
}),
language: 'sl', language: 'sl',
level: 'picky' level: 'picky'
} }
@ -59,8 +66,16 @@ async function besProof(el)
let range = document.createRange() let range = document.createRange()
// Locate start of the grammar mistake. // Locate start of the grammar mistake.
for (let idx = 0, startingOffset = 0; ; startingOffset += data[idx++].text.length) { for (
if (!data[idx].markup && /*startingOffset <= match.offset &&*/ match.offset < startingOffset + data[idx].text.length) { let idx = 0, startingOffset = 0;
;
startingOffset += data[idx++].text.length
) {
if (
!data[idx].markup &&
/*startingOffset <= match.offset &&*/ match.offset <
startingOffset + data[idx].text.length
) {
range.setStart(data[idx].el, match.offset - startingOffset) range.setStart(data[idx].el, match.offset - startingOffset)
break break
} }
@ -68,8 +83,16 @@ async function besProof(el)
// Locate end of the grammar mistake. // Locate end of the grammar mistake.
let endOffset = match.offset + match.length let endOffset = match.offset + match.length
for (let idx = 0, startingOffset = 0; ; startingOffset += data[idx++].text.length) { for (
if (!data[idx].markup && /*startingOffset <= endOffset &&*/ endOffset <= startingOffset + data[idx].text.length) { let idx = 0, startingOffset = 0;
;
startingOffset += data[idx++].text.length
) {
if (
!data[idx].markup &&
/*startingOffset <= endOffset &&*/ endOffset <=
startingOffset + data[idx].text.length
) {
range.setEnd(data[idx].el, endOffset - startingOffset) range.setEnd(data[idx].el, endOffset - startingOffset)
break break
} }
@ -82,61 +105,67 @@ async function besProof(el)
}) })
.catch(error => { .catch(error => {
// TODO: Make parsing issues non-fatal. But show an error sign somewhere in the UI. // TODO: Make parsing issues non-fatal. But show an error sign somewhere in the UI.
throw new Error('Parsing backend server response failed: ' + error) throw new Error(
'Parsing backend server response failed: ' + error
)
}) })
} }
return [{ text: '<'+el.tagName+'/>', el: el, markup: true }] return [{ text: '<' + el.tagName + '/>', el: el, markup: true }]
} } else {
else {
// Surround inline element with dummy <tagName>...</tagName>. // Surround inline element with dummy <tagName>...</tagName>.
let data = [{ text: '<'+el.tagName+'>', el: el, markup: true }] let data = [{ text: '<' + el.tagName + '>', el: el, markup: true }]
for (const el2 of el.childNodes) { for (const el2 of el.childNodes) {
data = data.concat(await besProof(el2)) data = data.concat(await besProof(el2))
} }
data.splice(data.length, 0, { text: '</'+el.tagName+'>', markup: true }) data.splice(data.length, 0, {
return data; text: '</' + el.tagName + '>',
markup: true
})
return data
} }
default: default:
return [{ text: '<?'+el.nodeType+'>', el: el, markup: true }] return [{ text: '<?' + el.nodeType + '>', el: el, markup: true }]
} }
} }
// Marks section of text that is about to change as not-yet-grammar-proofed. // Marks section of text that is about to change as not-yet-grammar-proofed.
function besHandleBeforeInput(editorId, event) function besHandleBeforeInput(editorId, event) {
{
let editor = besEditors[editorId] let editor = besEditors[editorId]
if (editor.timer) clearTimeout(editor.timer) if (editor.timer) clearTimeout(editor.timer)
editor.timer = setTimeout(function(){ besProof(edit) }, 1000) editor.timer = setTimeout(function () {
besProof(edit)
}, 1000)
// No need to invalidate elements after range.startContainer since they will // No need to invalidate elements after range.startContainer since they will
// get either deleted or replaced. // get either deleted or replaced.
let edit = document.getElementById(editorId) let edit = document.getElementById(editorId)
event.getTargetRanges().forEach(range => besClearProofed(besGetBlockParent(range.startContainer, edit))) event
.getTargetRanges()
.forEach(range =>
besClearProofed(besGetBlockParent(range.startContainer, edit))
)
} }
// Test if given block element has already been grammar-proofed. // Test if given block element has already been grammar-proofed.
function besIsProofed(el) function besIsProofed(el) {
{
return el.getAttribute('besProofed') === 'true' return el.getAttribute('besProofed') === 'true'
} }
// Mark given block element as grammar-proofed. // Mark given block element as grammar-proofed.
function besMarkProofed(el) function besMarkProofed(el) {
{
el.setAttribute('besProofed', 'true') el.setAttribute('besProofed', 'true')
} }
// Mark given block element as not grammar-proofed. // Mark given block element as not grammar-proofed.
function besClearProofed(el) function besClearProofed(el) {
{
el?.removeAttribute('besProofed') el?.removeAttribute('besProofed')
} }
// Remove all grammar mistakes markup for given block element. // Remove all grammar mistakes markup for given block element.
function besClearAllMistakes(el) { function besClearAllMistakes(el) {
for (const el2 of el.childNodes) { for (const el2 of el.childNodes) {
if (el2.tagName === 'SPAN' && el2.classList.contains('typo-mistake')) { if (el2.tagName === 'SPAN' && el2.classList.contains('bes-typo-mistake')) {
el2.replaceWith(...el2.childNodes) el2.replaceWith(...el2.childNodes)
el2.remove() el2.remove()
} }
@ -145,47 +174,49 @@ function besClearAllMistakes(el) {
// Adds grammar mistake markup // Adds grammar mistake markup
function besAddMistake(range, match) { function besAddMistake(range, match) {
const correctionPanel = document.getElementById('correction-panel'); const correctionPanel = document.getElementById('correction-panel')
const clientRects = range.getClientRects() const clientRects = range.getClientRects()
for (let i = 0, n = clientRects.length; i < n; ++i) { for (let i = 0, n = clientRects.length; i < n; ++i) {
const rect = clientRects[i] const rect = clientRects[i]
const highlight = document.createElement("div"); const highlight = document.createElement('div')
highlight.classList.add("typo-mistake"); highlight.classList.add('bes-typo-mistake')
highlight.dataset.info = match.message; highlight.dataset.info = match.message
highlight.style.left = `${rect.left}px`; highlight.style.left = `${rect.left}px`
highlight.style.top = `${rect.top}px`; highlight.style.top = `${rect.top}px`
highlight.style.width = `${rect.width}px`; highlight.style.width = `${rect.width}px`
highlight.style.height = `${rect.height}px`; highlight.style.height = `${rect.height}px`
correctionPanel.appendChild(highlight); correctionPanel.appendChild(highlight)
// TODO: Find a solution to handle click events on the highlights // TODO: Find a solution to handle click events on the highlights
// const editor = document.querySelector('.online-editor') // const editor = document.querySelector('.bes-online-editor')
// highlight.addEventListener("click", function(e) { // highlight.addEventListener("click", function(e) {
// console.log(e); // console.log(e);
// editor.focus(); // editor.focus();
// besHandleClick(e); // besHandleClick(e);
// return true; // return true;
// }); // });
} }
} }
// Tests if given element is block element. // Tests if given element is block element.
function besIsBlockElement(el) function besIsBlockElement(el) {
{
const defaultView = document.defaultView const defaultView = document.defaultView
switch (defaultView.getComputedStyle(el, null).getPropertyValue('display').toLowerCase()) switch (
{ defaultView
.getComputedStyle(el, null)
.getPropertyValue('display')
.toLowerCase()
) {
case 'inline': case 'inline':
case 'inline-block': case 'inline-block':
return false; return false
default: default:
return true return true
} }
} }
// Returns first block parent element // Returns first block parent element
function besGetBlockParent(el, edit) function besGetBlockParent(el, edit) {
{
for (; el && el !== edit; el = el.parentNode) { for (; el && el !== edit; el = el.parentNode) {
if (el.nodeType === Node.ELEMENT_NODE && besIsBlockElement(el)) return el if (el.nodeType === Node.ELEMENT_NODE && besIsBlockElement(el)) return el
} }

View File

@ -1,25 +1,5 @@
/* Besana online editor */
/* TODO: Rename classes to "bes-..." */
/* TODO: In the release version, .online-editor should not contain any formatting. Let users format editor at will. */
.online-editor {
width: 80%;
height: 300px;
margin: 0 auto;
padding: 20px;
border-radius: 10px;
background-color: #f5f5f5;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
line-height: 1.6;
white-space: pre-wrap;
overflow-y: auto;
font-family: Arial, Helvetica, sans-serif;
z-index: 2;
}
/* Mistake types styles */ /* Mistake types styles */
.typo-mistake { .bes-typo-mistake {
border-bottom: 2px solid red; border-bottom: 2px solid red;
position: absolute; position: absolute;
z-index: 2; z-index: 2;
@ -29,8 +9,3 @@
text-decoration-color: red; text-decoration-color: red;
cursor: text; */ cursor: text; */
} }
.other-mistake {
text-decoration: underline;
text-decoration-color: blue;
}