-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
384 lines (324 loc) · 12 KB
/
Copy pathcontent.js
File metadata and controls
384 lines (324 loc) · 12 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
(() => {
"use strict";
const BADGE_ID = "udemy-progress-percent-badge";
const POPOVER_LINE_ID = "udemy-progress-percent-line";
const UPDATE_DEBOUNCE_MS = 200;
const COUNTS_REGEX = /(\d+)\s*\/\s*(\d+)/g;
const PERCENT_REGEX = /(\d{1,3})(?:[.,](\d+))?\s*%/g;
let lastKnownCounts = null;
function normalizeText(value) {
if (!value) return "";
return value
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase();
}
function isVisibleElement(element) {
if (!(element instanceof Element)) return false;
const style = window.getComputedStyle(element);
if (style.display === "none" || style.visibility === "hidden") return false;
const rect = element.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
function extractAllCountsFromText(text) {
if (!text) return [];
const matches = [];
let match;
COUNTS_REGEX.lastIndex = 0;
// eslint-disable-next-line no-cond-assign
while ((match = COUNTS_REGEX.exec(text))) {
const done = Number.parseInt(match[1], 10);
const total = Number.parseInt(match[2], 10);
if (!Number.isFinite(done) || !Number.isFinite(total)) continue;
if (total <= 0) continue;
if (done < 0 || done > total) continue;
matches.push({ done, total });
}
return matches;
}
function extractAllPercentsFromText(text) {
if (!text) return [];
const percents = [];
let match;
PERCENT_REGEX.lastIndex = 0;
// eslint-disable-next-line no-cond-assign
while ((match = PERCENT_REGEX.exec(text))) {
const whole = match[1];
const decimal = match[2] || "";
const normalized = decimal ? `${whole}.${decimal}` : whole;
const value = Number.parseFloat(normalized);
if (!Number.isFinite(value)) continue;
if (value < 0 || value > 100) continue;
percents.push(value);
}
return percents;
}
function extractCountsByLine(text) {
if (!text) return [];
const lines = text.split(/\n+/g);
const results = [];
for (const line of lines) {
const matches = extractAllCountsFromText(line);
if (matches.length === 1) results.push(matches[0]);
}
return results;
}
function sumCounts(pairs) {
let done = 0;
let total = 0;
for (const p of pairs) {
done += p.done;
total += p.total;
}
if (total <= 0) return null;
if (done < 0 || done > total) return null;
return { done, total };
}
function findPercentNearAnchor(anchor) {
if (!anchor) return null;
const candidateTexts = [];
candidateTexts.push(anchor.innerText || anchor.textContent || "");
if (anchor.nextElementSibling) {
candidateTexts.push(anchor.nextElementSibling.innerText || anchor.nextElementSibling.textContent || "");
}
if (anchor.previousElementSibling) {
candidateTexts.push(anchor.previousElementSibling.innerText || anchor.previousElementSibling.textContent || "");
}
let current = anchor.parentElement;
for (let i = 0; i < 3 && current; i += 1) {
candidateTexts.push(current.innerText || current.textContent || "");
current = current.parentElement;
}
const allValues = [];
for (const text of candidateTexts) allValues.push(...extractAllPercentsFromText(text));
if (allValues.length === 0) return null;
const nonZero = allValues.filter((v) => v > 0);
if (nonZero.length > 0) return Math.max(...nonZero);
return allValues[0];
return null;
}
function findCurriculumContainer() {
const keywords = ["kurs icerigi", "course content"];
const candidates = Array.from(document.querySelectorAll("h1,h2,h3,h4,div,span,button,a"));
const scored = [];
for (const el of candidates) {
if (!isVisibleElement(el)) continue;
const text = normalizeText(el.textContent || "");
if (!keywords.some((k) => text.includes(k))) continue;
const rect = el.getBoundingClientRect();
const topWeight = rect.top >= 0 && rect.top <= 700 ? 2 : 0;
const score = 5 + topWeight;
scored.push({ el, score });
}
scored.sort((a, b) => b.score - a.score);
const hit = scored[0]?.el || null;
if (!hit) {
return (
document.querySelector("[data-purpose*='curriculum']") ||
document.querySelector("[data-testid*='curriculum']") ||
document.querySelector("[class*='curriculum']") ||
null
);
}
return (
hit.closest(
"aside, [role='complementary'], [data-purpose*='curriculum'], [data-testid*='curriculum'], [class*='curriculum'], [class*='sidebar']"
) ||
hit.parentElement ||
null
);
}
function findCountsFromCurriculum() {
const container = findCurriculumContainer();
if (!container) return null;
const pairs = extractCountsByLine(container.innerText || "");
if (pairs.length < 2) return null;
const maxTotal = Math.max(...pairs.map((p) => p.total));
const summed = sumCounts(pairs);
if (!summed) return null;
if (summed.total <= maxTotal) return null;
if (summed.total > 5000) return null;
return { ...summed, source: { curriculum: container } };
}
function findBadgeInsertionTarget(anchor) {
if (!anchor) return null;
const siblingCandidates = [];
if (anchor.nextElementSibling) siblingCandidates.push(anchor.nextElementSibling);
if (anchor.previousElementSibling) siblingCandidates.push(anchor.previousElementSibling);
const parent = anchor.parentElement;
if (parent) {
for (const child of Array.from(parent.children).slice(0, 10)) siblingCandidates.push(child);
}
for (const el of siblingCandidates) {
if (!(el instanceof Element)) continue;
if (!isVisibleElement(el)) continue;
const text = (el.textContent || "").trim();
if (/^\d{1,3}%$/.test(text)) return el;
}
return anchor;
}
function chooseBestCounts(matches) {
if (!matches || matches.length === 0) return null;
const sorted = matches
.slice()
.sort((a, b) => (b.total - a.total) || (b.done - a.done));
return sorted[0] || null;
}
function computePercents(done, total) {
const percent = (done / total) * 100;
const roundedPercent = Math.round(percent);
const exactPercent = Math.round(percent * 100) / 100;
return { percent, roundedPercent, exactPercent };
}
function findProgressAnchor() {
const keywords = ["ilerleme", "progress"];
const candidates = Array.from(
document.querySelectorAll(
"button, [role='button'], a, [aria-label], [data-purpose], [data-testid]"
)
);
const scored = [];
for (const el of candidates) {
if (!isVisibleElement(el)) continue;
const text = normalizeText(el.textContent || "") + " " + normalizeText(el.getAttribute("aria-label") || "");
if (!text) continue;
if (!keywords.some((k) => text.includes(k))) continue;
const rect = el.getBoundingClientRect();
const topWeight = rect.top >= 0 && rect.top <= 500 ? 2 : 0;
const lengthPenalty = Math.min(2, Math.floor((text.length || 0) / 80));
const score = 5 + topWeight - lengthPenalty;
scored.push({ el, score });
}
scored.sort((a, b) => b.score - a.score);
return scored[0]?.el || null;
}
function findVisiblePopover() {
const popoverCandidates = Array.from(
document.querySelectorAll(
"[role='dialog'], [role='tooltip'], [aria-modal='true'], [class*='popover'], [class*='tooltip'], [data-purpose*='popover'], [data-purpose*='tooltip']"
)
);
const visible = popoverCandidates.filter((el) => isVisibleElement(el));
if (visible.length === 0) return null;
const withCounts = [];
for (const el of visible) {
const counts = extractAllCountsFromText(el.innerText || "");
if (counts.length === 0) continue;
// Prefer the smallest popover that contains counts (more specific).
const rect = el.getBoundingClientRect();
const area = rect.width * rect.height;
withCounts.push({ el, area });
}
withCounts.sort((a, b) => a.area - b.area);
return withCounts[0]?.el || null;
}
function findProgressCounts() {
// 1) Prefer counts from a visible popover/tooltip.
const popover = findVisiblePopover();
if (popover) {
const best = chooseBestCounts(extractAllCountsFromText(popover.innerText || ""));
if (best) return { ...best, source: { popover } };
}
// 2) Try near the progress anchor/area.
const anchor = findProgressAnchor();
if (anchor) {
const nearTexts = [];
let current = anchor;
for (let i = 0; i < 4 && current; i += 1) {
if (current instanceof Element) {
nearTexts.push(current.innerText || current.textContent || "");
}
current = current.parentElement;
}
for (const text of nearTexts) {
const best = chooseBestCounts(extractAllCountsFromText(text));
if (best) return { ...best, source: { anchor } };
}
}
// 3) If Udemy lazy-loads overall progress, derive it from curriculum section counts.
const fromCurriculum = findCountsFromCurriculum();
if (fromCurriculum) return fromCurriculum;
return null;
}
function upsertBadge(anchor, percents, counts) {
if (!anchor) return;
let badge = document.getElementById(BADGE_ID);
if (!badge) {
badge = document.createElement("span");
badge.id = BADGE_ID;
badge.setAttribute("role", "status");
badge.setAttribute("aria-live", "polite");
}
anchor.insertAdjacentElement("afterend", badge);
badge.textContent = `${percents.roundedPercent}%`;
badge.title = counts
? `${percents.exactPercent.toFixed(2)}% (${counts.done}/${counts.total})`
: `${percents.exactPercent.toFixed(2)}% (detay icin ilerlemeyi acin)`;
}
function upsertPopoverLine(percents, counts) {
const popover = findVisiblePopover();
if (!popover) return;
let line = popover.querySelector(`#${POPOVER_LINE_ID}`);
if (!line) {
line = document.createElement("div");
line.id = POPOVER_LINE_ID;
popover.appendChild(line);
}
line.textContent = `\u0130lerleme: %${percents.exactPercent.toFixed(2)} (${counts.done}/${counts.total})`;
}
function updateUi() {
const found = findProgressCounts();
const anchor = found?.source?.anchor || findProgressAnchor();
const insertionTarget = findBadgeInsertionTarget(anchor);
if (found) {
const { done, total } = found;
const percents = computePercents(done, total);
lastKnownCounts = { done, total };
upsertBadge(insertionTarget, percents, { done, total });
upsertPopoverLine(percents, { done, total });
return;
}
if (lastKnownCounts) {
const percents = computePercents(lastKnownCounts.done, lastKnownCounts.total);
upsertBadge(insertionTarget, percents, lastKnownCounts);
return;
}
const headerPercent = findPercentNearAnchor(anchor);
if (headerPercent == null) return;
if (headerPercent === 0) return;
const percents = {
percent: headerPercent,
roundedPercent: Math.round(headerPercent),
exactPercent: Math.round(headerPercent * 100) / 100
};
upsertBadge(insertionTarget, percents, null);
}
function observeDomChanges() {
let scheduled = null;
const scheduleUpdate = () => {
if (scheduled) window.clearTimeout(scheduled);
scheduled = window.setTimeout(() => {
scheduled = null;
try {
updateUi();
} catch {
// Defensive: never throw into the page / console.
}
}, UPDATE_DEBOUNCE_MS);
};
const observer = new MutationObserver(() => scheduleUpdate());
observer.observe(document.body, { subtree: true, childList: true, characterData: true });
// Initial run + a delayed run for late-rendered SPA content.
scheduleUpdate();
window.setTimeout(scheduleUpdate, 800);
}
function main() {
if (!document.body) return;
observeDomChanges();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", main, { once: true });
} else {
main();
}
})();