-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadtime.js
More file actions
172 lines (172 loc) · 5.7 KB
/
readtime.js
File metadata and controls
172 lines (172 loc) · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/**
* Read Time Counter
* https://github.com/SPACESODA/readtimecounter
*/
(function() {
"use strict";
const DEFAULTS = {
engSpeed: 275,
charSpeed: 500,
imgSpeed: 12,
timeFormat: "decimal"
};
let segmenter;
if (typeof Intl !== "undefined" && Intl.Segmenter) {
segmenter = new Intl.Segmenter("ja", { granularity: "word" });
}
function isCJK(str) {
return /[\p{Script=Han}\p{Script=Hangul}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(
str
);
}
function analyzeText(text) {
let engCount = 0;
let ckjCount = 0;
if (segmenter) {
const segments = segmenter.segment(text);
for (const { segment, isWordLike } of segments) {
if (isWordLike) {
if (isCJK(segment)) {
ckjCount += [...segment].length;
} else {
engCount++;
}
}
}
} else {
const ckjMatches = text.match(
/[\p{Script=Han}\p{Script=Hangul}\p{Script=Hiragana}\p{Script=Katakana}]+/gu
);
if (ckjMatches) {
ckjCount = ckjMatches.join("").length;
}
const nonCkjText = text.replace(
/[\p{Script=Han}\p{Script=Hangul}\p{Script=Hiragana}\p{Script=Katakana}]+/gu,
" "
);
const cleanedText = nonCkjText.replace(/[^\w\s'-]/g, " ").replace(/\s+/g, " ").trim();
if (cleanedText.length > 0) {
engCount = cleanedText.split(" ").length;
}
}
return { engCount, ckjCount };
}
function calculateReadingTime(stats, settings = DEFAULTS) {
const engTime = stats.engCount / settings.engSpeed;
const ckjTime = stats.ckjCount / settings.charSpeed;
const imgTime = stats.imgCount * settings.imgSpeed / 60;
return engTime + ckjTime + imgTime;
}
function formatReadingTime(totalMinutes, format = "decimal") {
let displayTime;
if (format === "integer") {
displayTime = Math.round(totalMinutes).toString();
} else {
displayTime = (Math.round(totalMinutes * 10) / 10).toFixed(1);
if (displayTime.endsWith(".0")) {
displayTime = displayTime.slice(0, -2);
}
}
return parseFloat(displayTime) === 0 ? "0" : displayTime;
}
const defaultBrowserSettings = {
...DEFAULTS,
readTimeTarget: "readtime",
wordCountTarget: "wordCount",
ckjCountTarget: "ckjCount",
imgCountTarget: "imgCount",
hybridCountTarget: "hybridCount",
readTimeArea: "readtimearea"
};
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
function countImages(element) {
return element.querySelectorAll("img[alt], svg[alt]").length;
}
function getReadableText(element) {
let text = "";
const walker = document.createTreeWalker(
element,
NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
{
acceptNode: function(node) {
if (node.nodeType === Node.ELEMENT_NODE) {
if (["SCRIPT", "STYLE", "NOSCRIPT"].includes(node.tagName)) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_SKIP;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
while (walker.nextNode()) {
text += walker.currentNode.textContent + " ";
}
return text.replace(/\s+/g, " ").trim();
}
(function() {
const userSettings = window.readingTimeSettings || {};
const settings = Object.assign(
{},
defaultBrowserSettings,
userSettings
);
function updateDisplay(element) {
const text = getReadableText(element);
const { engCount, ckjCount } = analyzeText(text);
const imgCount = countImages(element);
const totalMinutes = calculateReadingTime(
{ engCount, ckjCount, imgCount },
settings
);
const displayTime = formatReadingTime(totalMinutes, settings.timeFormat);
const readTimeElement = document.getElementById(settings.readTimeTarget);
if (readTimeElement) readTimeElement.textContent = displayTime;
const wordCountElement = document.getElementById(settings.wordCountTarget);
if (wordCountElement) wordCountElement.textContent = engCount.toString();
const ckjCountElement = document.getElementById(settings.ckjCountTarget);
if (ckjCountElement) ckjCountElement.textContent = ckjCount.toString();
const imgCountElement = document.getElementById(settings.imgCountTarget);
if (imgCountElement) imgCountElement.textContent = imgCount.toString();
const hybridCountElement = document.getElementById(
settings.hybridCountTarget
);
if (hybridCountElement) {
let infoParts = [];
if (engCount > 0) infoParts.push(`${engCount} Words`);
if (ckjCount > 0) infoParts.push(`${ckjCount} CKJ Characters`);
if (imgCount > 0) infoParts.push(`${imgCount} Images`);
hybridCountElement.textContent = infoParts.length ? infoParts.join(" • ") : "0";
}
}
document.addEventListener("DOMContentLoaded", function() {
const readtimeArea = document.getElementById(settings.readTimeArea);
if (!readtimeArea) {
return;
}
const debouncedUpdate = debounce(
() => updateDisplay(readtimeArea),
250
);
if (["INPUT", "TEXTAREA"].includes(readtimeArea.tagName) || readtimeArea.isContentEditable) {
readtimeArea.addEventListener("input", debouncedUpdate);
} else {
const observer = new MutationObserver(debouncedUpdate);
observer.observe(readtimeArea, {
attributes: true,
childList: true,
subtree: true,
characterData: true
});
}
updateDisplay(readtimeArea);
});
})();
})();