diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 58a8d11..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,13 +0,0 @@ -version: 2 -updates: - - package-ecosystem: github-actions - directory: / - schedule: - interval: monthly - - package-ecosystem: npm - directory: / - schedule: - interval: monthly - groups: - dev-dependencies: - patterns: ["*"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fabe746..c0a1a96 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,15 @@ jobs: - name: Smoke test run: npm run test:smoke + - name: Feature tests + run: npm run test:e2e -- --screenshots screenshots + + - uses: actions/upload-artifact@v5 + if: always() + with: + name: feature-screenshots + path: screenshots/ + - uses: actions/upload-artifact@v5 with: name: packages diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 50e257a..529c413 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -55,7 +55,7 @@ jobs: run: git diff --exit-code -- userscript.js return-youtube-subscribers.user.js store/listings - name: Smoke test - run: npx playwright install --with-deps chromium firefox webkit && npm run test:smoke + run: npx playwright install --with-deps chromium firefox webkit && npm run test:smoke && npm run test:e2e - name: Release notes run: node scripts/release-notes.mjs > dist/release-notes.md diff --git a/.gitignore b/.gitignore index 84ef352..73e275d 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ build/ .DS_Store *.xpi .web-extension-id +screenshots/ diff --git a/CHANGELOG.md b/CHANGELOG.md index cae18d6..37ff4c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ tagged version into the GitHub release and the Firefox Add-ons version notes. ## 4.4.0 +- Sort channel search results by exact subscriber count. +- Exact counts on featured channels and other channel lists. +- Live streams refresh the count every 10 seconds, and digits roll when a count changes. +- New full-screen live counter with race mode (two channels and the gap between them) and a "Save image" button for sharing. +- On your own channel: next milestone, subscribers to go, recent daily growth and a projected milestone date. +- New toolbar popup: channels you've viewed ranked by growth, a race picker, and a choice of exact or compact (452.3M) numbers. +- Hover any count to see that it's an estimate, where it came from and when it was updated. +- Everything the extension adds follows YouTube's light, dark and ambient themes. - New logo and icons, redrawn for every size from 16px up. - Firefox now uses Manifest V3, the same manifest as every other browser. Requires Firefox 140 or newer. - One build now produces the Chrome, Edge, Opera, Firefox and Safari packages and the userscript, so every browser gets the same version at the same time. diff --git a/README.md b/README.md index d0b896d..b8b21bb 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ npm run lint ``` ```bash -npm run test:smoke +npm run test:smoke && npm run test:e2e ``` Releasing, store credentials and the Safari setup are in [docs/RELEASING.md](docs/RELEASING.md). diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 23ef73a..d2f13ab 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -190,7 +190,6 @@ hand: store's credentials at once. - **Each store fails alone.** Stores publish in separate jobs, so a Chrome review problem doesn't block Firefox, and each can be gated behind its own approval. -- **Dependabot** keeps the actions and npm tools updated monthly. What still has to be done by hand: listing text and images on the Chrome, Edge and Opera dashboards (their APIs only accept packages), Opera uploads, and pressing **Submit for Review** diff --git a/index.html b/index.html index 026cd3a..8175739 100644 --- a/index.html +++ b/index.html @@ -22,7 +22,6 @@ - +
+${body.html}`; + +function searchPage() { + const row = (c) => ` + + ${avatar(c, 136)} +
${c.name}
+
${c.handle} • ${c.rounded} subscribers
+
Official ${c.name} channel.
+ Subscribe
`; + return shell({ query: "mrbeast", html: `
${[CH.philanthropy, CH.mrbeast, CH.gaming].map(row).join("")}
` }); +} + +function channelPage(c, { dark = false } = {}) { + const featured = [CH.mrbeast, CH.gaming, CH.philanthropy].map((f) => ` + ${avatar(f, 104)} + ${f.name}${f.rounded} subscribers`).join(""); + return shell({ html: ` +
+ +
HomeVideosShortsPlaylists
+

Featured channels

+
${featured}
`, + }, { dark, data: `var ytInitialData={"externalId":"${c.id}"};` }); +} + +function watchPage(c, { live = false, dark = true } = {}) { + const chat = live ? `
+ Live chat${["LET'S GOOO", "GG", "who's here from shorts", "W stream", "first time catching it live!"].map((m, i) => `
viewer${i + 7}  ${m}
`).join("")}
` : ""; + return shell({ html: `
+
+ ${live ? 'LIVE' : ""}
+

${live ? "$1,000,000 Live Giveaway Countdown" : "I Spent 100 Days In The Wilderness"}

+
${avatar(c, 40)} +
+
${c.rounded} subscribers
+ Subscribe
+
${chat}
`, + }, { dark, data: `var ytInitialPlayerResponse={"videoDetails":{"channelId":"${c.id}"}};` }); +} + +// ---------- browser ---------- + +const ext = join(root, "dist/chrome"); +// Chrome derives an unpacked extension's ID from its path. +const extId = [...createHash("sha256").update(ext).digest("hex").slice(0, 32)].map((h) => String.fromCharCode(97 + parseInt(h, 16))).join(""); +const profile = mkdtempSync(join(tmpdir(), "ryts-e2e-")); +const context = await chromium.launchPersistentContext(profile, { + channel: "chromium", + viewport: { width: 1280, height: 800 }, + deviceScaleFactor: shotsDir ? 2 : 1, + acceptDownloads: true, + args: [`--disable-extensions-except=${ext}`, `--load-extension=${ext}`], +}); + +await context.route("https://backend.mixerno.space/**", (route) => { + const id = decodeURIComponent(route.request().url().split("/").pop()); + const c = byId[id]; + let count = c?.count; + if (c === CH.mrbeast && liveMode) count += liveTicks++ * 1873; + route.fulfill({ + status: c ? 200 : 404, contentType: "application/json", headers: { "access-control-allow-origin": "*" }, + body: JSON.stringify(c ? { items: [{ statistics: { subscriberCount: count } }] } : {}), + }); +}); +await context.route("https://yt3.ggpht.com/**", (route) => route.fulfill({ contentType: "image/png", body: readFileSync(join(root, "store/templates/avatars/sfmg.png")) })); +let pageFor = () => ""; +await context.route("https://www.youtube.com/**", (route) => { + const url = new URL(route.request().url()); + const c = byHandle[decodeURIComponent(url.pathname.slice(1)).toLowerCase()]; + // Handle lookups (fetch of /@handle) return that channel's page; navigations use the current fixture. + const body = route.request().resourceType() === "document" ? pageFor(url) : c ? channelPage(c) : pageFor(url); + route.fulfill({ contentType: "text/html", body }); +}); + +let failures = 0; +const check = async (name, fn) => { + try { await fn(); console.log(`ok ${name}`); } catch (e) { failures++; console.error(`FAIL ${name}: ${e.message.split("\n")[0]}`); } +}; +const shot = async (page, file, opts = {}) => { if (shotsDir) await page.screenshot({ path: join(shotsDir, file), ...opts }); }; +const text = (page, sel) => page.locator(sel).first().evaluate((el) => el.querySelector(".ryts-sr")?.textContent ?? el.textContent); +const until = (page, fn, arg, timeout = 15000) => page.waitForFunction(fn, arg, { timeout }); + +// Seed some history so growth, projections and the popup have data. +const ext0 = await context.newPage(); +await ext0.goto(`chrome-extension://${extId}/popup.html`); +const hourAgo = Date.now() - 6 * 3600_000; +await ext0.evaluate(([CH, hourAgo]) => chrome.storage.local.set({ + history: Object.fromEntries(Object.values(CH).map((c, i) => [c.id, { + name: c.name, handle: c.handle, seen: hourAgo, + points: [[hourAgo, c.count - [9400, 1210, 3020, 3][i]], [hourAgo + 3600_000, c.count - [7400, 1000, 2400, 2][i]]], + }])), +}), [CH, hourAgo]); +await ext0.close(); + +// 1. Search: exact counts + sort by subscribers +await check("search: exact counts and sort by subscribers", async () => { + pageFor = () => searchPage(); + const page = await context.newPage(); + await page.goto("https://www.youtube.com/results?search_query=mrbeast"); + await until(page, () => document.querySelectorAll("[data-ryts-value]").length >= 3); + await page.getByRole("button", { name: "Sort channels by subscribers" }).click(); + await until(page, () => document.querySelector(".ryts-chip")?.getAttribute("aria-pressed") === "true"); + const order = await page.$$eval("ytd-channel-renderer #text", (els) => els.map((e) => e.textContent)); + if (order.join() !== "MrBeast,MrBeast Gaming,Beast Philanthropy") throw new Error("order was " + order.join()); + if ((await text(page, "ytd-channel-renderer #video-count")) !== "452,318,906 subscribers") throw new Error("count not exact"); + await page.locator("ytd-channel-renderer #video-count").first().hover(); + await page.waitForSelector(".ryts-tip:not([hidden])"); + await shot(page, "1-search-sorted.png"); + await page.close(); +}); + +// 2. Own channel: header roll, milestone panel, featured channels, counter link +for (const dark of [false, true]) { + await check(`own channel page (${dark ? "dark" : "light"} theme): panel, featured channels, counter link`, async () => { + pageFor = () => channelPage(CH.sfmg, { dark }); + const page = await context.newPage(); + await page.goto("https://www.youtube.com/@sfmg"); + await until(page, () => document.querySelector(".ryts-panel")); + const header = await text(page, "yt-content-metadata-view-model > div:nth-child(3) > span"); + if (header !== "34,010 subscribers") throw new Error("header was " + header); + await until(page, () => [...document.querySelectorAll("ytd-grid-channel-renderer #subscribers")].every((e) => e.dataset.rytsValue)); + const featured = await page.$$eval("ytd-grid-channel-renderer #subscribers", (els) => els.map((e) => e.textContent)); + if (featured[0] !== "452,318,906 subscribers") throw new Error("featured was " + featured[0]); + const panel = await page.locator(".ryts-panel").innerText(); + if (!/Next milestone: 35,000/.test(panel) || !/990\s*to go/.test(panel) || !/per day/.test(panel)) throw new Error("panel: " + panel.replace(/\n/g, " | ")); + if (!(await page.locator(".ryts-open").count())) throw new Error("no counter link"); + if (await page.evaluate(() => getComputedStyle(document.querySelector(".ryts-panel b")).color) !== (dark ? "rgb(241, 241, 241)" : "rgb(15, 15, 15)")) throw new Error("panel ignores theme"); + await shot(page, `2-own-channel-${dark ? "dark" : "light"}.png`); + await page.close(); + }); +} + +// 3. Live stream: count refreshes and rolls +await check("live stream: count refreshes with a digit roll", async () => { + liveTicks = 0; + liveMode = true; + pageFor = () => watchPage(CH.mrbeast, { live: true }); + const page = await context.newPage(); + await page.goto("https://www.youtube.com/watch?v=live"); + await until(page, () => document.querySelector("#owner-sub-count.ryts-live")); + const first = await text(page, "#owner-sub-count"); + await until(page, (f) => document.querySelector("#owner-sub-count .ryts-sr")?.textContent !== f, first, 20000); + await page.waitForTimeout(300); + await shot(page, "3a-live-mid-roll.png", { clip: { x: 0, y: 540, width: 640, height: 120 } }); + await page.waitForTimeout(1200); + await page.locator("#owner-sub-count").hover(); + await shot(page, "3-live.png"); + const second = await text(page, "#owner-sub-count"); + if (first === second) throw new Error("count did not change"); + const tip = await page.locator(".ryts-tip").textContent(); + if (!/Estimated by Mixerno\.space/.test(tip) || !/YouTube shows 452M/.test(tip) || !/Live/.test(tip)) throw new Error("tooltip: " + tip); + liveMode = false; + await page.close(); +}); + +// 4. Compact format, switched from the popup's setting +await check("compact number format", async () => { + pageFor = () => watchPage(CH.mrbeast, { dark: false }); + const page = await context.newPage(); + await page.goto("https://www.youtube.com/watch?v=compact"); + await until(page, () => document.querySelector("#owner-sub-count[data-ryts-value]")); + const popup = await context.newPage(); + await popup.goto(`chrome-extension://${extId}/popup.html`); + await popup.getByLabel("Compact").check(); + await until(page, () => document.querySelector("#owner-sub-count")?.dataset.rytsValue?.startsWith("452.3M")); + await page.bringToFront(); + const y = await page.evaluate(() => document.querySelector("#owner").getBoundingClientRect().top + scrollY); + await shot(page, "4-compact-format.png", { fullPage: true, clip: { x: 0, y: y - 60, width: 760, height: 150 } }); + await popup.getByLabel("Exact").check(); + await popup.close(); + await page.close(); +}); + +// 5. Popup: fastest growing +await check("popup: fastest growing ranking", async () => { + const popup = await context.newPage(); + await popup.setViewportSize({ width: 392, height: 640 }); + await popup.goto(`chrome-extension://${extId}/popup.html`); + const names = await popup.$$eval(".list .name", (els) => els.map((e) => e.textContent)); + if (names[0] !== "MrBeast") throw new Error("ranking was " + names.join()); + await shot(popup, "5-popup.png", { fullPage: true }); + await popup.close(); +}); + +// 6. Counter page and race, plus the share image +await check("live counter, race mode and share image", async () => { + const page = await context.newPage(); + await page.goto(`chrome-extension://${extId}/counter.html?c=${CH.mrbeast.id}&n=MrBeast`); + await page.waitForFunction(() => document.querySelector(".big .ryts-sr")); + await shot(page, "6-big-counter.png"); + await page.goto(`chrome-extension://${extId}/counter.html?c=${CH.mrbeast.id}&n=MrBeast&vs=${CH.gaming.id}&vn=MrBeast%20Gaming`); + await page.waitForFunction(() => /leads by/.test(document.querySelector(".gap")?.textContent || "")); + const gap = await page.locator(".gap").textContent(); + if (!/MrBeast leads by [\d,]+ subscribers/.test(gap)) throw new Error("gap: " + gap); + await shot(page, "7-race.png"); + const [download] = await Promise.all([page.waitForEvent("download"), page.getByRole("button", { name: "Save image" }).click()]); + if (!download.suggestedFilename().endsWith(".png")) throw new Error("download was " + download.suggestedFilename()); + if (shotsDir) await download.saveAs(join(shotsDir, "8-share-image.png")); + await page.close(); +}); + +await context.close(); +rmSync(profile, { recursive: true, force: true }); +console.log(failures ? `${failures} failed` : "all passed"); +process.exit(failures ? 1 : 0); diff --git a/scripts/smoke-test.mjs b/scripts/smoke-test.mjs index 384746a..231bae5 100755 --- a/scripts/smoke-test.mjs +++ b/scripts/smoke-test.mjs @@ -39,14 +39,17 @@ async function expectExact(page, label) { await page.goto("https://www.youtube.com/watch?v=smoke"); try { await page.waitForFunction( - (want) => document.querySelector("#owner-sub-count")?.textContent === want, + (want) => { + const el = document.querySelector("#owner-sub-count"); + return (el?.querySelector(".ryts-sr") ?? el)?.textContent === want; // rolling digits keep a plain copy + }, EXPECTED, { timeout: 15000 } ); console.log(`ok ${label}`); return true; } catch { - const got = await page.locator("#owner-sub-count").textContent().catch(() => "?"); + const got = await page.locator("#owner-sub-count").evaluate((el) => (el.querySelector(".ryts-sr") ?? el).textContent).catch(() => "?"); console.error(`FAIL ${label}: expected "${EXPECTED}", got "${got}"`); return false; } diff --git a/src/counter.html b/src/counter.html new file mode 100644 index 0000000..deaf5b8 --- /dev/null +++ b/src/counter.html @@ -0,0 +1,24 @@ + + + + + + Live subscriber count + + + + +
Return YouTube Subscribers
+
+
+

Loading…

+ + + +
+ + + + diff --git a/src/counter.js b/src/counter.js new file mode 100644 index 0000000..96c236c --- /dev/null +++ b/src/counter.js @@ -0,0 +1,122 @@ +// Full-screen live counter for one channel, or a race between two. +// counter.html?c=&n=[&vs=&vn=] + +(async () => { + const R = RYTS; + const REFRESH_MS = 5000; + const params = new URLSearchParams(location.search); + const history = await R.getHistory(); + const nameOf = (id, given) => given || history[id]?.name || history[id]?.handle || id; + + const sides = [{ id: params.get("c"), name: nameOf(params.get("c"), params.get("n")) }]; + if (params.get("vs")) sides.push({ id: params.get("vs"), name: nameOf(params.get("vs"), params.get("vn")) }); + + const board = document.getElementById("board"); + const status = document.getElementById("status"); + if (!sides[0].id) { + status.textContent = "No channel chosen. Open this page from a channel page or the toolbar popup."; + return; + } + + // Layout + board.classList.toggle("race", sides.length > 1); + for (const side of sides) { + const section = document.createElement("section"); + section.className = "side"; + const h1 = document.createElement("h1"); + h1.textContent = side.name; + side.number = Object.assign(document.createElement("div"), { className: "big", textContent: "–" }); + const sub = Object.assign(document.createElement("p"), { textContent: "subscribers" }); + section.append(h1, side.number, sub); + side.section = section; + board.append(section); + } + const gap = Object.assign(document.createElement("p"), { className: "gap" }); + if (sides.length > 1) board.append(gap); + document.title = sides.map((s) => s.name).join(" vs ") + " live subscriber count"; + + // "Race against" menu + const vs = document.getElementById("vs"); + Object.entries(history) + .filter(([id]) => id !== sides[0].id) + .sort((a, b) => (b[1].points.at(-1)?.[1] || 0) - (a[1].points.at(-1)?.[1] || 0)) + .forEach(([id, h]) => vs.add(new Option(h.name || h.handle || id, id))); + vs.value = sides[1]?.id || ""; + vs.addEventListener("change", () => { + const next = new URLSearchParams({ c: sides[0].id, n: sides[0].name }); + if (vs.value) next.set("vs", vs.value), next.set("vn", nameOf(vs.value)); + location.search = next; + }); + + // Refresh loop + async function refresh() { + const counts = await Promise.all(sides.map((s) => R.fetchCount(s.id, { fresh: true }))); + if (counts.some((c) => c === null)) { + status.textContent = `Couldn't reach ${R.SOURCE}. Trying again in ${REFRESH_MS / 1000} seconds.`; + return; + } + sides.forEach((side, i) => { + const text = R.exact(counts[i]); + const animate = side.count !== undefined && side.count !== counts[i]; + if (R.canRoll()) R.roll(side.number, text, side.text, animate); + else side.number.textContent = text; + side.count = counts[i]; + side.text = text; + R.observe(side.id, counts[i], { name: side.name }); + }); + if (sides.length > 1) { + const [a, b] = sides; + const lead = a.count >= b.count ? a : b; + const other = lead === a ? b : a; + sides.forEach((s) => s.section.classList.toggle("leader", s === lead)); + gap.replaceChildren(`${lead.name} leads by `, Object.assign(document.createElement("strong"), { textContent: R.exact(lead.count - other.count) }), " subscribers"); + } + status.textContent = `Estimated by ${R.SOURCE}. Updated ${R.time(Date.now())}, refreshes every ${REFRESH_MS / 1000} seconds.`; + } + await refresh(); + setInterval(refresh, REFRESH_MS); + + // Full screen + const fs = document.getElementById("fullscreen"); + fs.addEventListener("click", () => (document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen())); + document.addEventListener("fullscreenchange", () => { fs.textContent = document.fullscreenElement ? "Exit full screen" : "Full screen"; }); + + // Shareable image + document.getElementById("save").addEventListener("click", async () => { + const W = 1200, H = 630, canvas = Object.assign(document.createElement("canvas"), { width: W, height: H }); + const ctx = canvas.getContext("2d"); + const font = (weight, size) => `${weight} ${size}px Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`; + ctx.fillStyle = "#F5F6FA"; ctx.fillRect(0, 0, W, H); + ctx.fillStyle = "#E0262F"; ctx.fillRect(0, H - 14, W, 14); + const logo = new Image(); + logo.src = "icons/icon-128.png"; + await logo.decode().catch(() => {}); + ctx.drawImage(logo, 64, 52, 64, 64); + ctx.fillStyle = "#1A1C2E"; ctx.font = font(800, 28); ctx.fillText("Return YouTube Subscribers", 140, 94); + const fit = (text, weight, size, max) => { + while (size > 12) { ctx.font = font(weight, size); if (ctx.measureText(text).width <= max) break; size -= 2; } + return size; + }; + if (sides.length === 1) { + const s = sides[0]; + ctx.fillStyle = "#1A1C2E"; fit(s.name, 700, 52, W - 128); ctx.fillText(s.name, 64, 250); + fit(s.text, 800, 170, W - 128); ctx.fillText(s.text, 60, 420); + ctx.fillStyle = "#5D6178"; ctx.font = font(500, 30); ctx.fillText("subscribers", 64, 475); + } else { + sides.forEach((s, i) => { + const x = 64 + i * 560; + ctx.fillStyle = "#1A1C2E"; fit(s.name, 700, 40, 500); ctx.fillText(s.name, x, 240); + fit(s.text, 800, 84, 480); ctx.fillText(s.text, x - 2, 350); + }); + const lead = sides[0].count >= sides[1].count ? sides[0] : sides[1]; + const diff = R.exact(Math.abs(sides[0].count - sides[1].count)); + ctx.fillStyle = "#5D6178"; ctx.font = font(500, 30); ctx.fillText(`${lead.name} leads by ${diff}`, 64, 460); + } + ctx.fillStyle = "#5D6178"; ctx.font = font(500, 22); + ctx.fillText(`Estimated live count, ${new Date().toLocaleString([], { dateStyle: "medium", timeStyle: "short" })}. ryts.mgcounts.com`, 64, H - 52); + const link = document.createElement("a"); + link.download = `${sides.map((s) => s.name).join("-vs-").replace(/[^\w-]+/g, "_")}-subscribers.png`; + link.href = canvas.toDataURL("image/png"); + link.click(); + }); +})(); diff --git a/src/main.js b/src/main.js index b8e8cd2..08ba67d 100644 --- a/src/main.js +++ b/src/main.js @@ -1,223 +1,405 @@ -let currentURL = window.location.href; -const apiLink = "https://backend.mixerno.space/api/youtube/estv3/"; -const apiPath = "items[0].statistics.subscriberCount"; -const strType = "en-US"; -let lastFetchedSubscriberCount = null; - -const possibleSubCounters = [ - "#owner-sub-count", - "#page-header > yt-page-header-renderer > yt-page-header-view-model > div > div.ytPageHeaderViewModelHeadline > div > yt-content-metadata-view-model > div:nth-child(3) > span:nth-child(1)" -]; - -function getValueFromJson(json, path) { - const keys = path.replace(/\[(\d+)\]/g, '.$1').split('.'); // Converts [0] to .0 and splits on . - let result = json; - - for (let key of keys) { - if (result && result[key] !== undefined) { - result = result[key]; - } else { - return undefined; +// Return YouTube Subscribers content script. Needs shared.js loaded first. + +(() => { + const R = RYTS; + const SEL = { + owner: "#owner-sub-count", + header: "#page-header > yt-page-header-renderer > yt-page-header-view-model > div > div.ytPageHeaderViewModelHeadline > div > yt-content-metadata-view-model > div:nth-child(3) > span:nth-child(1)", + headerRoot: "#page-header", + about: "#additional-info-container > table > tbody > tr:nth-child(6) > td:nth-child(2)", + channelRenderer: "ytd-channel-renderer", + }; + const ROUNDED = /^\s*[\d.,]+\s*[KMB]?\s+subscribers?\s*$/i; + const CHANNEL_HREF = /\/(?:channel\/(UC[\w-]{22})|(@[^/?#]+))/; + const LIVE_REFRESH_MS = 10_000; + const log = (...a) => console.log("[RYTS]", ...a); + + let settings = { format: "exact" }; + let page = null; // { url, id, name, handle, count, live } + const states = new Map(); // element -> { id, count, rounded, at, roll, live, prevText } + + // ---------- styles (YouTube's own colour variables, so light/dark/ambient all match) ---------- + + const style = document.createElement("style"); + style.textContent = ` + .ryts-roll { white-space: pre; font-variant-numeric: tabular-nums; } + .ryts-d, .ryts-t { display: inline-block; vertical-align: top; height: 1lh; } + .ryts-d { overflow: hidden; } + .ryts-reel { display: block; transition: transform .8s cubic-bezier(.2, .8, .2, 1); } + .ryts-reel > span { display: block; height: 1lh; } + .ryts-reel > span::before { content: attr(data-d); } + .ryts-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .ryts-live::before { content: ""; display: inline-block; width: .5em; height: .5em; margin-right: .4em; border-radius: 50%; + background: #ff0033; vertical-align: .1em; animation: ryts-pulse 1.6s ease-in-out infinite; } + @keyframes ryts-pulse { 50% { opacity: .35; } } + .ryts-open { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin-left: 6px; + border-radius: 50%; vertical-align: middle; color: var(--yt-spec-text-secondary, #606060); text-decoration: none; } + .ryts-open:hover { background: var(--yt-spec-10-percent-layer, rgba(0, 0, 0, .1)); color: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-open svg { width: 16px; height: 16px; fill: currentColor; } + .ryts-chip { font: 500 14px/36px Roboto, Arial, sans-serif; height: 36px; padding: 0 16px; border: 0; border-radius: 18px; + cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; + color: var(--yt-spec-text-primary, #0f0f0f); background: var(--yt-spec-badge-chip-background, rgba(0, 0, 0, .05)); } + .ryts-chip:hover { background: var(--yt-spec-button-chip-background-hover, rgba(0, 0, 0, .1)); } + .ryts-chip[aria-pressed="true"] { color: var(--yt-spec-text-primary-inverse, #fff); background: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-chip:focus-visible, .ryts-open:focus-visible { outline: 2px solid var(--yt-spec-call-to-action, #065fd4); outline-offset: 2px; } + .ryts-bar { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; font: 400 12px/18px Roboto, Arial, sans-serif; + color: var(--yt-spec-text-secondary, #606060); } + .ryts-panel { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 32px; margin: 16px 0 8px; padding: 16px 20px; + border-radius: 12px; font: 400 14px/20px Roboto, Arial, sans-serif; color: var(--yt-spec-text-secondary, #606060); + background: var(--yt-spec-badge-chip-background, rgba(0, 0, 0, .05)); } + .ryts-panel b { display: block; font-size: 16px; line-height: 22px; font-weight: 500; color: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-panel strong { display: block; font-size: 20px; line-height: 28px; font-weight: 700; color: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-panel .ryts-chip { margin-left: auto; } + .ryts-tip { position: fixed; z-index: 9999; max-width: 280px; padding: 8px 10px; border-radius: 4px; pointer-events: none; + font: 400 12px/16px Roboto, Arial, sans-serif; color: #fff; background: rgba(97, 97, 97, .95); } + @media (prefers-reduced-motion: reduce) { .ryts-reel { transition: none; } .ryts-live::before { animation: none; } } + `; + // Added in start(): at document-start (userscripts) may not exist yet. + + // Tiny DOM builder: h("div", { className: "x" }, child, "text", ...) + const h = (tag, props = {}, ...children) => { + const el = Object.assign(document.createElement(tag), props); + el.append(...children.filter((c) => c != null)); + return el; + }; + + // ---------- rendering ---------- + + const label = (s) => R.format(s.count, settings.format) + " subscribers"; + const tooltip = (s) => + `Estimated by ${R.SOURCE}, updated ${R.time(s.at)}.` + + (s.rounded ? ` YouTube shows ${s.rounded.trim()}.` : "") + + (s.live ? " Live: refreshes every 10 seconds." : ""); + + function paint(el, s, animate = false) { + const text = label(s); + el.dataset.rytsTip = tooltip(s); + el.setAttribute("aria-description", el.dataset.rytsTip); + el.classList.toggle("ryts-live", !!s.live); + el.dataset.rytsValue = text; + el.removeAttribute("is-empty"); + if (s.roll && R.canRoll()) R.roll(el, text, s.prevText, animate); + else if (el.textContent !== text) el.textContent = text; + s.prevText = text; + } + + function intact(el, s) { + if (el.dataset.rytsValue !== label(s)) return false; + return s.roll && R.canRoll() ? !!el.querySelector(":scope > .ryts-roll") : el.textContent === label(s); + } + + // Shows a count in `el` and keeps it there when YouTube re-renders the element. + function show(el, s) { + const old = states.get(el); + const state = { rounded: old?.rounded ?? el.textContent, prevText: old?.prevText, ...s, at: R.updatedAt(s.id) }; + states.set(el, state); + paint(el, state, !!old && old.count !== state.count); + if (!el.__rytsObserver) { + el.__rytsObserver = new MutationObserver(() => { + const st = states.get(el); + if (st && !intact(el, st)) paint(el, st); + }); + el.__rytsObserver.observe(el, { childList: true, characterData: true, subtree: true }); } + return state; } - return result; -} + function forget(el) { + el.__rytsObserver?.disconnect(); + delete el.__rytsObserver; + states.delete(el); + } -function check() { - let url = window.location.href; - if (url.includes("/results?search_query=")) { - setTimeout(function () { searchResults(); }, 1000); - } else { - const subscriberCount = document.querySelector(possibleSubCounters[1]); - const ownerSubCount = document.querySelector(possibleSubCounters[0]); + // One tooltip, styled like YouTube's, explaining where a count comes from. + const tip = h("div", { className: "ryts-tip", hidden: true }); + tip.setAttribute("role", "tooltip"); + document.addEventListener("mouseover", (e) => { + const el = e.target instanceof Element && e.target.closest("[data-ryts-tip]"); + if (!el) return void (tip.hidden = true); + if (!tip.isConnected) document.documentElement.append(tip); + tip.textContent = el.dataset.rytsTip; + tip.hidden = false; + const box = el.getBoundingClientRect(); + tip.style.left = Math.max(8, Math.min(box.left, innerWidth - tip.offsetWidth - 8)) + "px"; + tip.style.top = (box.bottom + 8 + tip.offsetHeight > innerHeight ? box.top - tip.offsetHeight - 8 : box.bottom + 8) + "px"; + }, { passive: true }); - if (subscriberCount) { - stats(); - } else if (ownerSubCount) { - stats2(); - } else { - setTimeout(check, 100); - } + // ---------- channel IDs ---------- + + const idByUrl = new Map(); + + function extractChannelId(html) { + const external = html.match(/"externalId":"(.*?)"/)?.[1]; + const browse = html.match(/"browse_id":"(.*?)"/)?.[1]; + const channel = html.match(/"channelId":"(.*?)"/)?.[1]; + return external || browse || channel || null; } -} - -async function fetchSubscriberData(channelId, targetSelectorIndex, element) { - try { - const response = await fetch(apiLink + channelId); - const data = await response.json(); - - if (data) { - - let subscriberText = getValueFromJson(data, apiPath); - console.log(subscriberText) - - if (element) { - element.textContent = parseInt(subscriberText).toLocaleString(strType) + " subscribers"; - } else { - const targetElement = document.querySelector(possibleSubCounters[targetSelectorIndex]); - - if (!targetElement) return; - if (subscriberText !== undefined && subscriberText !== null) { - if (targetElement.getAttribute("loaded") === "true") return; - - subscriberText = String(subscriberText).trim(); - const formattedCount = parseInt(subscriberText).toLocaleString(strType); - targetElement.textContent = formattedCount + " subscribers"; - targetElement.setAttribute("loaded", "true"); - targetElement.removeAttribute("is-empty"); - lastFetchedSubscriberCount = formattedCount; - - const ownerSubCount = document.querySelector("#owner-sub-count"); - if (ownerSubCount) { - ownerSubCount.__rytsExpectedText = formattedCount + " subscribers"; - ownerSubCount.textContent = ownerSubCount.__rytsExpectedText; - - if (!ownerSubCount.__rytsSubscriberObserver) { - ownerSubCount.__rytsSubscriberObserver = new MutationObserver(() => { - if (ownerSubCount.textContent !== ownerSubCount.__rytsExpectedText) { - ownerSubCount.textContent = ownerSubCount.__rytsExpectedText; - } - }); - ownerSubCount.__rytsSubscriberObserver.observe(ownerSubCount, { - characterData: true, - childList: true, - subtree: true - }); - } - } - - const updateAdditionalInfo = () => { - const additionalInfoElement = document.querySelector("#additional-info-container > table > tbody > tr:nth-child(6) > td:nth-child(2)"); - if (additionalInfoElement) { - additionalInfoElement.textContent = formattedCount + " subscribers"; - clearInterval(infoCheckInterval); - } - }; - - updateAdditionalInfo(); - - const infoCheckInterval = setInterval(updateAdditionalInfo, 500); - } - } - } else { - console.error("[RYTS] Error fetching subscriber data:", data); + + function idForUrl(url) { + if (!idByUrl.has(url)) { + idByUrl.set(url, fetch(url, { credentials: "include" }) + .then((r) => r.text()) + .then(extractChannelId) + .catch(() => null)); } + return idByUrl.get(url); + } - } catch (error) { - console.error("[RYTS] Error fetching subscriber data:", error); + async function idForHref(href) { + const m = href?.match(CHANNEL_HREF); + if (!m) return null; + if (m[1]) return m[1]; + return idForUrl("https://www.youtube.com/" + m[2]); + } + + // At most four lookups at a time for lists (search results, featured channels). + let active = 0; + const waiting = []; + function limited(task) { + return new Promise((resolve) => { + const run = async () => { + active++; + try { resolve(await task()); } catch { resolve(null); } finally { + active--; + waiting.shift()?.(); + } + }; + active < 4 ? run() : waiting.push(run); + }); } -} -function stats() { - const req = new XMLHttpRequest(); - req.open("GET", currentURL, false); - req.send(null); + // ---------- channel and watch pages ---------- - if (req.status === 200) { - const res = req.responseText; - const channelId = extractChannelId(res); - if (channelId) { - fetchSubscriberData(channelId, 1); + const waitFor = (find, ms = 15000) => new Promise((resolve) => { + const start = Date.now(); + const tick = () => { + const el = find(); + if (el || Date.now() - start > ms) resolve(el || null); + else setTimeout(tick, 150); + }; + tick(); + }); + + function pageMeta(isChannel) { + if (isChannel) { + const name = document.querySelector(`${SEL.headerRoot} h1`)?.textContent.trim(); + return { name, handle: location.pathname.match(/@[^/]+/)?.[0] }; } + const link = document.querySelector("#owner #channel-name a, ytd-video-owner-renderer #channel-name a"); + return { name: link?.textContent.trim(), handle: decodeURIComponent(link?.getAttribute("href")?.match(/@[^/?#]+/)?.[0] || "") || undefined }; } -} -function stats2() { - const req = new XMLHttpRequest(); - req.open("GET", currentURL, false); - req.send(null); + async function handlePage() { + const url = location.href; + stopLive(); + for (const el of [...states.keys()]) if (!el.closest(SEL.channelRenderer)) forget(el); + document.querySelectorAll(".ryts-panel, .ryts-open").forEach((n) => n.remove()); + page = null; + if (!/\/(channel\/|c\/|user\/|watch\?|@)/.test(url)) return; - if (req.status === 200) { - const res = req.responseText; - const channelId = extractChannelId(res); - if (channelId) { - fetchSubscriberData(channelId, 0); - } + const target = await waitFor(() => document.querySelector(SEL.header) || document.querySelector(SEL.owner)); + if (!target || url !== location.href) return; + const isChannel = target.matches(SEL.header); + const id = await idForUrl(url); + if (!id || url !== location.href) return; + const count = await R.fetchCount(id); + if (count === null || url !== location.href) return; + + page = { url, id, count, isChannel, ...pageMeta(isChannel) }; + log(isChannel ? "Channel page" : "Watch page", id, count); + R.observe(id, count, page); + show(target, { id, count, roll: true }); + if (isChannel) { + addCounterLink(target); // inline in the header's stats row; watch pages have no inline spot + ownChannelPanel(); + } else startLiveIfLive(target); + decorate(); } -} -function extractChannelId(responseText) { - const browseIdMatch = responseText.match(/"browse_id":"(.*?)"/); - const channelIdMatch = responseText.match(/"channelId":"(.*?)"/); - const externalIdMatch = responseText.match(/"externalId":"(.*?)"/); + function addCounterLink(el) { + const href = page && R.pageUrl("counter.html", { c: page.id, n: page.name || page.handle || "" }); + if (!href || el.nextElementSibling?.classList.contains("ryts-open")) return; + const a = document.createElement("a"); + a.className = "ryts-open"; + a.href = href; + a.target = "_blank"; + a.title = "Open the live counter"; + a.setAttribute("aria-label", "Open the live counter"); + const NS = "http://www.w3.org/2000/svg"; + const svg = document.createElementNS(NS, "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); + svg.setAttribute("aria-hidden", "true"); + const path = document.createElementNS(NS, "path"); + path.setAttribute("d", "M5 5h6v2H7v4H5V5zm8 0h6v6h-2V7h-4V5zM5 13h2v4h4v2H5v-6zm12 0h2v6h-6v-2h4v-4z"); + svg.append(path); + a.append(svg); + el.after(a); + } - console.log("[RYTS] Browse ID:", browseIdMatch?.[1]); - console.log("[RYTS] Channel ID:", channelIdMatch?.[1]); - console.log("[RYTS] External ID:", externalIdMatch?.[1]); + // ---------- live streams: refresh the count while the stream is on ---------- - return externalIdMatch?.[1] || browseIdMatch?.[1] || channelIdMatch?.[1] || null; -} + let liveTimer = null; + const isLive = () => + !!document.querySelector("#movie_player.ytp-live, .html5-video-player.ytp-live") || + (!!document.querySelector('meta[itemprop="isLiveBroadcast"][content="True"]') && !document.querySelector('meta[itemprop="endDate"]')); -function clearLoadedState() { - for (let selector of possibleSubCounters) { - const element = document.querySelector(selector); - if (element) { - element.removeAttribute("loaded"); - console.log("[RYTS] Cleared loaded state for selector:", selector); - } + function startLiveIfLive(el) { + if (!isLive()) return; + const url = location.href; + const s = states.get(el); + s.live = true; + paint(el, s); + liveTimer = setInterval(async () => { + if (location.href !== url || !page) return stopLive(); + const count = await R.fetchCount(page.id, { fresh: true }); + if (count === null || location.href !== url) return; + page.count = count; + R.observe(page.id, count, page); + show(el, { id: page.id, count, roll: true, live: true }); + }, LIVE_REFRESH_MS); } -} - -setInterval(() => { - const url = window.location.href; - if (currentURL !== url) { - currentURL = url; - console.log("[RYTS] URL changed:", url); - clearLoadedState(); - if (url.includes("/results?search_query=")) { - setTimeout(searchResults, 1000); - } else if (/\/channel\/|\/c\/|\/user\/|\/watch\?v=|\/@/.test(url)) { - const subscriberCount = document.querySelector(possibleSubCounters[1]); - const isWatchPage = url.includes("/watch?v="); - - console.log("[RYTS]", isWatchPage ? "Watch page" : "Channel page"); - if (isWatchPage) { - stats2(); - } else { - const updateStats = () => { - if (subscriberCount && subscriberCount.getAttribute("is-empty") === null) { - stats(); - } else { - setTimeout(updateStats, 500); - } - }; - updateStats(); - } + + function stopLive() { + clearInterval(liveTimer); + liveTimer = null; + } + + // ---------- your own channel: milestone panel ---------- + + async function ownChannelPanel() { + const root = document.querySelector(SEL.headerRoot); + if (!page?.isChannel || !root || !root.querySelector('a[href*="studio.youtube.com"]')) return; + const history = (await R.getHistory())[page.id]; + const perDay = R.growthPerDay(history?.points); + const goal = R.nextMilestone(page.count); + const togo = goal - page.count; + const eta = perDay > 0 ? new Date(Date.now() + (togo / perDay) * 86_400_000) : null; + if (!page?.isChannel || document.querySelector(".ryts-panel")) return; + + const panel = document.createElement("section"); + panel.className = "ryts-panel"; + panel.setAttribute("aria-label", "Your channel"); + const cell = (big, small) => h("div", {}, h("strong", { textContent: big }), small); + panel.append(h("div", {}, h("b", { textContent: "Your channel" }), `Next milestone: ${R.exact(goal)}`), cell(R.exact(togo), "to go")); + if (perDay !== null) { + panel.append( + cell(`${perDay >= 0 ? "+" : "−"}${R.exact(Math.round(Math.abs(perDay)))}`, "per day, recently"), + cell(eta ? eta.toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" }) : "Not growing", "projected milestone date"), + ); + } else { + panel.append(h("div", { textContent: "Growth and a projected date appear after you've visited a few times." })); + } + const href = R.pageUrl("counter.html", { c: page.id, n: page.name || "" }); + if (href) { + const open = document.createElement("a"); + Object.assign(open, { className: "ryts-chip", href, target: "_blank", textContent: "Open live counter" }); + panel.append(open); } + root.after(panel); } -}, 500); - -async function searchResults() { - console.log('[RYTS] Search Page') - try { - let channelRenderers = document.querySelectorAll("ytd-channel-renderer"); - for (const channelRenderer of channelRenderers) { - try { - let link = channelRenderer.querySelector("#main-link").href; - console.log(link) - if (link) { - if (link.includes("@")) { - fetch("https://www.youtube.com/@" + link.split("@")[1]) - .then((response) => response.text()) - .then(async (data) => { - if (data && data.includes('externalId')) { - let channelId = data.split('"externalId":"')[1].split('"')[0]; - fetchSubscriberData(channelId, 0, channelRenderer.querySelector("#video-count")); - } - }); - } else { - - } - } - } catch (error) { - console.error("[RYTS] Error fetching search results:", error); + + // ---------- lists: search results, featured channels, About dialog ---------- + + function decorate() { + // Search results (existing behaviour: the count lives in #video-count). + if (location.href.includes("/results?")) { + for (const renderer of document.querySelectorAll(SEL.channelRenderer)) { + const target = renderer.querySelector("#video-count"); + const href = renderer.querySelector("#main-link")?.href; + if (!target || !href || renderer.__ryts) continue; + renderer.__ryts = limited(async () => { + const id = await idForHref(href); + const count = id && await R.fetchCount(id); + if (count == null) return null; + R.observe(id, count, { name: renderer.querySelector("#channel-title #text, #text")?.textContent.trim(), handle: href.match(/@[^/?#]+/)?.[0] }); + show(target, { id, count }); + renderer.dataset.rytsCount = count; + return count; + }); } + sortButton(); } - } catch (error) { - console.error("[RYTS] Error fetching search results:", error); - setTimeout(searchResults, 1000); + + // Featured channels and channel lists: any "123K subscribers" text near a channel link. + const walker = document.createTreeWalker(document.querySelector("ytd-page-manager") || document.body, NodeFilter.SHOW_TEXT, { + acceptNode: (n) => (ROUNDED.test(n.data) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP), + }); + const found = []; + while (walker.nextNode()) found.push(walker.currentNode.parentElement); + for (const el of found) { + if (!el || el.__ryts || states.has(el) || el.matches(SEL.owner) || el.closest(`${SEL.channelRenderer}, ${SEL.headerRoot}, #owner`)) continue; + const card = el.closest("ytd-grid-channel-renderer, ytd-mini-channel-renderer, ytd-channel-renderer, yt-lockup-view-model, ytd-rich-item-renderer") + || el.parentElement?.closest(":has(a[href*='/@'], a[href*='/channel/UC'])"); + const href = card?.querySelector("a[href*='/@'], a[href*='/channel/UC']")?.getAttribute("href"); + if (!href) continue; + el.__ryts = limited(async () => { + const id = await idForHref(href); + const count = id && await R.fetchCount(id); + if (count == null) return; + show(el, { id, count }); + }); + } + + // The About dialog's table row. + const about = page?.isChannel && document.querySelector(SEL.about); + if (about && !states.has(about)) show(about, { id: page.id, count: page.count }); } -} -check(); + function sortButton() { + const renderers = [...document.querySelectorAll(SEL.channelRenderer)]; + if (renderers.length < 2 || document.querySelector(".ryts-bar")) return; + const bar = document.createElement("div"); + bar.className = "ryts-bar"; + const button = h("button", { type: "button", className: "ryts-chip", textContent: "Sort channels by subscribers" }); + button.setAttribute("aria-pressed", "false"); + bar.append(button, h("span", { textContent: "Exact counts by Return YouTube Subscribers" })); + renderers[0].before(bar); + button.addEventListener("click", async () => { + button.textContent = "Sorting…"; + const list = [...document.querySelectorAll(SEL.channelRenderer)]; + await Promise.all(list.map((r) => r.__ryts)); + const marker = document.createComment("ryts"); + bar.after(marker); + list.sort((a, b) => (+b.dataset.rytsCount || 0) - (+a.dataset.rytsCount || 0)) + .forEach((r) => marker.before(r)); + marker.remove(); + button.textContent = "Sorted by subscribers"; + button.setAttribute("aria-pressed", "true"); + }); + } + + // ---------- wiring ---------- + + let scheduled = null; + const pageObserver = new MutationObserver(() => { + if (scheduled) return; + scheduled = setTimeout(() => { + scheduled = null; + decorate(); + }, 400); + }); + + let lastUrl = null; + const onNavigate = () => { + if (location.href === lastUrl) return; + lastUrl = location.href; + log("URL changed:", lastUrl); + handlePage(); + decorate(); + }; + document.addEventListener("yt-navigate-finish", onNavigate); + setInterval(() => document.body && onNavigate(), 1000); // fallback if YouTube renames its navigation event + + R.getSettings().then((s) => { settings = s; }); + R.onSettings((s) => { + settings = s; + for (const [el, st] of states) paint(el, st); + }); + + const start = () => { + (document.head || document.documentElement).append(style); + pageObserver.observe(document.documentElement, { childList: true, subtree: true }); + onNavigate(); + }; + document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", start, { once: true }) : start(); +})(); diff --git a/src/manifest.json b/src/manifest.json index e5ac9b2..2ac0cc2 100644 --- a/src/manifest.json +++ b/src/manifest.json @@ -12,13 +12,28 @@ "96": "icons/icon-96.png", "128": "icons/icon-128.png" }, + "action": { + "default_title": "Return YouTube Subscribers", + "default_popup": "popup.html", + "default_icon": { + "16": "icons/icon-16.png", + "32": "icons/icon-32.png" + } + }, "content_scripts": [ { "matches": ["https://*.youtube.com/*"], - "js": ["main.js"] + "js": ["shared.js", "main.js"] } ], + "permissions": ["storage"], "host_permissions": ["https://backend.mixerno.space/*"], + "web_accessible_resources": [ + { + "resources": ["counter.html"], + "matches": ["https://*.youtube.com/*"] + } + ], "browser_specific_settings": { "gecko": { "id": "__FIREFOX_ID__", diff --git a/src/pages.css b/src/pages.css new file mode 100644 index 0000000..fb81d10 --- /dev/null +++ b/src/pages.css @@ -0,0 +1,73 @@ +/* Styles for the toolbar popup and the counter page. Same palette as the website. */ +:root { + --paper: #F5F6FA; --surface: #FFFFFF; --mist: #E3E6EF; --ink: #1A1C2E; --slate: #5D6178; + --red: #E0262F; --red-ink: #C11A23; --up: #18794E; color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root { --paper: #171928; --surface: #20233A; --mist: #2E3250; --ink: #ECEEF6; --slate: #A3A8C3; --red-ink: #FF6B6B; --up: #4CC38A; color-scheme: dark; } +} +* { box-sizing: border-box; } +body { margin: 0; background: var(--paper); color: var(--ink); font: 400 14px/1.5 Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + font-feature-settings: "tnum" 1; -webkit-font-smoothing: antialiased; } +h1, h2 { margin: 0; letter-spacing: -0.02em; } +h2 { font-size: 13px; font-weight: 700; margin-bottom: 8px; } +a { color: inherit; } +:focus-visible { outline: 2px solid var(--red); outline-offset: 2px; border-radius: 4px; } +button, select { font: inherit; color: inherit; } +.btn { border: 0; border-radius: 999px; background: var(--red); color: #fff; font-weight: 700; padding: 8px 16px; cursor: pointer; } +.btn:hover { background: var(--red-ink); } +.btn-quiet { background: transparent; color: var(--ink); border: 2px solid var(--mist); padding: 6px 14px; } +.btn-quiet:hover { background: transparent; border-color: var(--slate); } +select { background: var(--surface); border: 2px solid var(--mist); border-radius: 8px; padding: 6px 8px; min-width: 0; } + +/* digit roll (same as the content script) */ +.ryts-roll { white-space: pre; font-variant-numeric: tabular-nums; } +.ryts-d, .ryts-t { display: inline-block; vertical-align: top; height: 1lh; } +.ryts-d { overflow: hidden; } +.ryts-reel { display: block; transition: transform .8s cubic-bezier(.2, .8, .2, 1); } +.ryts-reel > span { display: block; height: 1lh; } +.ryts-reel > span::before { content: attr(data-d); } +.ryts-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +@media (prefers-reduced-motion: reduce) { .ryts-reel { transition: none; } } + +/* ---------- popup ---------- */ +.popup { width: 360px; padding: 16px; } +.brand { text-decoration: none; display: flex; align-items: center; gap: 10px; font-weight: 800; letter-spacing: -0.01em; font-size: 15px; margin-bottom: 14px; } +.tabs { display: flex; gap: 6px; margin-bottom: 8px; } +.tabs button { border: 2px solid var(--mist); background: transparent; border-radius: 999px; padding: 4px 12px; font-weight: 600; font-size: 13px; color: var(--slate); cursor: pointer; } +.tabs button[aria-selected="true"] { background: var(--ink); border-color: var(--ink); color: var(--paper); } +.list { list-style: none; margin: 0; padding: 0; } +.list li { border-bottom: 1px solid var(--mist); padding: 2px 0; } +.list a { display: grid; grid-template-columns: 22px 1fr auto; gap: 2px 10px; align-items: baseline; padding: 7px 6px; text-decoration: none; border-radius: 6px; } +.list a:hover { background: var(--surface); } +.list .rank { color: var(--slate); font-weight: 700; font-size: 12px; } +.list .name { font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.list .count { color: var(--slate); grid-column: 2; font-size: 13px; } +.list .delta { grid-row: 1 / span 2; grid-column: 3; align-self: center; font-weight: 700; font-size: 13px; color: var(--up); } +.list .delta.down { color: var(--red-ink); } +.empty { color: var(--slate); padding: 12px 4px; margin: 0; } +.popup section { margin-top: 16px; padding-top: 14px; border-top: 2px solid var(--mist); } +.race-row { display: grid; grid-template-columns: 1fr auto 1fr; gap: 8px; align-items: center; margin-bottom: 10px; color: var(--slate); font-weight: 600; } +.settings label { display: flex; align-items: center; gap: 8px; padding: 3px 0; cursor: pointer; } +.settings label span { margin-left: auto; color: var(--slate); } +.fine { color: var(--slate); font-size: 12px; margin: 14px 0 0; } + +/* ---------- counter page ---------- */ +.counter { min-height: 100vh; display: grid; grid-template-rows: auto 1fr auto; } +.counter > header { padding: 20px clamp(24px, 6vw, 80px) 0; } +.board { display: grid; align-content: center; gap: 48px; padding: clamp(24px, 6vw, 80px); } +.board.race { grid-template-columns: 1fr 1fr; align-items: end; column-gap: clamp(24px, 6vw, 96px); } +.side h1 { font-size: clamp(20px, 3vw, 36px); font-weight: 700; margin-bottom: 8px; } +.big { font-weight: 800; letter-spacing: -0.045em; line-height: 1; white-space: nowrap; font-size: clamp(56px, 13vw, 220px); } +.race .big { font-size: clamp(36px, 7vw, 140px); } +.side p { color: var(--slate); font-size: clamp(16px, 1.6vw, 22px); margin: 12px 0 0; } +.leader .big { color: var(--ink); } +.gap { grid-column: 1 / -1; font-size: clamp(18px, 2.2vw, 30px); color: var(--slate); margin: 0; border-top: 2px solid var(--mist); padding-top: 24px; } +.gap strong { color: var(--red-ink); } +.bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; padding: 16px clamp(24px, 6vw, 80px); border-top: 2px solid var(--mist); } +.bar .status { color: var(--slate); margin-right: auto; } +.bar label { display: flex; align-items: center; gap: 8px; color: var(--slate); font-weight: 600; } +.bar .brand { margin: 0; font-size: 13px; text-decoration: none; } +:fullscreen .bar { opacity: 0; transition: opacity .2s; } +:fullscreen .bar:hover, :fullscreen .bar:focus-within { opacity: 1; } +@media (max-width: 700px) { .board.race { grid-template-columns: 1fr; } } diff --git a/src/popup.html b/src/popup.html new file mode 100644 index 0000000..e69fcc3 --- /dev/null +++ b/src/popup.html @@ -0,0 +1,38 @@ + + + + + Return YouTube Subscribers + + + +
Return YouTube Subscribers
+ +
+ + +
+
    + + +
    +

    Race two channels

    +
    + + vs + +
    + +
    + +
    +

    Number format

    + + +
    + +

    Growth is measured from counts the extension sees while you browse YouTube, and is stored only on this device.

    + + + + diff --git a/src/popup.js b/src/popup.js new file mode 100644 index 0000000..522fb1d --- /dev/null +++ b/src/popup.js @@ -0,0 +1,70 @@ +// Toolbar popup: channels you've viewed, ranked by growth; race picker; number format. + +(async () => { + const R = RYTS; + const history = await R.getHistory(); + const channels = Object.entries(history).map(([id, h]) => ({ + id, + name: h.name || h.handle || id, + count: h.points.at(-1)?.[1], + perDay: R.growthPerDay(h.points), + seen: h.seen || 0, + })).filter((c) => c.count != null); + + const list = document.getElementById("list"); + const empty = document.getElementById("empty"); + const counterLink = (params) => R.pageUrl("counter.html", params); + + function render(view) { + const rows = view === "growing" + ? channels.filter((c) => c.perDay !== null).sort((a, b) => b.perDay - a.perDay) + : [...channels].sort((a, b) => b.seen - a.seen); + list.replaceChildren(...rows.slice(0, 10).map((c, i) => { + const li = document.createElement("li"); + const a = document.createElement("a"); + a.href = counterLink({ c: c.id, n: c.name }); + a.target = "_blank"; + const cell = (cls, text) => Object.assign(document.createElement("span"), { className: cls, textContent: text }); + const delta = c.perDay === null ? "" : `${c.perDay >= 0 ? "+" : "−"}${R.exact(Math.round(Math.abs(c.perDay)))}/day`; + a.append(cell("rank", i + 1), cell("name", c.name), cell("delta" + (c.perDay < 0 ? " down" : ""), delta), cell("count", R.exact(c.count) + " subscribers")); + li.append(a); + return li; + })); + empty.hidden = rows.length > 0; + empty.textContent = channels.length === 0 + ? "Open a few YouTube channels or videos. They'll appear here with their exact counts." + : "Growth shows up once you've seen a channel twice, at least 30 minutes apart. Check Recently viewed for now."; + } + + const tabs = [...document.querySelectorAll('[role="tab"]')]; + for (const tab of tabs) { + tab.addEventListener("click", () => { + tabs.forEach((t) => t.setAttribute("aria-selected", t === tab)); + render(tab.dataset.view); + }); + } + render(channels.some((c) => c.perDay !== null) || channels.length === 0 ? "growing" : "recent"); + if (!channels.some((c) => c.perDay !== null) && channels.length) tabs.forEach((t) => t.setAttribute("aria-selected", t.dataset.view === "recent")); + + // Race picker + const [a, b] = ["race-a", "race-b"].map((id) => document.getElementById(id)); + const byCount = [...channels].sort((x, y) => y.count - x.count); + for (const select of [a, b]) { + select.replaceChildren(...byCount.map((c) => new Option(c.name, c.id))); + } + if (byCount[1]) b.value = byCount[1].id; + const raceButton = document.getElementById("race"); + raceButton.disabled = byCount.length < 2; + if (byCount.length < 2) raceButton.title = "View at least two channels first"; + raceButton.addEventListener("click", () => { + const name = (id) => channels.find((c) => c.id === id)?.name || ""; + open(counterLink({ c: a.value, n: name(a.value), vs: b.value, vn: name(b.value) }), "_blank"); + }); + + // Number format + const settings = await R.getSettings(); + for (const radio of document.querySelectorAll('input[name="format"]')) { + radio.checked = radio.value === settings.format; + radio.addEventListener("change", () => R.setSettings({ format: radio.value })); + } +})(); diff --git a/src/shared.js b/src/shared.js new file mode 100644 index 0000000..10360c4 --- /dev/null +++ b/src/shared.js @@ -0,0 +1,183 @@ +// Shared helpers for the content script, the toolbar popup and the counter page. +// Plain script (no modules) so it also works as part of the userscript. + +var RYTS = (() => { + const API = "https://backend.mixerno.space/api/youtube/estv3/"; + const SOURCE = "Mixerno.space"; + + // Extension storage when running as an extension, localStorage in the userscript. + const ext = globalThis.browser?.storage?.local ? globalThis.browser + : globalThis.chrome?.storage?.local ? globalThis.chrome : null; + + const store = { + async get(key, fallback) { + try { + if (ext) return (await ext.storage.local.get(key))[key] ?? fallback; + const raw = localStorage.getItem("ryts:" + key); + return raw ? JSON.parse(raw) : fallback; + } catch { + return fallback; + } + }, + async set(key, value) { + try { + if (ext) await ext.storage.local.set({ [key]: value }); + else localStorage.setItem("ryts:" + key, JSON.stringify(value)); + } catch { /* storage full or blocked: features degrade, counts still show */ } + }, + onChange(key, callback) { + ext?.storage?.onChanged?.addListener((changes, area) => { + if (area === "local" && changes[key]) callback(changes[key].newValue); + }); + }, + }; + + // ---------- settings ---------- + + const DEFAULT_SETTINGS = { format: "exact" }; + const getSettings = async () => ({ ...DEFAULT_SETTINGS, ...(await store.get("settings", {})) }); + const setSettings = async (patch) => store.set("settings", { ...(await getSettings()), ...patch }); + const onSettings = (callback) => store.onChange("settings", (s) => callback({ ...DEFAULT_SETTINGS, ...s })); + + // ---------- formatting ---------- + + const exactFormat = new Intl.NumberFormat("en-US"); + // One more significant figure than YouTube's three: 452.3M, 1.284M, 34.01K. + const compactFormat = new Intl.NumberFormat("en-US", { + notation: "compact", maximumSignificantDigits: 4, roundingMode: "trunc", + }); + const format = (n, mode = "exact") => (mode === "compact" && n >= 1000 ? compactFormat : exactFormat).format(n); + const exact = (n) => exactFormat.format(n); + const time = (t) => new Date(t).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }); + + // ---------- counts ---------- + + const cache = new Map(); // id -> { count, at, promise } + const CACHE_MS = 60_000; + + async function fetchCount(id, { fresh = false } = {}) { + const hit = cache.get(id); + if (hit?.promise) return hit.promise; + if (!fresh && hit && Date.now() - hit.at < CACHE_MS) return hit.count; + const promise = fetch(API + encodeURIComponent(id)) + .then((r) => (r.ok ? r.json() : null)) + .then((data) => { + const n = parseInt(data?.items?.[0]?.statistics?.subscriberCount, 10); + return Number.isFinite(n) ? n : null; + }) + .catch(() => null) + .then((count) => { + cache.set(id, count === null ? undefined : { count, at: Date.now() }); + if (count === null) cache.delete(id); + return count; + }); + cache.set(id, { ...hit, promise }); + return promise; + } + + const updatedAt = (id) => cache.get(id)?.at ?? Date.now(); + + // ---------- history (local only; powers growth, projections and the popup) ---------- + + const MAX_POINTS = 240; + const MIN_GAP_MS = 5 * 60_000; + let historyWrite = Promise.resolve(); + + function observe(id, count, meta = {}) { + historyWrite = historyWrite.then(async () => { + const history = await store.get("history", {}); + const entry = history[id] || { points: [] }; + if (meta.name) entry.name = meta.name; + if (meta.handle) entry.handle = meta.handle; + const now = Date.now(); + const last = entry.points[entry.points.length - 1]; + // Keep one point per five minutes; within that window just update the latest value. + if (last && now - last[0] < MIN_GAP_MS && entry.points.length > 1) entry.points[entry.points.length - 1] = [now, count]; + else entry.points.push([now, count]); + entry.points = entry.points.slice(-MAX_POINTS); + entry.seen = now; + history[id] = entry; + await store.set("history", history); + }); + return historyWrite; + } + + const getHistory = () => store.get("history", {}); + + // Subscribers per day across the stored points; needs at least 30 minutes of data. + function growthPerDay(points = []) { + if (points.length < 2) return null; + const [t0, c0] = points[0]; + const [t1, c1] = points[points.length - 1]; + const days = (t1 - t0) / 86_400_000; + return days >= 1 / 48 ? (c1 - c0) / days : null; + } + + // Next "round" milestone two significant figures up: 34,010 -> 35,000; 452,318,906 -> 460,000,000. + function nextMilestone(n) { + const step = 10 ** Math.max(2, String(Math.floor(n)).length - 2); + return (Math.floor(n / step) + 1) * step; + } + + // ---------- digit roll ---------- + + // Renders `text` into `el` as rolling digits. Digits are drawn by CSS from data + // attributes, so the element's text stays clean; a visually hidden copy is what + // screen readers read and what gets copied. + const canRoll = () => typeof CSS !== "undefined" && CSS.supports("height", "1lh"); + + function roll(el, text, prevText = "", animate = false) { + const wrap = document.createElement("span"); + wrap.className = "ryts-roll"; + wrap.setAttribute("aria-hidden", "true"); + const chars = [...text]; + const offset = chars.length - [...prevText].length; // align digits from the right + const moves = []; + let run = null; // consecutive non-digits share one box, aligned like the digits + chars.forEach((ch, i) => { + if (!/\d/.test(ch)) { + if (!run) wrap.append(run = Object.assign(document.createElement("span"), { className: "ryts-t" })); + run.textContent += ch; + return; + } + run = null; + const to = +ch; + const before = [...prevText][i - offset]; + const from = animate && /\d/.test(before || "") ? +before : to; + const box = document.createElement("span"); + box.className = "ryts-d"; + const reel = document.createElement("span"); + reel.className = "ryts-reel"; + for (let d = 0; d < 10; d++) { + const face = document.createElement("span"); + face.dataset.d = d; + reel.append(face); + } + reel.style.transform = `translateY(calc(-1lh * ${from}))`; + box.append(reel); + wrap.append(box); + if (from !== to) moves.push([reel, to]); + }); + const sr = document.createElement("span"); + sr.className = "ryts-sr"; + sr.textContent = text; + el.replaceChildren(wrap, sr); + if (moves.length) { + wrap.getBoundingClientRect(); // commit start positions + requestAnimationFrame(() => moves.forEach(([reel, to]) => { reel.style.transform = `translateY(calc(-1lh * ${to}))`; })); + } + } + + // ---------- extension pages ---------- + + const pageUrl = (page, params) => { + const getURL = (globalThis.browser || globalThis.chrome)?.runtime?.getURL; + if (!getURL || !ext) return null; // userscript: no extension pages + return getURL(page) + "?" + new URLSearchParams(params); + }; + + return { + API, SOURCE, store, getSettings, setSettings, onSettings, + format, exact, time, canRoll, roll, fetchCount, updatedAt, observe, getHistory, growthPerDay, nextMilestone, pageUrl, + }; +})(); diff --git a/store/listing.json b/store/listing.json index 2001bd1..56278fc 100644 --- a/store/listing.json +++ b/store/listing.json @@ -5,7 +5,17 @@ "tagline": "Exact subscriber counts, back on YouTube.", "safariSubtitle": "Exact YouTube sub counts", "safariPromotionalText": "YouTube rounds every subscriber count. Return YouTube Subscribers puts the full number back on channel pages, watch pages and search results.", - "keywords": ["youtube", "subscribers", "subscriber count", "exact", "live count", "channel", "creator", "stats", "counter"], + "keywords": [ + "youtube", + "subscribers", + "subscriber count", + "exact", + "live count", + "channel", + "creator", + "stats", + "counter" + ], "description": [ "Since September 2019 YouTube has rounded every subscriber count: \"1.2M subscribers\" could mean anything from 1,200,000 to 1,299,999. Return YouTube Subscribers puts the full number back.", "", @@ -14,6 +24,15 @@ "• Watch pages: the exact count appears under the channel name on every video", "• Search results: exact counts on channel results", "• Keeps working as you browse; no page reloads needed", + "• Sort channel search results by exact subscriber count", + "• Exact counts on featured channels and channel lists", + "• Live streams: the count refreshes every 10 seconds, with rolling digits", + "• Full-screen live counter, and race mode to watch two channels side by side", + "• Save a shareable image of any count or race", + "• On your own channel: next milestone, subscribers to go and a projected date", + "• Toolbar popup ranking the channels you've viewed by how fast they're growing", + "• Choose exact (452,318,906) or compact (452.3M) numbers", + "• Hover any count to see where it came from and when it was updated", "", "HOW IT WORKS", "YouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure.", @@ -21,6 +40,7 @@ "PRIVACY", "• No account, no sign-in, nothing to configure", "• No analytics, ads or tracking inside the extension", + "• Growth history stays on your device", "• The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count", "• Open source on GitHub", "", @@ -48,16 +68,33 @@ }, "dataDisclosure": { "summary": "The extension sends the public channel ID of the YouTube channel being viewed to backend.mixerno.space to look up its subscriber count. Nothing else is collected, stored or sold.", - "chromeDataTypes": ["Web history (the ID of the YouTube channel currently being viewed)"], + "chromeDataTypes": [ + "Web history (the ID of the YouTube channel currently being viewed)" + ], "singlePurpose": "Show exact, unabbreviated subscriber counts on YouTube in place of YouTube's rounded counts.", "hostPermissionJustification": "backend.mixerno.space is the API that returns the estimated subscriber count for a channel ID. youtube.com access is needed to read the channel ID and replace the rounded count on the page.", "reviewerNotes": "To test: open any YouTube channel page (for example https://www.youtube.com/@YouTube) or video. The rounded count under the channel name (e.g. \"14.2M subscribers\") is replaced with the full number fetched from https://backend.mixerno.space/api/youtube/estv3/. No minification or bundling is used; the submitted main.js is the source." }, "screenshots": [ - { "file": "screenshot-1-channel.png", "caption": "Exact subscriber counts on every channel page" }, - { "file": "screenshot-2-watch.png", "caption": "The full number under every video" }, - { "file": "screenshot-3-search.png", "caption": "Exact counts in search results" }, - { "file": "screenshot-4-before-after.png", "caption": "452M becomes 452,318,906" }, - { "file": "screenshot-5-privacy.png", "caption": "Lightweight, open source, no tracking" } + { + "file": "screenshot-1-channel.png", + "caption": "Exact subscriber counts on every channel page" + }, + { + "file": "screenshot-2-watch.png", + "caption": "The full number under every video" + }, + { + "file": "screenshot-3-search.png", + "caption": "Exact counts in search results" + }, + { + "file": "screenshot-4-before-after.png", + "caption": "452M becomes 452,318,906" + }, + { + "file": "screenshot-5-privacy.png", + "caption": "Lightweight, open source, no tracking" + } ] } diff --git a/store/listings/amo-metadata.json b/store/listings/amo-metadata.json index e6aafd1..cfdafd4 100644 --- a/store/listings/amo-metadata.json +++ b/store/listings/amo-metadata.json @@ -6,7 +6,7 @@ "en-US": "See exact subscriber counts on YouTube again: on channel pages, under videos, and in search results." }, "description": { - "en-US": "Since September 2019 YouTube has rounded every subscriber count: \"1.2M subscribers\" could mean anything from 1,200,000 to 1,299,999. Return YouTube Subscribers puts the full number back.\n\nWHAT IT DOES\n• Channel pages: \"452M subscribers\" becomes \"452,318,906 subscribers\"\n• Watch pages: the exact count appears under the channel name on every video\n• Search results: exact counts on channel results\n• Keeps working as you browse; no page reloads needed\n\nHOW IT WORKS\nYouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure.\n\nPRIVACY\n• No account, no sign-in, nothing to configure\n• No analytics, ads or tracking inside the extension\n• The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count\n• Open source on GitHub\n\nLINKS\nWebsite: https://ryts.mgcounts.com\nSource code: https://github.com/returnyoutubesubscribers/returnyoutubesubscribers.github.io\nDiscord: https://discord.gg/RRwzccVWfD\n\nReturn YouTube Subscribers is an independent project and is not affiliated with YouTube or Google." + "en-US": "Since September 2019 YouTube has rounded every subscriber count: \"1.2M subscribers\" could mean anything from 1,200,000 to 1,299,999. Return YouTube Subscribers puts the full number back.\n\nWHAT IT DOES\n• Channel pages: \"452M subscribers\" becomes \"452,318,906 subscribers\"\n• Watch pages: the exact count appears under the channel name on every video\n• Search results: exact counts on channel results\n• Keeps working as you browse; no page reloads needed\n• Sort channel search results by exact subscriber count\n• Exact counts on featured channels and channel lists\n• Live streams: the count refreshes every 10 seconds, with rolling digits\n• Full-screen live counter, and race mode to watch two channels side by side\n• Save a shareable image of any count or race\n• On your own channel: next milestone, subscribers to go and a projected date\n• Toolbar popup ranking the channels you've viewed by how fast they're growing\n• Choose exact (452,318,906) or compact (452.3M) numbers\n• Hover any count to see where it came from and when it was updated\n\nHOW IT WORKS\nYouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure.\n\nPRIVACY\n• No account, no sign-in, nothing to configure\n• No analytics, ads or tracking inside the extension\n• Growth history stays on your device\n• The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count\n• Open source on GitHub\n\nLINKS\nWebsite: https://ryts.mgcounts.com\nSource code: https://github.com/returnyoutubesubscribers/returnyoutubesubscribers.github.io\nDiscord: https://discord.gg/RRwzccVWfD\n\nReturn YouTube Subscribers is an independent project and is not affiliated with YouTube or Google." }, "homepage": { "en-US": "https://ryts.mgcounts.com" diff --git a/store/listings/chrome-web-store.md b/store/listings/chrome-web-store.md index 43e57ff..20f9918 100644 --- a/store/listings/chrome-web-store.md +++ b/store/listings/chrome-web-store.md @@ -15,7 +15,7 @@ Return YouTube Subscribers See exact subscriber counts on YouTube again: on channel pages, under videos, and in search results. ``` -## Description (1274/16000) +## Description (1901/16000) ```text Since September 2019 YouTube has rounded every subscriber count: "1.2M subscribers" could mean anything from 1,200,000 to 1,299,999. Return YouTube Subscribers puts the full number back. @@ -25,6 +25,15 @@ WHAT IT DOES • Watch pages: the exact count appears under the channel name on every video • Search results: exact counts on channel results • Keeps working as you browse; no page reloads needed +• Sort channel search results by exact subscriber count +• Exact counts on featured channels and channel lists +• Live streams: the count refreshes every 10 seconds, with rolling digits +• Full-screen live counter, and race mode to watch two channels side by side +• Save a shareable image of any count or race +• On your own channel: next milestone, subscribers to go and a projected date +• Toolbar popup ranking the channels you've viewed by how fast they're growing +• Choose exact (452,318,906) or compact (452.3M) numbers +• Hover any count to see where it came from and when it was updated HOW IT WORKS YouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure. @@ -32,6 +41,7 @@ YouTube no longer publishes exact counts. The extension reads the ID of the chan PRIVACY • No account, no sign-in, nothing to configure • No analytics, ads or tracking inside the extension +• Growth history stays on your device • The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count • Open source on GitHub diff --git a/store/listings/edge-add-ons.md b/store/listings/edge-add-ons.md index b6b2105..017fac9 100644 --- a/store/listings/edge-add-ons.md +++ b/store/listings/edge-add-ons.md @@ -15,7 +15,7 @@ Return YouTube Subscribers See exact subscriber counts on YouTube again: on channel pages, under videos, and in search results. ``` -## Description (1274/10000) +## Description (1901/10000) ```text Since September 2019 YouTube has rounded every subscriber count: "1.2M subscribers" could mean anything from 1,200,000 to 1,299,999. Return YouTube Subscribers puts the full number back. @@ -25,6 +25,15 @@ WHAT IT DOES • Watch pages: the exact count appears under the channel name on every video • Search results: exact counts on channel results • Keeps working as you browse; no page reloads needed +• Sort channel search results by exact subscriber count +• Exact counts on featured channels and channel lists +• Live streams: the count refreshes every 10 seconds, with rolling digits +• Full-screen live counter, and race mode to watch two channels side by side +• Save a shareable image of any count or race +• On your own channel: next milestone, subscribers to go and a projected date +• Toolbar popup ranking the channels you've viewed by how fast they're growing +• Choose exact (452,318,906) or compact (452.3M) numbers +• Hover any count to see where it came from and when it was updated HOW IT WORKS YouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure. @@ -32,6 +41,7 @@ YouTube no longer publishes exact counts. The extension reads the ID of the chan PRIVACY • No account, no sign-in, nothing to configure • No analytics, ads or tracking inside the extension +• Growth history stays on your device • The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count • Open source on GitHub diff --git a/store/listings/firefox-amo.md b/store/listings/firefox-amo.md index 18e4f88..8342b5c 100644 --- a/store/listings/firefox-amo.md +++ b/store/listings/firefox-amo.md @@ -17,7 +17,7 @@ Return YouTube Subscribers See exact subscriber counts on YouTube again: on channel pages, under videos, and in search results. ``` -## Description (1274/15000) +## Description (1901/15000) ```text Since September 2019 YouTube has rounded every subscriber count: "1.2M subscribers" could mean anything from 1,200,000 to 1,299,999. Return YouTube Subscribers puts the full number back. @@ -27,6 +27,15 @@ WHAT IT DOES • Watch pages: the exact count appears under the channel name on every video • Search results: exact counts on channel results • Keeps working as you browse; no page reloads needed +• Sort channel search results by exact subscriber count +• Exact counts on featured channels and channel lists +• Live streams: the count refreshes every 10 seconds, with rolling digits +• Full-screen live counter, and race mode to watch two channels side by side +• Save a shareable image of any count or race +• On your own channel: next milestone, subscribers to go and a projected date +• Toolbar popup ranking the channels you've viewed by how fast they're growing +• Choose exact (452,318,906) or compact (452.3M) numbers +• Hover any count to see where it came from and when it was updated HOW IT WORKS YouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure. @@ -34,6 +43,7 @@ YouTube no longer publishes exact counts. The extension reads the ID of the chan PRIVACY • No account, no sign-in, nothing to configure • No analytics, ads or tracking inside the extension +• Growth history stays on your device • The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count • Open source on GitHub diff --git a/store/listings/opera-add-ons.md b/store/listings/opera-add-ons.md index da841e4..ab497f6 100644 --- a/store/listings/opera-add-ons.md +++ b/store/listings/opera-add-ons.md @@ -27,6 +27,15 @@ WHAT IT DOES • Watch pages: the exact count appears under the channel name on every video • Search results: exact counts on channel results • Keeps working as you browse; no page reloads needed +• Sort channel search results by exact subscriber count +• Exact counts on featured channels and channel lists +• Live streams: the count refreshes every 10 seconds, with rolling digits +• Full-screen live counter, and race mode to watch two channels side by side +• Save a shareable image of any count or race +• On your own channel: next milestone, subscribers to go and a projected date +• Toolbar popup ranking the channels you've viewed by how fast they're growing +• Choose exact (452,318,906) or compact (452.3M) numbers +• Hover any count to see where it came from and when it was updated HOW IT WORKS YouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure. @@ -34,6 +43,7 @@ YouTube no longer publishes exact counts. The extension reads the ID of the chan PRIVACY • No account, no sign-in, nothing to configure • No analytics, ads or tracking inside the extension +• Growth history stays on your device • The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count • Open source on GitHub diff --git a/store/listings/safari-app-store.md b/store/listings/safari-app-store.md index 81cd46b..9ba302d 100644 --- a/store/listings/safari-app-store.md +++ b/store/listings/safari-app-store.md @@ -23,7 +23,7 @@ Exact YouTube sub counts YouTube rounds every subscriber count. Return YouTube Subscribers puts the full number back on channel pages, watch pages and search results. ``` -## Description (1274/4000) +## Description (1901/4000) ```text Since September 2019 YouTube has rounded every subscriber count: "1.2M subscribers" could mean anything from 1,200,000 to 1,299,999. Return YouTube Subscribers puts the full number back. @@ -33,6 +33,15 @@ WHAT IT DOES • Watch pages: the exact count appears under the channel name on every video • Search results: exact counts on channel results • Keeps working as you browse; no page reloads needed +• Sort channel search results by exact subscriber count +• Exact counts on featured channels and channel lists +• Live streams: the count refreshes every 10 seconds, with rolling digits +• Full-screen live counter, and race mode to watch two channels side by side +• Save a shareable image of any count or race +• On your own channel: next milestone, subscribers to go and a projected date +• Toolbar popup ranking the channels you've viewed by how fast they're growing +• Choose exact (452,318,906) or compact (452.3M) numbers +• Hover any count to see where it came from and when it was updated HOW IT WORKS YouTube no longer publishes exact counts. The extension reads the ID of the channel you are viewing, asks the Mixerno.space API for its estimated count, and shows that in place of the rounded number. Counts are estimates and can differ slightly from YouTube's internal figure. @@ -40,6 +49,7 @@ YouTube no longer publishes exact counts. The extension reads the ID of the chan PRIVACY • No account, no sign-in, nothing to configure • No analytics, ads or tracking inside the extension +• Growth history stays on your device • The only data sent anywhere is the public ID of the channel you are viewing, to backend.mixerno.space, to look up its count • Open source on GitHub diff --git a/userscript.js b/userscript.js index 3c3f031..cbbb96d 100644 --- a/userscript.js +++ b/userscript.js @@ -13,228 +13,594 @@ // @run-at document-start // @grant none // ==/UserScript== -// Generated from src/main.js by scripts/build.mjs. Do not edit by hand. - -let currentURL = window.location.href; -const apiLink = "https://backend.mixerno.space/api/youtube/estv3/"; -const apiPath = "items[0].statistics.subscriberCount"; -const strType = "en-US"; -let lastFetchedSubscriberCount = null; - -const possibleSubCounters = [ - "#owner-sub-count", - "#page-header > yt-page-header-renderer > yt-page-header-view-model > div > div.ytPageHeaderViewModelHeadline > div > yt-content-metadata-view-model > div:nth-child(3) > span:nth-child(1)" -]; - -function getValueFromJson(json, path) { - const keys = path.replace(/\[(\d+)\]/g, '.$1').split('.'); // Converts [0] to .0 and splits on . - let result = json; - - for (let key of keys) { - if (result && result[key] !== undefined) { - result = result[key]; - } else { - return undefined; - } +// Generated from src/shared.js and src/main.js by scripts/build.mjs. Do not edit by hand. + +// Shared helpers for the content script, the toolbar popup and the counter page. +// Plain script (no modules) so it also works as part of the userscript. + +var RYTS = (() => { + const API = "https://backend.mixerno.space/api/youtube/estv3/"; + const SOURCE = "Mixerno.space"; + + // Extension storage when running as an extension, localStorage in the userscript. + const ext = globalThis.browser?.storage?.local ? globalThis.browser + : globalThis.chrome?.storage?.local ? globalThis.chrome : null; + + const store = { + async get(key, fallback) { + try { + if (ext) return (await ext.storage.local.get(key))[key] ?? fallback; + const raw = localStorage.getItem("ryts:" + key); + return raw ? JSON.parse(raw) : fallback; + } catch { + return fallback; + } + }, + async set(key, value) { + try { + if (ext) await ext.storage.local.set({ [key]: value }); + else localStorage.setItem("ryts:" + key, JSON.stringify(value)); + } catch { /* storage full or blocked: features degrade, counts still show */ } + }, + onChange(key, callback) { + ext?.storage?.onChanged?.addListener((changes, area) => { + if (area === "local" && changes[key]) callback(changes[key].newValue); + }); + }, + }; + + // ---------- settings ---------- + + const DEFAULT_SETTINGS = { format: "exact" }; + const getSettings = async () => ({ ...DEFAULT_SETTINGS, ...(await store.get("settings", {})) }); + const setSettings = async (patch) => store.set("settings", { ...(await getSettings()), ...patch }); + const onSettings = (callback) => store.onChange("settings", (s) => callback({ ...DEFAULT_SETTINGS, ...s })); + + // ---------- formatting ---------- + + const exactFormat = new Intl.NumberFormat("en-US"); + // One more significant figure than YouTube's three: 452.3M, 1.284M, 34.01K. + const compactFormat = new Intl.NumberFormat("en-US", { + notation: "compact", maximumSignificantDigits: 4, roundingMode: "trunc", + }); + const format = (n, mode = "exact") => (mode === "compact" && n >= 1000 ? compactFormat : exactFormat).format(n); + const exact = (n) => exactFormat.format(n); + const time = (t) => new Date(t).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }); + + // ---------- counts ---------- + + const cache = new Map(); // id -> { count, at, promise } + const CACHE_MS = 60_000; + + async function fetchCount(id, { fresh = false } = {}) { + const hit = cache.get(id); + if (hit?.promise) return hit.promise; + if (!fresh && hit && Date.now() - hit.at < CACHE_MS) return hit.count; + const promise = fetch(API + encodeURIComponent(id)) + .then((r) => (r.ok ? r.json() : null)) + .then((data) => { + const n = parseInt(data?.items?.[0]?.statistics?.subscriberCount, 10); + return Number.isFinite(n) ? n : null; + }) + .catch(() => null) + .then((count) => { + cache.set(id, count === null ? undefined : { count, at: Date.now() }); + if (count === null) cache.delete(id); + return count; + }); + cache.set(id, { ...hit, promise }); + return promise; } - return result; -} + const updatedAt = (id) => cache.get(id)?.at ?? Date.now(); -function check() { - let url = window.location.href; - if (url.includes("/results?search_query=")) { - setTimeout(function () { searchResults(); }, 1000); - } else { - const subscriberCount = document.querySelector(possibleSubCounters[1]); - const ownerSubCount = document.querySelector(possibleSubCounters[0]); + // ---------- history (local only; powers growth, projections and the popup) ---------- - if (subscriberCount) { - stats(); - } else if (ownerSubCount) { - stats2(); - } else { - setTimeout(check, 100); - } + const MAX_POINTS = 240; + const MIN_GAP_MS = 5 * 60_000; + let historyWrite = Promise.resolve(); + + function observe(id, count, meta = {}) { + historyWrite = historyWrite.then(async () => { + const history = await store.get("history", {}); + const entry = history[id] || { points: [] }; + if (meta.name) entry.name = meta.name; + if (meta.handle) entry.handle = meta.handle; + const now = Date.now(); + const last = entry.points[entry.points.length - 1]; + // Keep one point per five minutes; within that window just update the latest value. + if (last && now - last[0] < MIN_GAP_MS && entry.points.length > 1) entry.points[entry.points.length - 1] = [now, count]; + else entry.points.push([now, count]); + entry.points = entry.points.slice(-MAX_POINTS); + entry.seen = now; + history[id] = entry; + await store.set("history", history); + }); + return historyWrite; } -} - -async function fetchSubscriberData(channelId, targetSelectorIndex, element) { - try { - const response = await fetch(apiLink + channelId); - const data = await response.json(); - - if (data) { - - let subscriberText = getValueFromJson(data, apiPath); - console.log(subscriberText) - - if (element) { - element.textContent = parseInt(subscriberText).toLocaleString(strType) + " subscribers"; - } else { - const targetElement = document.querySelector(possibleSubCounters[targetSelectorIndex]); - - if (!targetElement) return; - if (subscriberText !== undefined && subscriberText !== null) { - if (targetElement.getAttribute("loaded") === "true") return; - - subscriberText = String(subscriberText).trim(); - const formattedCount = parseInt(subscriberText).toLocaleString(strType); - targetElement.textContent = formattedCount + " subscribers"; - targetElement.setAttribute("loaded", "true"); - targetElement.removeAttribute("is-empty"); - lastFetchedSubscriberCount = formattedCount; - - const ownerSubCount = document.querySelector("#owner-sub-count"); - if (ownerSubCount) { - ownerSubCount.__rytsExpectedText = formattedCount + " subscribers"; - ownerSubCount.textContent = ownerSubCount.__rytsExpectedText; - - if (!ownerSubCount.__rytsSubscriberObserver) { - ownerSubCount.__rytsSubscriberObserver = new MutationObserver(() => { - if (ownerSubCount.textContent !== ownerSubCount.__rytsExpectedText) { - ownerSubCount.textContent = ownerSubCount.__rytsExpectedText; - } - }); - ownerSubCount.__rytsSubscriberObserver.observe(ownerSubCount, { - characterData: true, - childList: true, - subtree: true - }); - } - } - - const updateAdditionalInfo = () => { - const additionalInfoElement = document.querySelector("#additional-info-container > table > tbody > tr:nth-child(6) > td:nth-child(2)"); - if (additionalInfoElement) { - additionalInfoElement.textContent = formattedCount + " subscribers"; - clearInterval(infoCheckInterval); - } - }; - - updateAdditionalInfo(); - - const infoCheckInterval = setInterval(updateAdditionalInfo, 500); - } + + const getHistory = () => store.get("history", {}); + + // Subscribers per day across the stored points; needs at least 30 minutes of data. + function growthPerDay(points = []) { + if (points.length < 2) return null; + const [t0, c0] = points[0]; + const [t1, c1] = points[points.length - 1]; + const days = (t1 - t0) / 86_400_000; + return days >= 1 / 48 ? (c1 - c0) / days : null; + } + + // Next "round" milestone two significant figures up: 34,010 -> 35,000; 452,318,906 -> 460,000,000. + function nextMilestone(n) { + const step = 10 ** Math.max(2, String(Math.floor(n)).length - 2); + return (Math.floor(n / step) + 1) * step; + } + + // ---------- digit roll ---------- + + // Renders `text` into `el` as rolling digits. Digits are drawn by CSS from data + // attributes, so the element's text stays clean; a visually hidden copy is what + // screen readers read and what gets copied. + const canRoll = () => typeof CSS !== "undefined" && CSS.supports("height", "1lh"); + + function roll(el, text, prevText = "", animate = false) { + const wrap = document.createElement("span"); + wrap.className = "ryts-roll"; + wrap.setAttribute("aria-hidden", "true"); + const chars = [...text]; + const offset = chars.length - [...prevText].length; // align digits from the right + const moves = []; + let run = null; // consecutive non-digits share one box, aligned like the digits + chars.forEach((ch, i) => { + if (!/\d/.test(ch)) { + if (!run) wrap.append(run = Object.assign(document.createElement("span"), { className: "ryts-t" })); + run.textContent += ch; + return; } - } else { - console.error("[RYTS] Error fetching subscriber data:", data); + run = null; + const to = +ch; + const before = [...prevText][i - offset]; + const from = animate && /\d/.test(before || "") ? +before : to; + const box = document.createElement("span"); + box.className = "ryts-d"; + const reel = document.createElement("span"); + reel.className = "ryts-reel"; + for (let d = 0; d < 10; d++) { + const face = document.createElement("span"); + face.dataset.d = d; + reel.append(face); + } + reel.style.transform = `translateY(calc(-1lh * ${from}))`; + box.append(reel); + wrap.append(box); + if (from !== to) moves.push([reel, to]); + }); + const sr = document.createElement("span"); + sr.className = "ryts-sr"; + sr.textContent = text; + el.replaceChildren(wrap, sr); + if (moves.length) { + wrap.getBoundingClientRect(); // commit start positions + requestAnimationFrame(() => moves.forEach(([reel, to]) => { reel.style.transform = `translateY(calc(-1lh * ${to}))`; })); } + } + + // ---------- extension pages ---------- + + const pageUrl = (page, params) => { + const getURL = (globalThis.browser || globalThis.chrome)?.runtime?.getURL; + if (!getURL || !ext) return null; // userscript: no extension pages + return getURL(page) + "?" + new URLSearchParams(params); + }; + + return { + API, SOURCE, store, getSettings, setSettings, onSettings, + format, exact, time, canRoll, roll, fetchCount, updatedAt, observe, getHistory, growthPerDay, nextMilestone, pageUrl, + }; +})(); + +// Return YouTube Subscribers content script. Needs shared.js loaded first. + +(() => { + const R = RYTS; + const SEL = { + owner: "#owner-sub-count", + header: "#page-header > yt-page-header-renderer > yt-page-header-view-model > div > div.ytPageHeaderViewModelHeadline > div > yt-content-metadata-view-model > div:nth-child(3) > span:nth-child(1)", + headerRoot: "#page-header", + about: "#additional-info-container > table > tbody > tr:nth-child(6) > td:nth-child(2)", + channelRenderer: "ytd-channel-renderer", + }; + const ROUNDED = /^\s*[\d.,]+\s*[KMB]?\s+subscribers?\s*$/i; + const CHANNEL_HREF = /\/(?:channel\/(UC[\w-]{22})|(@[^/?#]+))/; + const LIVE_REFRESH_MS = 10_000; + const log = (...a) => console.log("[RYTS]", ...a); + + let settings = { format: "exact" }; + let page = null; // { url, id, name, handle, count, live } + const states = new Map(); // element -> { id, count, rounded, at, roll, live, prevText } + + // ---------- styles (YouTube's own colour variables, so light/dark/ambient all match) ---------- + + const style = document.createElement("style"); + style.textContent = ` + .ryts-roll { white-space: pre; font-variant-numeric: tabular-nums; } + .ryts-d, .ryts-t { display: inline-block; vertical-align: top; height: 1lh; } + .ryts-d { overflow: hidden; } + .ryts-reel { display: block; transition: transform .8s cubic-bezier(.2, .8, .2, 1); } + .ryts-reel > span { display: block; height: 1lh; } + .ryts-reel > span::before { content: attr(data-d); } + .ryts-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .ryts-live::before { content: ""; display: inline-block; width: .5em; height: .5em; margin-right: .4em; border-radius: 50%; + background: #ff0033; vertical-align: .1em; animation: ryts-pulse 1.6s ease-in-out infinite; } + @keyframes ryts-pulse { 50% { opacity: .35; } } + .ryts-open { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin-left: 6px; + border-radius: 50%; vertical-align: middle; color: var(--yt-spec-text-secondary, #606060); text-decoration: none; } + .ryts-open:hover { background: var(--yt-spec-10-percent-layer, rgba(0, 0, 0, .1)); color: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-open svg { width: 16px; height: 16px; fill: currentColor; } + .ryts-chip { font: 500 14px/36px Roboto, Arial, sans-serif; height: 36px; padding: 0 16px; border: 0; border-radius: 18px; + cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; + color: var(--yt-spec-text-primary, #0f0f0f); background: var(--yt-spec-badge-chip-background, rgba(0, 0, 0, .05)); } + .ryts-chip:hover { background: var(--yt-spec-button-chip-background-hover, rgba(0, 0, 0, .1)); } + .ryts-chip[aria-pressed="true"] { color: var(--yt-spec-text-primary-inverse, #fff); background: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-chip:focus-visible, .ryts-open:focus-visible { outline: 2px solid var(--yt-spec-call-to-action, #065fd4); outline-offset: 2px; } + .ryts-bar { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; font: 400 12px/18px Roboto, Arial, sans-serif; + color: var(--yt-spec-text-secondary, #606060); } + .ryts-panel { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 32px; margin: 16px 0 8px; padding: 16px 20px; + border-radius: 12px; font: 400 14px/20px Roboto, Arial, sans-serif; color: var(--yt-spec-text-secondary, #606060); + background: var(--yt-spec-badge-chip-background, rgba(0, 0, 0, .05)); } + .ryts-panel b { display: block; font-size: 16px; line-height: 22px; font-weight: 500; color: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-panel strong { display: block; font-size: 20px; line-height: 28px; font-weight: 700; color: var(--yt-spec-text-primary, #0f0f0f); } + .ryts-panel .ryts-chip { margin-left: auto; } + .ryts-tip { position: fixed; z-index: 9999; max-width: 280px; padding: 8px 10px; border-radius: 4px; pointer-events: none; + font: 400 12px/16px Roboto, Arial, sans-serif; color: #fff; background: rgba(97, 97, 97, .95); } + @media (prefers-reduced-motion: reduce) { .ryts-reel { transition: none; } .ryts-live::before { animation: none; } } + `; + // Added in start(): at document-start (userscripts) may not exist yet. + + // Tiny DOM builder: h("div", { className: "x" }, child, "text", ...) + const h = (tag, props = {}, ...children) => { + const el = Object.assign(document.createElement(tag), props); + el.append(...children.filter((c) => c != null)); + return el; + }; + + // ---------- rendering ---------- + + const label = (s) => R.format(s.count, settings.format) + " subscribers"; + const tooltip = (s) => + `Estimated by ${R.SOURCE}, updated ${R.time(s.at)}.` + + (s.rounded ? ` YouTube shows ${s.rounded.trim()}.` : "") + + (s.live ? " Live: refreshes every 10 seconds." : ""); - } catch (error) { - console.error("[RYTS] Error fetching subscriber data:", error); + function paint(el, s, animate = false) { + const text = label(s); + el.dataset.rytsTip = tooltip(s); + el.setAttribute("aria-description", el.dataset.rytsTip); + el.classList.toggle("ryts-live", !!s.live); + el.dataset.rytsValue = text; + el.removeAttribute("is-empty"); + if (s.roll && R.canRoll()) R.roll(el, text, s.prevText, animate); + else if (el.textContent !== text) el.textContent = text; + s.prevText = text; } -} -function stats() { - const req = new XMLHttpRequest(); - req.open("GET", currentURL, false); - req.send(null); + function intact(el, s) { + if (el.dataset.rytsValue !== label(s)) return false; + return s.roll && R.canRoll() ? !!el.querySelector(":scope > .ryts-roll") : el.textContent === label(s); + } - if (req.status === 200) { - const res = req.responseText; - const channelId = extractChannelId(res); - if (channelId) { - fetchSubscriberData(channelId, 1); + // Shows a count in `el` and keeps it there when YouTube re-renders the element. + function show(el, s) { + const old = states.get(el); + const state = { rounded: old?.rounded ?? el.textContent, prevText: old?.prevText, ...s, at: R.updatedAt(s.id) }; + states.set(el, state); + paint(el, state, !!old && old.count !== state.count); + if (!el.__rytsObserver) { + el.__rytsObserver = new MutationObserver(() => { + const st = states.get(el); + if (st && !intact(el, st)) paint(el, st); + }); + el.__rytsObserver.observe(el, { childList: true, characterData: true, subtree: true }); } + return state; + } + + function forget(el) { + el.__rytsObserver?.disconnect(); + delete el.__rytsObserver; + states.delete(el); } -} -function stats2() { - const req = new XMLHttpRequest(); - req.open("GET", currentURL, false); - req.send(null); + // One tooltip, styled like YouTube's, explaining where a count comes from. + const tip = h("div", { className: "ryts-tip", hidden: true }); + tip.setAttribute("role", "tooltip"); + document.addEventListener("mouseover", (e) => { + const el = e.target instanceof Element && e.target.closest("[data-ryts-tip]"); + if (!el) return void (tip.hidden = true); + if (!tip.isConnected) document.documentElement.append(tip); + tip.textContent = el.dataset.rytsTip; + tip.hidden = false; + const box = el.getBoundingClientRect(); + tip.style.left = Math.max(8, Math.min(box.left, innerWidth - tip.offsetWidth - 8)) + "px"; + tip.style.top = (box.bottom + 8 + tip.offsetHeight > innerHeight ? box.top - tip.offsetHeight - 8 : box.bottom + 8) + "px"; + }, { passive: true }); - if (req.status === 200) { - const res = req.responseText; - const channelId = extractChannelId(res); - if (channelId) { - fetchSubscriberData(channelId, 0); + // ---------- channel IDs ---------- + + const idByUrl = new Map(); + + function extractChannelId(html) { + const external = html.match(/"externalId":"(.*?)"/)?.[1]; + const browse = html.match(/"browse_id":"(.*?)"/)?.[1]; + const channel = html.match(/"channelId":"(.*?)"/)?.[1]; + return external || browse || channel || null; + } + + function idForUrl(url) { + if (!idByUrl.has(url)) { + idByUrl.set(url, fetch(url, { credentials: "include" }) + .then((r) => r.text()) + .then(extractChannelId) + .catch(() => null)); } + return idByUrl.get(url); + } + + async function idForHref(href) { + const m = href?.match(CHANNEL_HREF); + if (!m) return null; + if (m[1]) return m[1]; + return idForUrl("https://www.youtube.com/" + m[2]); } -} -function extractChannelId(responseText) { - const browseIdMatch = responseText.match(/"browse_id":"(.*?)"/); - const channelIdMatch = responseText.match(/"channelId":"(.*?)"/); - const externalIdMatch = responseText.match(/"externalId":"(.*?)"/); + // At most four lookups at a time for lists (search results, featured channels). + let active = 0; + const waiting = []; + function limited(task) { + return new Promise((resolve) => { + const run = async () => { + active++; + try { resolve(await task()); } catch { resolve(null); } finally { + active--; + waiting.shift()?.(); + } + }; + active < 4 ? run() : waiting.push(run); + }); + } - console.log("[RYTS] Browse ID:", browseIdMatch?.[1]); - console.log("[RYTS] Channel ID:", channelIdMatch?.[1]); - console.log("[RYTS] External ID:", externalIdMatch?.[1]); + // ---------- channel and watch pages ---------- - return externalIdMatch?.[1] || browseIdMatch?.[1] || channelIdMatch?.[1] || null; -} + const waitFor = (find, ms = 15000) => new Promise((resolve) => { + const start = Date.now(); + const tick = () => { + const el = find(); + if (el || Date.now() - start > ms) resolve(el || null); + else setTimeout(tick, 150); + }; + tick(); + }); -function clearLoadedState() { - for (let selector of possibleSubCounters) { - const element = document.querySelector(selector); - if (element) { - element.removeAttribute("loaded"); - console.log("[RYTS] Cleared loaded state for selector:", selector); + function pageMeta(isChannel) { + if (isChannel) { + const name = document.querySelector(`${SEL.headerRoot} h1`)?.textContent.trim(); + return { name, handle: location.pathname.match(/@[^/]+/)?.[0] }; } + const link = document.querySelector("#owner #channel-name a, ytd-video-owner-renderer #channel-name a"); + return { name: link?.textContent.trim(), handle: decodeURIComponent(link?.getAttribute("href")?.match(/@[^/?#]+/)?.[0] || "") || undefined }; } -} - -setInterval(() => { - const url = window.location.href; - if (currentURL !== url) { - currentURL = url; - console.log("[RYTS] URL changed:", url); - clearLoadedState(); - if (url.includes("/results?search_query=")) { - setTimeout(searchResults, 1000); - } else if (/\/channel\/|\/c\/|\/user\/|\/watch\?v=|\/@/.test(url)) { - const subscriberCount = document.querySelector(possibleSubCounters[1]); - const isWatchPage = url.includes("/watch?v="); - - console.log("[RYTS]", isWatchPage ? "Watch page" : "Channel page"); - if (isWatchPage) { - stats2(); - } else { - const updateStats = () => { - if (subscriberCount && subscriberCount.getAttribute("is-empty") === null) { - stats(); - } else { - setTimeout(updateStats, 500); - } - }; - updateStats(); - } + + async function handlePage() { + const url = location.href; + stopLive(); + for (const el of [...states.keys()]) if (!el.closest(SEL.channelRenderer)) forget(el); + document.querySelectorAll(".ryts-panel, .ryts-open").forEach((n) => n.remove()); + page = null; + if (!/\/(channel\/|c\/|user\/|watch\?|@)/.test(url)) return; + + const target = await waitFor(() => document.querySelector(SEL.header) || document.querySelector(SEL.owner)); + if (!target || url !== location.href) return; + const isChannel = target.matches(SEL.header); + const id = await idForUrl(url); + if (!id || url !== location.href) return; + const count = await R.fetchCount(id); + if (count === null || url !== location.href) return; + + page = { url, id, count, isChannel, ...pageMeta(isChannel) }; + log(isChannel ? "Channel page" : "Watch page", id, count); + R.observe(id, count, page); + show(target, { id, count, roll: true }); + if (isChannel) { + addCounterLink(target); // inline in the header's stats row; watch pages have no inline spot + ownChannelPanel(); + } else startLiveIfLive(target); + decorate(); + } + + function addCounterLink(el) { + const href = page && R.pageUrl("counter.html", { c: page.id, n: page.name || page.handle || "" }); + if (!href || el.nextElementSibling?.classList.contains("ryts-open")) return; + const a = document.createElement("a"); + a.className = "ryts-open"; + a.href = href; + a.target = "_blank"; + a.title = "Open the live counter"; + a.setAttribute("aria-label", "Open the live counter"); + const NS = "http://www.w3.org/2000/svg"; + const svg = document.createElementNS(NS, "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); + svg.setAttribute("aria-hidden", "true"); + const path = document.createElementNS(NS, "path"); + path.setAttribute("d", "M5 5h6v2H7v4H5V5zm8 0h6v6h-2V7h-4V5zM5 13h2v4h4v2H5v-6zm12 0h2v6h-6v-2h4v-4z"); + svg.append(path); + a.append(svg); + el.after(a); + } + + // ---------- live streams: refresh the count while the stream is on ---------- + + let liveTimer = null; + const isLive = () => + !!document.querySelector("#movie_player.ytp-live, .html5-video-player.ytp-live") || + (!!document.querySelector('meta[itemprop="isLiveBroadcast"][content="True"]') && !document.querySelector('meta[itemprop="endDate"]')); + + function startLiveIfLive(el) { + if (!isLive()) return; + const url = location.href; + const s = states.get(el); + s.live = true; + paint(el, s); + liveTimer = setInterval(async () => { + if (location.href !== url || !page) return stopLive(); + const count = await R.fetchCount(page.id, { fresh: true }); + if (count === null || location.href !== url) return; + page.count = count; + R.observe(page.id, count, page); + show(el, { id: page.id, count, roll: true, live: true }); + }, LIVE_REFRESH_MS); + } + + function stopLive() { + clearInterval(liveTimer); + liveTimer = null; + } + + // ---------- your own channel: milestone panel ---------- + + async function ownChannelPanel() { + const root = document.querySelector(SEL.headerRoot); + if (!page?.isChannel || !root || !root.querySelector('a[href*="studio.youtube.com"]')) return; + const history = (await R.getHistory())[page.id]; + const perDay = R.growthPerDay(history?.points); + const goal = R.nextMilestone(page.count); + const togo = goal - page.count; + const eta = perDay > 0 ? new Date(Date.now() + (togo / perDay) * 86_400_000) : null; + if (!page?.isChannel || document.querySelector(".ryts-panel")) return; + + const panel = document.createElement("section"); + panel.className = "ryts-panel"; + panel.setAttribute("aria-label", "Your channel"); + const cell = (big, small) => h("div", {}, h("strong", { textContent: big }), small); + panel.append(h("div", {}, h("b", { textContent: "Your channel" }), `Next milestone: ${R.exact(goal)}`), cell(R.exact(togo), "to go")); + if (perDay !== null) { + panel.append( + cell(`${perDay >= 0 ? "+" : "−"}${R.exact(Math.round(Math.abs(perDay)))}`, "per day, recently"), + cell(eta ? eta.toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" }) : "Not growing", "projected milestone date"), + ); + } else { + panel.append(h("div", { textContent: "Growth and a projected date appear after you've visited a few times." })); + } + const href = R.pageUrl("counter.html", { c: page.id, n: page.name || "" }); + if (href) { + const open = document.createElement("a"); + Object.assign(open, { className: "ryts-chip", href, target: "_blank", textContent: "Open live counter" }); + panel.append(open); } + root.after(panel); } -}, 500); -async function searchResults() { - console.log('[RYTS] Search Page') - try { - let channelRenderers = document.querySelectorAll("ytd-channel-renderer"); - for (const channelRenderer of channelRenderers) { - try { - let link = channelRenderer.querySelector("#main-link").href; - console.log(link) - if (link) { - if (link.includes("@")) { - fetch("https://www.youtube.com/@" + link.split("@")[1]) - .then((response) => response.text()) - .then(async (data) => { - if (data && data.includes('externalId')) { - let channelId = data.split('"externalId":"')[1].split('"')[0]; - fetchSubscriberData(channelId, 0, channelRenderer.querySelector("#video-count")); - } - }); - } else { - - } - } - } catch (error) { - console.error("[RYTS] Error fetching search results:", error); + // ---------- lists: search results, featured channels, About dialog ---------- + + function decorate() { + // Search results (existing behaviour: the count lives in #video-count). + if (location.href.includes("/results?")) { + for (const renderer of document.querySelectorAll(SEL.channelRenderer)) { + const target = renderer.querySelector("#video-count"); + const href = renderer.querySelector("#main-link")?.href; + if (!target || !href || renderer.__ryts) continue; + renderer.__ryts = limited(async () => { + const id = await idForHref(href); + const count = id && await R.fetchCount(id); + if (count == null) return null; + R.observe(id, count, { name: renderer.querySelector("#channel-title #text, #text")?.textContent.trim(), handle: href.match(/@[^/?#]+/)?.[0] }); + show(target, { id, count }); + renderer.dataset.rytsCount = count; + return count; + }); } + sortButton(); + } + + // Featured channels and channel lists: any "123K subscribers" text near a channel link. + const walker = document.createTreeWalker(document.querySelector("ytd-page-manager") || document.body, NodeFilter.SHOW_TEXT, { + acceptNode: (n) => (ROUNDED.test(n.data) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP), + }); + const found = []; + while (walker.nextNode()) found.push(walker.currentNode.parentElement); + for (const el of found) { + if (!el || el.__ryts || states.has(el) || el.matches(SEL.owner) || el.closest(`${SEL.channelRenderer}, ${SEL.headerRoot}, #owner`)) continue; + const card = el.closest("ytd-grid-channel-renderer, ytd-mini-channel-renderer, ytd-channel-renderer, yt-lockup-view-model, ytd-rich-item-renderer") + || el.parentElement?.closest(":has(a[href*='/@'], a[href*='/channel/UC'])"); + const href = card?.querySelector("a[href*='/@'], a[href*='/channel/UC']")?.getAttribute("href"); + if (!href) continue; + el.__ryts = limited(async () => { + const id = await idForHref(href); + const count = id && await R.fetchCount(id); + if (count == null) return; + show(el, { id, count }); + }); } - } catch (error) { - console.error("[RYTS] Error fetching search results:", error); - setTimeout(searchResults, 1000); + + // The About dialog's table row. + const about = page?.isChannel && document.querySelector(SEL.about); + if (about && !states.has(about)) show(about, { id: page.id, count: page.count }); + } + + function sortButton() { + const renderers = [...document.querySelectorAll(SEL.channelRenderer)]; + if (renderers.length < 2 || document.querySelector(".ryts-bar")) return; + const bar = document.createElement("div"); + bar.className = "ryts-bar"; + const button = h("button", { type: "button", className: "ryts-chip", textContent: "Sort channels by subscribers" }); + button.setAttribute("aria-pressed", "false"); + bar.append(button, h("span", { textContent: "Exact counts by Return YouTube Subscribers" })); + renderers[0].before(bar); + button.addEventListener("click", async () => { + button.textContent = "Sorting…"; + const list = [...document.querySelectorAll(SEL.channelRenderer)]; + await Promise.all(list.map((r) => r.__ryts)); + const marker = document.createComment("ryts"); + bar.after(marker); + list.sort((a, b) => (+b.dataset.rytsCount || 0) - (+a.dataset.rytsCount || 0)) + .forEach((r) => marker.before(r)); + marker.remove(); + button.textContent = "Sorted by subscribers"; + button.setAttribute("aria-pressed", "true"); + }); } -} -check(); + // ---------- wiring ---------- + + let scheduled = null; + const pageObserver = new MutationObserver(() => { + if (scheduled) return; + scheduled = setTimeout(() => { + scheduled = null; + decorate(); + }, 400); + }); + + let lastUrl = null; + const onNavigate = () => { + if (location.href === lastUrl) return; + lastUrl = location.href; + log("URL changed:", lastUrl); + handlePage(); + decorate(); + }; + document.addEventListener("yt-navigate-finish", onNavigate); + setInterval(() => document.body && onNavigate(), 1000); // fallback if YouTube renames its navigation event + + R.getSettings().then((s) => { settings = s; }); + R.onSettings((s) => { + settings = s; + for (const [el, st] of states) paint(el, st); + }); + + const start = () => { + (document.head || document.documentElement).append(style); + pageObserver.observe(document.documentElement, { childList: true, subtree: true }); + onNavigate(); + }; + document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", start, { once: true }) : start(); +})();