feat: word count in articles

This commit is contained in:
LordMZTE 2024-08-28 11:18:48 +02:00
parent a3256a256a
commit dc324ea5ec
Signed by: LordMZTE
GPG key ID: B64802DC33A64FF6
6 changed files with 47 additions and 4 deletions

View file

@ -1,3 +1,3 @@
common.hxml
-main ArticleScript
-main article.Main
-js out/article.js

View file

@ -1,3 +1,3 @@
common.hxml
-main IndexScript
-main index.Main
-js out/index.js

View file

@ -1,8 +1,14 @@
package article;
import js.Browser.document;
import js.Browser.navigator;
function main() {
addCopyButtons();
final content = document.getElementById("content");
final wordcountP = document.getElementById("wordcount");
wordcountP.innerText = 'Words: ${WordCount.inElement(content)}';
}
/**

View file

@ -0,0 +1,35 @@
package article;
import js.html.CharacterData;
import js.html.Node;
using Lambda;
using StringTools;
function inElement(el:Node):Int {
var words = 0;
var child = el.firstChild;
while (child != null) {
switch (child.nodeType) {
case Node.TEXT_NODE:
words += inString(cast(child, CharacterData).data);
case Node.ELEMENT_NODE:
if (!["pre", "code"].contains(child.nodeName.toLowerCase()))
words += inElement(child);
}
child = child.nextSibling;
}
return words;
}
function inString(s:String):Int {
final n = s
.split("\n")
.flatMap(sp -> sp.split(" "))
.filter(sp -> sp.trim().length > 0)
.length;
return n;
}

View file

@ -1,7 +1,8 @@
import index.Filter;
package index;
import js.Browser.window;
import js.Browser.document;
import lib.Article;
import index.ArticleElement;
function main() {
final filter = new Filter();

View file

@ -11,6 +11,7 @@
<body>
<div id="topright">
<p><% meta.date %></p>
<p id="wordcount">Words: ?</p>
<p><a href="https://git.mzte.de/LordMZTE/homepage/src/branch/master/src/a/<% meta.id %>/index.html.cgt" target="_blank">[src]</a></p>
</div>
<h1><% meta.title %></h1>