From 8bbce6b3bf13af93789d82fa2eb6fef245fa24fa Mon Sep 17 00:00:00 2001 From: Paul Tarbouriech Date: Tue, 1 Dec 2026 19:16:22 +0100 Subject: [PATCH] Add browser extensions from the bluesky prototypes. Import the four Chrome extension packages under extensions/ for Bluesky, X, and Facebook experiments. Co-authored-by: Cursor --- extensions/chrome-extension-fb-why/content.js | 733 ++++++++++++++++++ extensions/chrome-extension-fb-why/inject.js | 261 +++++++ .../chrome-extension-fb-why/manifest.json | 36 + extensions/chrome-extension-fb-why/styles.css | 82 ++ .../chrome-extension-x-filter/content.js | 219 ++++++ .../chrome-extension-x-filter/inject.js | 566 ++++++++++++++ .../chrome-extension-x-filter/manifest.json | 21 + .../chrome-extension-x-filter/styles.css | 80 ++ extensions/chrome-extension-x/content.js | 311 ++++++++ extensions/chrome-extension-x/inject.js | 167 ++++ extensions/chrome-extension-x/manifest.json | 21 + extensions/chrome-extension-x/styles.css | 49 ++ extensions/chrome-extension/content.js | 546 +++++++++++++ extensions/chrome-extension/inject.js | 55 ++ extensions/chrome-extension/manifest.json | 27 + extensions/chrome-extension/styles.css | 49 ++ 16 files changed, 3223 insertions(+) create mode 100644 extensions/chrome-extension-fb-why/content.js create mode 100644 extensions/chrome-extension-fb-why/inject.js create mode 100644 extensions/chrome-extension-fb-why/manifest.json create mode 100644 extensions/chrome-extension-fb-why/styles.css create mode 100644 extensions/chrome-extension-x-filter/content.js create mode 100644 extensions/chrome-extension-x-filter/inject.js create mode 100644 extensions/chrome-extension-x-filter/manifest.json create mode 100644 extensions/chrome-extension-x-filter/styles.css create mode 100644 extensions/chrome-extension-x/content.js create mode 100644 extensions/chrome-extension-x/inject.js create mode 100644 extensions/chrome-extension-x/manifest.json create mode 100644 extensions/chrome-extension-x/styles.css create mode 100644 extensions/chrome-extension/content.js create mode 100644 extensions/chrome-extension/inject.js create mode 100644 extensions/chrome-extension/manifest.json create mode 100644 extensions/chrome-extension/styles.css diff --git a/extensions/chrome-extension-fb-why/content.js b/extensions/chrome-extension-fb-why/content.js new file mode 100644 index 0000000..8ff3c25 --- /dev/null +++ b/extensions/chrome-extension-fb-why/content.js @@ -0,0 +1,733 @@ +/** + * UI click: find post ⋯ menus → Pourquoi je vois… for top visible units. + */ + +const SOURCE = "fb-why-top10"; +const TARGET_OK = 5; +const MAX_ATTEMPTS = 14; +const MAX_SCROLL_ROUNDS = 12; + +const WHY_RE = + /pourquoi (je vois|vous voyez) cette (publication|publicit[ée])|why am i seeing this( (post|ad))?/i; +const WHY_DIALOG_RE = + /pourquoi (je vois|vous voyez)|why am i seeing|vous suivez|you follow|est populaire|is popular|publicit|advertiser|sponsored|suggestion|int[ée]ress/i; +const MORE_RE = /plus d['’]options|more options|voir plus|see more options/i; +const MENU_BTN_RE = + /actions (pour|for) (cette|this) (publication|post)|actions pour cette publicit|actions for this (post|ad)|ouvrir le menu|open (the )?menu|more about this|en savoir plus/i; + +/** @type {Map} */ +const results = new Map(); +/** @type {{ key: string, label: string, isAd: boolean }[]} */ +let items = []; +let statusMsg = "Click Fetch whys (UI)."; +let running = false; +let panel = null; +let lastError = ""; + +window.addEventListener("message", (event) => { + if (event.source !== window) return; + const data = event.data; + if (!data || data.source !== SOURCE) return; + if (data.type === "why" && data.key) { + results.set(data.key, data.why); + render(); + } + if (data.type === "state" && data.whys) { + for (const [k, v] of Object.entries(data.whys)) results.set(k, v); + render(); + } +}); + +function sleep(ms) { + return new Promise((r) => setTimeout(r, ms)); +} + +function visible(el) { + if (!el || !(el instanceof Element)) return false; + const r = el.getBoundingClientRect(); + if (r.width < 2 || r.height < 2) return false; + if (r.bottom < -40 || r.top > window.innerHeight + 40) return false; + const st = getComputedStyle(el); + return st.visibility !== "hidden" && st.display !== "none"; +} + +function textOf(el) { + return (el?.innerText || el?.textContent || "").replace(/\s+/g, " ").trim(); +} + +/** Climb to a reasonable post card containing the ⋯ button. */ +function postRootFromMenu(btn) { + let el = btn; + for (let i = 0; i < 25 && el; i++) { + if (el.getAttribute?.("role") === "article") return el; + el = el.parentElement; + } + // Size-based climb + el = btn.parentElement; + for (let i = 0; i < 20 && el; i++) { + const r = el.getBoundingClientRect(); + if (r.height > 160 && r.width > 300) return el; + el = el.parentElement; + } + return btn.parentElement; +} + +/** + * Discover posts via their ⋯ / Actions buttons (more reliable than role=article). + * @returns {{ root: Element, menuBtn: Element }[]} + */ +function findPostTargets() { + const buttons = [ + ...document.querySelectorAll("[aria-label]"), + ...document.querySelectorAll('[role="button"]'), + ]; + const seen = new Set(); + const out = []; + + for (const b of buttons) { + if (!visible(b)) continue; + const label = (b.getAttribute("aria-label") || "").trim(); + if (!label || !MENU_BTN_RE.test(label)) continue; + + const root = postRootFromMenu(b); + if (!root || seen.has(root)) continue; + // Avoid tiny comment menus + const r = root.getBoundingClientRect(); + if (r.height < 80) continue; + + seen.add(root); + out.push({ root, menuBtn: b, menuLabel: label }); + } + + out.sort( + (a, b) => + a.root.getBoundingClientRect().top - b.root.getBoundingClientRect().top, + ); + return out; +} + +function debugCounts() { + const targets = findPostTargets(); + const articles = document.querySelectorAll('[role="article"]').length; + const actionLabels = [...document.querySelectorAll("[aria-label]")] + .map((el) => el.getAttribute("aria-label") || "") + .filter((l) => /action|menu|option|publication|post/i.test(l)) + .slice(0, 8); + return { + matched: targets.length, + articles, + sampleLabels: actionLabels, + }; +} + +function isAdRoot(root) { + const t = textOf(root).slice(0, 500); + return /sponsored|publicit[ée]|sponsorisé/i.test(t); +} + +/** Short post label — avoid “Facebook Facebook Facebook…” chrome dumps. */ +function postLabel(root, fallback) { + const lines = textOf(root) + .split("\n") + .map((s) => s.trim()) + .filter(Boolean); + for (const line of lines.slice(0, 12)) { + if (line.length < 3 || line.length > 90) continue; + if (/^(facebook|j['’]aime|like|comment|partag|share|·)/i.test(line)) { + continue; + } + if (/^(il y a |ago$|\d+\s*(min|h|d|j)\b)/i.test(line)) continue; + return line; + } + return (fallback || "Post").slice(0, 80); +} + +function menuRoots() { + return [ + ...document.querySelectorAll('[role="menu"]'), + ...document.querySelectorAll('[role="dialog"]'), + ...document.querySelectorAll('[role="listbox"]'), + ].filter(visible); +} + +function findInMenus(regex) { + const pools = [ + ...menuRoots(), + document.body, + ]; + for (const root of pools) { + if (!root) continue; + const candidates = [ + ...root.querySelectorAll('[role="menuitem"]'), + ...root.querySelectorAll('[role="menuitemradio"]'), + ...root.querySelectorAll('[role="button"]'), + ...root.querySelectorAll("span, div, a"), + ]; + for (const el of candidates) { + if (!visible(el)) continue; + const t = (el.getAttribute("aria-label") || textOf(el) || "").trim(); + if (t && regex.test(t) && t.length < 140) return el; + } + } + return null; +} + +function clickEl(el) { + if (!el) return false; + try { + el.scrollIntoView({ block: "center", inline: "nearest" }); + } catch { + /* ignore */ + } + const opts = { bubbles: true, cancelable: true, view: window, buttons: 1 }; + el.dispatchEvent(new PointerEvent("pointerover", opts)); + el.dispatchEvent(new PointerEvent("pointerenter", opts)); + el.dispatchEvent(new MouseEvent("mouseover", opts)); + el.dispatchEvent(new PointerEvent("pointerdown", opts)); + el.dispatchEvent(new MouseEvent("mousedown", opts)); + el.dispatchEvent(new PointerEvent("pointerup", opts)); + el.dispatchEvent(new MouseEvent("mouseup", opts)); + el.dispatchEvent(new MouseEvent("click", opts)); + if (typeof el.click === "function") el.click(); + return true; +} + +async function pressEscape() { + for (const target of [document, document.body, document.documentElement]) { + target.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + code: "Escape", + keyCode: 27, + which: 27, + bubbles: true, + }), + ); + } + await sleep(250); +} + +async function waitFor(fn, timeoutMs, stepMs = 120) { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + const v = fn(); + if (v) return v; + await sleep(stepMs); + } + return null; +} + +function whyHasContent(w) { + return !!( + w && + (w.generic || w.personalized || w.advertiser || w.targeting?.length) + ); +} + +/** Clear junk from a scraped page dump (not from a real why card). */ +const CHROME_RE = + /marketplace|meta ai|historique des discussions|confidentialité\s*·|conditions générales|candy crush|vos raccourcis|souvenirs|\breels\b|signaler la publication|ça m['’]intéresse|chiffrement de bout en bout|entrez votre code pin/i; + +/** + * Slice a blob down to the why-panel section, then regex out reasons. + * Works even when the DOM root is a full-screen dialog wrapper. + */ +function extractWhyFromText(raw) { + if (!raw || raw.length < 40) return null; + if (!/pourquoi (je vois|vous voyez)|why am i seeing/i.test(raw)) return null; + + const titleIdx = raw.search( + /pourquoi (je vois|vous voyez) cette (publication|publicit[ée])|why am i seeing this( (post|ad))?/i, + ); + let slice = titleIdx >= 0 ? raw.slice(titleIdx, titleIdx + 1800) : raw.slice(0, 1800); + slice = slice.split( + /Préférences de contenu|Content [Pp]references|Voir le Centre de confidentialité|See Privacy Center|Centre de confidentialité/i, + )[0]; + + // Still looks like the whole app shell → bail (don't dump chrome) + if (CHROME_RE.test(slice)) return null; + + const reasonBits = []; + const push = (s) => { + const v = (s || "").replace(/\s+/g, " ").trim(); + if (v.length < 10 || v.length > 320) return; + if (reasonBits.some((p) => p.includes(v) || v.includes(p))) return; + reasonBits.push(v); + }; + + const friends = slice.match( + /Vous [êe]tes ami(?:\(e\))?s? avec .+?(?=Votre ami|Il existe|Cette publication|You are friends|Préférences|$)/i, + ); + const friendsEn = slice.match( + /You are friends with .+?(?=Friends since|Your friend|There are|This post|Content |$)/i, + ); + const friendSince = slice.match( + /Votre ami\(e\) depuis [^·]{4,40}|Friends since [^·]{4,40}|Your friend since [^·]{4,40}/i, + ); + const follow = slice.match( + /Vous suivez .+?(?=Suivi\(e\)|Cette publication|Il existe|You follow|This post|Préférences|$)/i, + ); + const followEn = slice.match( + /You follow .+?(?=Following since|This post|There are|Content |$)/i, + ); + const since = slice.match(/Suivi\(e\) depuis [^·]{4,40}|Following since [^·]{4,40}/i); + const popular = slice.match( + /(?:Cette publication .+?est populaire .+?(?=Il existe|Préférences|En savoir|$)|[^\n]{0,40}est populaire par rapport[^\n]{0,100})/i, + ); + const popularEn = slice.match( + /(?:This post .+?is popular .+?(?=There are|Content |Learn more|$)|[^\n]{0,40}is popular compared[^\n]{0,100})/i, + ); + const interest = slice.match( + /(?:parce que|because).{0,40}(?:int[ée]ress|interest).{0,80}?(?=Il existe|There are|Préférences|$)/i, + ); + + if (friends) push(friends[0]); + if (friendsEn) push(friendsEn[0]); + if (friendSince) push(friendSince[0]); + if (follow) push(follow[0]); + if (followEn) push(followEn[0]); + if (since) push(since[0]); + if (popular) push(popular[0]); + if (popularEn) push(popularEn[0]); + if (interest) push(interest[0]); + + // Ad-ish lines inside a real why panel + const age = slice.match(/âge[^·]{0,40}|age[^·]{0,40}\d{1,2}/i); + const loc = slice.match(/localisation[^·]{0,60}|location[^·]{0,60}/i); + if (age && /publicit|advert/i.test(slice.slice(0, 80))) push(age[0]); + if (loc && /publicit|advert/i.test(slice.slice(0, 80))) push(loc[0]); + + const disc = slice.match( + /Il existe plusieurs facteurs.+?(?=En savoir plus|Préférences|$)|There are several factors.+?(?=Learn more|Content |$)/i, + ); + const disclaimer = disc ? disc[0].replace(/\s+/g, " ").trim().slice(0, 500) : null; + + if (!reasonBits.length && !disclaimer) return null; + + const titleHead = slice.slice(0, 80); + const isAd = /publicit|advertisement|seeing this ad/i.test(titleHead); + let advertiser = null; + if (isAd) { + const m = slice.match( + /(?:sponsorisé par|sponsored by)\s*[:\-]?\s*([^·\n]{2,50})/i, + ); + advertiser = m?.[1]?.trim() || null; + } + + return { + kind: isAd ? "ad" : "post", + generic: reasonBits.length ? reasonBits.join(" · ") : disclaimer, + personalized: disclaimer, + advertiser, + targeting: reasonBits, + at: Date.now(), + source: "dom", + }; +} + +/** Collect text blobs that might contain the open why panel. */ +function whyTextCandidates() { + const blobs = []; + const seen = new Set(); + + const add = (el) => { + if (!el || !visible(el) || seen.has(el)) return; + const t = textOf(el); + if (t.length < 40) return; + if (!/pourquoi (je vois|vous voyez)|why am i seeing/i.test(t)) return; + seen.add(el); + blobs.push({ el, t, len: t.length }); + }; + + for (const el of document.querySelectorAll( + '[role="dialog"], [role="complementary"], [aria-modal="true"]', + )) { + add(el); + } + + // Title node → parent chain (card often sits under a full-screen dialog) + for (const el of document.querySelectorAll( + "h1, h2, h3, span, div, [role='heading'], [aria-label]", + )) { + if (!visible(el)) continue; + const label = el.getAttribute("aria-label") || ""; + const own = textOf(el); + const hit = + (own.length > 0 && + own.length < 120 && + /pourquoi (je vois|vous voyez)|why am i seeing/i.test(own)) || + WHY_RE.test(label); + if (!hit) continue; + let cur = el; + for (let i = 0; i < 16 && cur; i++) { + add(cur); + cur = cur.parentElement; + } + } + + // Prefer shorter blobs (tighter cards) first + blobs.sort((a, b) => a.len - b.len); + return blobs; +} + +function scrapeWhyDialog() { + const blobs = whyTextCandidates(); + + // Same-origin iframes (rare, but FB layers sometimes nest) + for (const iframe of document.querySelectorAll("iframe")) { + try { + const doc = iframe.contentDocument; + if (!doc?.body) continue; + const t = textOf(doc.body); + if (/pourquoi (je vois|vous voyez)|why am i seeing/i.test(t)) { + blobs.push({ el: doc.body, t, len: t.length }); + } + } catch { + /* cross-origin */ + } + } + + blobs.sort((a, b) => a.len - b.len); + + if (!blobs.length) { + console.info("[fb-why] scrape: no why title in DOM yet"); + return null; + } + + for (const { t, len } of blobs) { + const extracted = extractWhyFromText(t); + if (extracted) { + console.info("[fb-why] scrape ok", "blobLen=", len, extracted.generic?.slice(0, 80)); + return extracted; + } + } + + console.info( + "[fb-why] scrape: title found but no reasons", + blobs.slice(0, 3).map((b) => b.t.slice(0, 120)), + ); + return null; +} + +function readGraphqlWhy(key, since) { + const w = results.get(key); + if (whyHasContent(w) && (w.at || 0) >= since - 100 && w.source !== "dom") { + return w; + } + for (const [k, v] of results.entries()) { + if ( + (k.startsWith("waist-") || k === key) && + (v.at || 0) >= since - 100 && + whyHasContent(v) && + v.source !== "dom" + ) { + return { ...v, storyKey: key }; + } + } + return null; +} + +function mergeWhy(graphql, scraped) { + if (graphql && scraped) { + return { + kind: graphql.kind || scraped.kind, + generic: graphql.generic || scraped.generic, + personalized: graphql.personalized || scraped.personalized, + advertiser: graphql.advertiser || scraped.advertiser, + targeting: [ + ...(graphql.targeting || []), + ...(scraped.targeting || []).filter( + (t) => !(graphql.targeting || []).includes(t), + ), + ], + at: Date.now(), + source: "graphql+dom", + storyKey: graphql.storyKey || scraped.storyKey, + }; + } + return graphql || scraped || null; +} + +async function openWhyForTarget(target, key) { + const before = Date.now(); + window.postMessage({ source: SOURCE, type: "set-pending", key }, "*"); + await sleep(80); + + clickEl(target.menuBtn); + await sleep(700); + + window.postMessage( + { source: SOURCE, type: "claim-recent", key, since: before - 50 }, + "*", + ); + + let whyItem = findInMenus(WHY_RE); + if (!whyItem) { + const more = findInMenus(MORE_RE); + if (more) { + clickEl(more); + await sleep(700); + whyItem = findInMenus(WHY_RE); + } + } + if (!whyItem) whyItem = await waitFor(() => findInMenus(WHY_RE), 2500); + + if (!whyItem) { + await pressEscape(); + return { ok: false, error: "no Pourquoi/Why item in menu" }; + } + + clickEl(whyItem); + + // Always try BOTH: GraphQL (if any) + DOM scrape while panel is open + let graphql = null; + let scraped = null; + const deadline = Date.now() + 9000; + while (Date.now() < deadline) { + window.postMessage( + { source: SOURCE, type: "claim-recent", key, since: before - 50 }, + "*", + ); + if (!graphql) graphql = readGraphqlWhy(key, before); + const attempt = scrapeWhyDialog(); + if (attempt) scraped = attempt; + if (graphql && scraped) break; + // GraphQL-only: wait a bit for DOM; DOM-only: give GraphQL ~2.5s more + if (graphql && Date.now() - before > 4500) break; + if (scraped && !graphql && Date.now() - before > 2800) break; + await sleep(180); + } + + // Final passes + window.postMessage( + { source: SOURCE, type: "claim-recent", key, since: before - 50 }, + "*", + ); + await sleep(120); + if (!graphql) graphql = readGraphqlWhy(key, before); + if (!scraped) scraped = scrapeWhyDialog(); + + const merged = mergeWhy(graphql, scraped); + if (merged) { + results.set(key, { ...merged, storyKey: key }); + console.info( + "[fb-why]", + key, + "source=", + merged.source, + (merged.generic || "").slice(0, 80), + ); + } + + await sleep(200); + await pressEscape(); + await sleep(200); + await pressEscape(); + + if (!merged) { + return { ok: false, error: "panel opened but no GraphQL and no DOM text" }; + } + return { ok: true, source: merged.source }; +} + +function unusedTargets() { + return findPostTargets().filter( + (t) => !t.menuBtn.dataset.fbWhyDone && !t.root.dataset.fbWhyDone, + ); +} + +function markTargetDone(target) { + try { + target.menuBtn.dataset.fbWhyDone = "1"; + target.root.dataset.fbWhyDone = "1"; + } catch { + /* ignore */ + } +} + +async function scrollForMorePosts() { + const y0 = window.scrollY; + window.scrollBy({ top: Math.floor(window.innerHeight * 0.9), behavior: "smooth" }); + await sleep(1400); + // Nudge again if FB virtual list didn't move + if (Math.abs(window.scrollY - y0) < 40) { + window.scrollBy(0, Math.floor(window.innerHeight * 0.9)); + await sleep(1000); + } +} + +async function runUiFetch() { + console.info("[fb-why] Fetch clicked"); + if (running) { + statusMsg = "Already running…"; + render(); + return; + } + running = true; + lastError = ""; + items = []; + for (const k of [...results.keys()]) { + if (k.startsWith("dom-")) results.delete(k); + } + // Clear prior done marks so a new run can revisit + for (const el of document.querySelectorAll("[data-fb-why-done]")) { + delete el.dataset.fbWhyDone; + } + + try { + statusMsg = `Looking for ${TARGET_OK} posts…`; + render(); + + let attempts = 0; + let scrollRounds = 0; + let ok = 0; + + while (ok < TARGET_OK && attempts < MAX_ATTEMPTS) { + let targets = unusedTargets(); + if (!targets.length) { + if (scrollRounds >= MAX_SCROLL_ROUNDS) break; + statusMsg = `Scrolling for more posts… (${ok}/${TARGET_OK})`; + render(); + await scrollForMorePosts(); + scrollRounds += 1; + targets = unusedTargets(); + if (!targets.length) continue; + } + + const target = targets[0]; + markTargetDone(target); + attempts += 1; + + const isAd = isAdRoot(target.root); + const key = `dom-${ok}`; + const label = postLabel(target.root, target.menuLabel || `Post ${ok + 1}`); + statusMsg = `Fetching ${ok + 1}/${TARGET_OK}…`; + render(); + + try { + target.root.scrollIntoView({ block: "center" }); + } catch { + /* ignore */ + } + await sleep(400); + + try { + const res = await openWhyForTarget(target, key); + if (res.ok && whyHasContent(results.get(key))) { + items.push({ key, label, isAd }); + ok += 1; + } else { + results.delete(key); + console.info("[fb-why] skip failed", res?.error || "empty"); + } + } catch (e) { + results.delete(key); + console.warn("[fb-why] item error", e); + } + + render(); + await sleep(300); + } + + statusMsg = + ok >= TARGET_OK + ? `Done — ${ok} explanations.` + : `Done — ${ok}/${TARGET_OK} (scrolled ${scrollRounds}×).`; + } catch (e) { + lastError = String(e?.message || e); + statusMsg = "Crash: " + lastError; + console.error("[fb-why] runUiFetch", e); + } finally { + running = false; + window.postMessage({ source: SOURCE, type: "set-pending", key: null }, "*"); + render(); + } +} + +function formatWhy(why) { + if (!why) return "—"; + const parts = []; + if (why.kind === "ad" || why.advertiser) { + parts.push(`Ad${why.advertiser ? ": " + why.advertiser : ""}`); + } + if (why.generic) parts.push(why.generic); + if ( + why.personalized && + why.personalized !== why.generic && + !String(why.generic || "").includes(why.personalized.slice(0, 40)) + ) { + parts.push(why.personalized); + } + return parts.join("\n") || "—"; +} + +function escapeHtml(s) { + return String(s) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +function ensurePanel() { + if (panel) return panel; + panel = document.createElement("aside"); + panel.className = "fb-why-panel"; + panel.innerHTML = ` + +

+
    + `; + panel.addEventListener("click", (e) => { + const btn = e.target.closest("button[data-act]"); + if (!btn) return; + e.preventDefault(); + e.stopPropagation(); + if (btn.dataset.act === "fetch") { + statusMsg = "Starting…"; + render(); + void runUiFetch(); + } + }); + document.documentElement.appendChild(panel); + return panel; +} + +function render() { + ensurePanel(); + const fetchBtn = panel.querySelector(".fb-why-fetch"); + if (fetchBtn) fetchBtn.disabled = running; + panel.querySelector(".fb-why-status").textContent = statusMsg; + + const list = panel.querySelector(".fb-why-list"); + if (!items.length) { + list.innerHTML = running + ? "" + : `
  1. Scrolls the feed until it has ${TARGET_OK} explanations.
  2. `; + return; + } + + list.innerHTML = items + .map((s) => { + const why = results.get(s.key); + return `
  3. +
    + ${s.isAd ? "Ad" : "Post"} + ${escapeHtml(s.label)} +
    +
    ${escapeHtml(formatWhy(why))}
    +
  4. `; + }) + .join(""); +} + +function start() { + ensurePanel(); + statusMsg = ""; + render(); + window.postMessage({ source: SOURCE, type: "ping" }, "*"); + console.info("[fb-why] UI click mode v0.3.0"); +} + +if (document.documentElement) start(); +else document.addEventListener("DOMContentLoaded", start); diff --git a/extensions/chrome-extension-fb-why/inject.js b/extensions/chrome-extension-fb-why/inject.js new file mode 100644 index 0000000..e561c61 --- /dev/null +++ b/extensions/chrome-extension-fb-why/inject.js @@ -0,0 +1,261 @@ +/** + * MAIN world: capture WAIST GraphQL; expose last captures for UI flow. + */ +(function () { + const SOURCE = "fb-why-top10"; + + /** @type {string|null} */ + let pendingKey = null; + /** @type {Map} */ + const whys = new Map(); + /** @type {object[]} */ + let recent = []; + + const origFetch = window.fetch.bind(window); + + function emit(type, payload) { + window.postMessage({ source: SOURCE, type, ...payload }, "*"); + } + + function isGraphqlUrl(url) { + return /\/api\/graphql\/?/i.test(String(url || "")); + } + + function walk(obj, fn) { + if (obj == null || typeof obj !== "object") return; + fn(obj); + if (Array.isArray(obj)) { + obj.forEach((v) => walk(v, fn)); + return; + } + for (const v of Object.values(obj)) walk(v, fn); + } + + function isWaistResponse(data) { + const s = JSON.stringify(data); + return ( + s.includes("waist_") || + s.includes("ifr_waist_explanation") || + s.includes("WAISTUI") || + s.includes("waist_explanations") || + // Organic "why you see this post" payloads (no waist_ prefix) + s.includes("feed_unit_explanation") || + s.includes("WhyAmISeeingThis") || + s.includes("why_am_i_seeing") || + s.includes("RankingExplanation") || + s.includes("ranking_explanation") + ); + } + + function pushText(out, v) { + if (v == null) return; + const s = typeof v === "string" ? v.trim() : ""; + if (s.length > 8 && s.length < 600 && !out.targeting.includes(s)) { + out.targeting.push(s); + } + } + + function extractWhy(data) { + const out = { + kind: "post", + generic: null, + personalized: null, + advertiser: null, + targeting: [], + at: Date.now(), + }; + + walk(data, (node) => { + if (!node || typeof node !== "object") return; + if (node.ifr_waist_explanation_data) { + out.generic = + node.ifr_waist_explanation_data.generic_explanation || null; + out.personalized = + node.ifr_waist_explanation_data.personalized_explanation || null; + } + if (node.waist_advertiser_info?.name) { + out.kind = "ad"; + out.advertiser = node.waist_advertiser_info.name; + } + if (Array.isArray(node.waist_targeting_data)) { + out.kind = "ad"; + for (const t of node.waist_targeting_data) { + if (t.waist_ui_type === "AGE_GENDER") { + out.targeting.push(`age ${t.age_min ?? "?"}-${t.age_max ?? "?"}`); + } else if (t.waist_ui_type === "LOCATION" && t.location_name) { + out.targeting.push(`location ${t.location_name}`); + } else if (t.waist_ui_type) { + out.targeting.push(String(t.waist_ui_type)); + } + } + } + if (Array.isArray(node.waist_explanations_data)) { + for (const e of node.waist_explanations_data) { + const t = e.title || e.description || e.text || e.headline; + if (t) out.targeting.push(String(t)); + } + } + // Organic ranking / follow explanations + if (Array.isArray(node.explanations)) { + for (const e of node.explanations) { + if (typeof e === "string") pushText(out, e); + else if (e && typeof e === "object") { + pushText(out, e.title || e.text || e.description || e.subtitle); + pushText(out, e.body); + } + } + } + if (node.explanation_title || node.explanation_body) { + pushText(out, node.explanation_title); + pushText(out, node.explanation_body); + } + if (node.__typename && /Explanation|Waist|WhyAmISeeing/i.test(node.__typename)) { + pushText(out, node.title || node.text || node.description || node.name); + pushText(out, node.subtitle || node.body); + } + }); + + if (!out.generic && out.targeting.length) { + out.generic = out.targeting.join(" · "); + } + if (out.advertiser) out.kind = "ad"; + else if ( + out.targeting.some((x) => + /age |location |AGE_GENDER|LOCATION|advertiser|sponsored/i.test(x), + ) + ) { + out.kind = "ad"; + } + return out; + } + + function parseJsonResponse(text) { + try { + return JSON.parse(text); + } catch { + try { + const lines = text + .split("\n") + .filter(Boolean) + .map((l) => JSON.parse(l)); + return lines.length === 1 ? lines[0] : { batch: lines }; + } catch { + return null; + } + } + } + + function storeWhy(why) { + const key = pendingKey || `waist-${Date.now()}`; + const payload = { + ...why, + storyKey: key, + at: Date.now(), + source: why.source || "graphql", + }; + // Skip empty extracts + if ( + !payload.generic && + !payload.personalized && + !payload.advertiser && + !(payload.targeting && payload.targeting.length) + ) { + return; + } + whys.set(key, payload); + recent.push(payload); + if (recent.length > 20) recent.shift(); + window.__fbWhyLast = payload; + emit("why", { key, why: payload }); + emit("state", { whys: Object.fromEntries(whys), recent: recent.slice(-5) }); + console.info( + "[fb-why] captured", + key, + why.kind, + why.advertiser || why.generic?.slice?.(0, 60), + ); + } + + function handleResponseText(text) { + const data = parseJsonResponse(text); + if (!data) return; + // batch of JSON objects + if (data.batch && Array.isArray(data.batch)) { + for (const part of data.batch) { + if (isWaistResponse(part)) storeWhy(extractWhy(part)); + } + return; + } + if (!isWaistResponse(data)) return; + storeWhy(extractWhy(data)); + } + + window.fetch = async function (...args) { + const input = args[0]; + const url = + typeof input === "string" + ? input + : input instanceof Request + ? input.url + : String(input?.url ?? ""); + const res = await origFetch(...args); + if (isGraphqlUrl(url)) { + try { + const clone = res.clone(); + void clone.text().then(handleResponseText); + } catch { + /* ignore */ + } + } + return res; + }; + + const OrigXHR = window.XMLHttpRequest; + function PatchedXHR() { + const xhr = new OrigXHR(); + let url = ""; + const open = xhr.open; + xhr.open = function (method, u, ...rest) { + url = String(u || ""); + return open.call(xhr, method, u, ...rest); + }; + xhr.addEventListener("load", function () { + if (!isGraphqlUrl(url)) return; + try { + handleResponseText(xhr.responseText); + } catch { + /* ignore */ + } + }); + return xhr; + } + PatchedXHR.prototype = OrigXHR.prototype; + window.XMLHttpRequest = PatchedXHR; + + window.addEventListener("message", (event) => { + if (event.source !== window) return; + const data = event.data; + if (!data || data.source !== SOURCE) return; + if (data.type === "set-pending") { + pendingKey = data.key || null; + window.__fbWhyPending = pendingKey; + } + if (data.type === "ping") { + emit("state", { + whys: Object.fromEntries(whys), + recent: recent.slice(-5), + }); + } + if (data.type === "claim-recent") { + const since = data.since || 0; + const hit = [...recent].reverse().find((w) => (w.at || 0) > since); + if (hit) { + const key = data.key || hit.storyKey; + whys.set(key, { ...hit, storyKey: key }); + emit("why", { key, why: whys.get(key) }); + } + } + }); + + console.info("[fb-why] inject ready (capture + recent buffer)"); +})(); diff --git a/extensions/chrome-extension-fb-why/manifest.json b/extensions/chrome-extension-fb-why/manifest.json new file mode 100644 index 0000000..f9fc443 --- /dev/null +++ b/extensions/chrome-extension-fb-why/manifest.json @@ -0,0 +1,36 @@ +{ + "manifest_version": 3, + "name": "FB Why Top 10", + "version": "0.3.0", + "description": "Fetch Why for 5 Facebook feed posts (GraphQL + DOM), scrolling as needed.", + "host_permissions": [ + "https://www.facebook.com/*", + "https://web.facebook.com/*", + "https://facebook.com/*", + "https://m.facebook.com/*" + ], + "content_scripts": [ + { + "matches": [ + "https://www.facebook.com/*", + "https://web.facebook.com/*", + "https://facebook.com/*", + "https://m.facebook.com/*" + ], + "js": ["content.js"], + "css": ["styles.css"], + "run_at": "document_start" + }, + { + "matches": [ + "https://www.facebook.com/*", + "https://web.facebook.com/*", + "https://facebook.com/*", + "https://m.facebook.com/*" + ], + "js": ["inject.js"], + "run_at": "document_start", + "world": "MAIN" + } + ] +} diff --git a/extensions/chrome-extension-fb-why/styles.css b/extensions/chrome-extension-fb-why/styles.css new file mode 100644 index 0000000..4916b66 --- /dev/null +++ b/extensions/chrome-extension-fb-why/styles.css @@ -0,0 +1,82 @@ +.fb-why-panel { + position: fixed; + top: 72px; + right: 16px; + z-index: 2147483646; + width: 320px; + max-height: calc(100vh - 96px); + overflow: auto; + padding: 12px; + border-radius: 12px; + background: rgba(15, 20, 25, 0.95); + color: #e7e9ea; + border: 1px solid rgba(255, 255, 255, 0.14); + box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45); + font: 12px/1.4 system-ui, -apple-system, sans-serif; +} + +.fb-why-fetch { + appearance: none; + border: 0; + border-radius: 8px; + width: 100%; + padding: 8px 12px; + background: #1d9bf0; + color: #fff; + font: inherit; + font-weight: 700; + cursor: pointer; +} + +.fb-why-fetch:disabled { + opacity: 0.55; + cursor: wait; +} + +.fb-why-status { + margin: 8px 0 0; + color: #1d9bf0; + font-weight: 600; + min-height: 1.2em; +} + +.fb-why-list { + margin: 10px 0 0; + padding-left: 18px; +} + +.fb-why-list li { + margin-bottom: 10px; +} + +.fb-why-empty { + list-style: none; + margin-left: -18px; + color: #8b98a5; + font-size: 11px; +} + +.fb-why-item-head { + display: flex; + gap: 6px; + align-items: baseline; + margin-bottom: 4px; +} + +.fb-why-item-head .tag { + font-size: 10px; + font-weight: 700; + text-transform: uppercase; + color: #8b98a5; +} + +.fb-why-text { + margin: 0; + white-space: pre-wrap; + word-break: break-word; + background: rgba(255, 255, 255, 0.04); + border-radius: 8px; + padding: 6px 8px; + font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; + color: #d7dbe0; +} diff --git a/extensions/chrome-extension-x-filter/content.js b/extensions/chrome-extension-x-filter/content.js new file mode 100644 index 0000000..3fcdc66 --- /dev/null +++ b/extensions/chrome-extension-x-filter/content.js @@ -0,0 +1,219 @@ +/** + * Floating multi-select on For You: blur selected sources + live % from sample. + */ + +const SOURCE = "x-foryou-filter"; + +const CATEGORIES = [ + { id: "phoenix", label: "Phoenix" }, + { id: "phoenixCold", label: "Phoenix Cold" }, + { id: "viral", label: "Viral (Popular)" }, + { id: "inNetwork", label: "In Network" }, + { id: "promoted", label: "Promoted" }, +]; + +/** @type {Map} tweetId -> category */ +const byId = new Map(); + +/** @type {Set} */ +const selected = new Set(); + +let panel = null; +let sampleStatus = { + total: 0, + pages: 0, + paging: false, + target: 300, + error: null, +}; + +window.addEventListener("message", (event) => { + if (event.source !== window) return; + const data = event.data; + if (!data || data.source !== SOURCE) return; + + if (data.type === "sample-reset") { + byId.clear(); + updateStats(); + scheduleApply(); + } + + if (data.type === "feed-items") { + for (const item of data.items || []) { + if (!item?.id) continue; + byId.set(String(item.id), item.category || null); + } + updateStats(); + scheduleApply(); + } + + if (data.type === "sample-status") { + sampleStatus = { + total: data.total ?? 0, + pages: data.pages ?? 0, + paging: Boolean(data.paging), + target: data.target ?? 300, + error: data.error || null, + }; + updateStats(); + } +}); + +function isForYouHome() { + const path = location.pathname.replace(/\/$/, "") || "/"; + return path === "/home" || path === "/"; +} + +function countsByCategory() { + const counts = Object.fromEntries(CATEGORIES.map((c) => [c.id, 0])); + let known = 0; + for (const cat of byId.values()) { + if (!cat || !(cat in counts)) continue; + counts[cat] += 1; + known += 1; + } + return { counts, known }; +} + +function updateStats() { + if (!panel) return; + const { counts, known } = countsByCategory(); + const n = known || byId.size; + + for (const c of CATEGORIES) { + const el = panel.querySelector(`[data-pct="${c.id}"]`); + if (!el) continue; + const count = counts[c.id]; + if (!n) { + el.textContent = "—"; + continue; + } + const pct = Math.round((count / n) * 100); + el.textContent = `${pct}% · ${count}`; + } + + const status = panel.querySelector(".x-filter-status"); + if (status) { + const sampling = sampleStatus.paging ? " · sampling…" : ""; + const unknown = byId.size - known; + const extra = unknown > 0 ? ` · ${unknown} other` : ""; + status.textContent = `n=${n}${extra}${sampling}`; + } + const err = panel.querySelector(".x-filter-error"); + if (err) { + err.textContent = sampleStatus.error || ""; + err.hidden = !sampleStatus.error; + } +} + +function ensurePanel() { + if (panel) return panel; + panel = document.createElement("aside"); + panel.className = "x-filter-panel"; + panel.innerHTML = `

    Blur sources

    + ${CATEGORIES.map( + (c) => + ``, + ).join("")} +

    n=0

    + +

    Checked = blurred. Auto-samples HomeTimeline.

    `; + + panel.addEventListener("change", (e) => { + const input = e.target; + if (!(input instanceof HTMLInputElement) || !input.dataset.cat) return; + if (input.checked) selected.add(input.dataset.cat); + else selected.delete(input.dataset.cat); + applyBlur(); + }); + + document.documentElement.appendChild(panel); + updateStats(); + return panel; +} + +function updatePanelVisibility() { + ensurePanel(); + panel.hidden = !isForYouHome(); +} + +function idFromHref(href) { + try { + const u = new URL(href, location.origin); + const m = u.pathname.match(/\/status\/(\d+)/); + return m ? m[1] : null; + } catch { + return null; + } +} + +function tweetCardFromAnchor(a) { + return ( + a.closest?.('article[data-testid="tweet"]') || + a.closest?.("article") || + null + ); +} + +function applyBlur() { + for (const el of document.querySelectorAll(".x-filter-blurred")) { + el.classList.remove("x-filter-blurred"); + } + if (!selected.size || !isForYouHome()) return; + + /** @type {Map} */ + const cards = new Map(); + for (const a of document.querySelectorAll('a[href*="/status/"]')) { + const id = idFromHref(a.getAttribute("href") || ""); + if (!id || cards.has(id)) continue; + const card = tweetCardFromAnchor(a); + if (card) cards.set(id, card); + } + + for (const [id, card] of cards) { + const cat = byId.get(id); + if (cat && selected.has(cat)) card.classList.add("x-filter-blurred"); + } +} + +let applyTimer = null; +function scheduleApply() { + if (applyTimer) return; + applyTimer = requestAnimationFrame(() => { + applyTimer = null; + updatePanelVisibility(); + applyBlur(); + updateStats(); + }); +} + +const observer = new MutationObserver(() => scheduleApply()); + +function start() { + updatePanelVisibility(); + observer.observe(document.documentElement, { + childList: true, + subtree: true, + }); + window.addEventListener("popstate", scheduleApply); + const wrap = (fn) => + function (...args) { + const ret = fn.apply(this, args); + scheduleApply(); + return ret; + }; + history.pushState = wrap(history.pushState.bind(history)); + history.replaceState = wrap(history.replaceState.bind(history)); + setTimeout(scheduleApply, 500); + setTimeout(scheduleApply, 1500); + console.info("[x-filter] active"); +} + +if (document.documentElement) start(); +else document.addEventListener("DOMContentLoaded", start); diff --git a/extensions/chrome-extension-x-filter/inject.js b/extensions/chrome-extension-x-filter/inject.js new file mode 100644 index 0000000..cd86317 --- /dev/null +++ b/extensions/chrome-extension-x-filter/inject.js @@ -0,0 +1,566 @@ +/** + * MAIN world: capture HomeTimeline + paginate via bottom cursor for source stats. + * Falls back to artificial scroll if API replay fails. + */ +(function () { + const SOURCE = "x-foryou-filter"; + const PAGER_HEADER = "x-foryou-filter-pager"; + const TARGET_POSTS = 300; + const MAX_PAGES = 25; + const PAGE_DELAY_MS = 500; + const SCROLL_STEP_PX = 2200; + const SCROLL_ROUNDS = 40; + + const origFetch = window.fetch.bind(window); + + /** @type {{ url: string, method: string, headers: Record, body: string|null } | null} */ + let lastTemplate = null; + let paging = false; + let pageCount = 0; + let lastError = ""; + /** @type {Set} */ + const seenIds = new Set(); + + function emit(type, payload) { + window.postMessage({ source: SOURCE, type, ...payload }, "*"); + } + + function emitStatus() { + emit("sample-status", { + total: seenIds.size, + pages: pageCount, + paging, + target: TARGET_POSTS, + error: lastError || null, + }); + } + + function isHomeTimelineUrl(url) { + const u = String(url || ""); + if (/HomeLatestTimeline/i.test(u)) return false; + if (/HomeTimeline/i.test(u)) return true; + if (/\/2\/timeline\/home\.json/i.test(u)) return true; + return false; + } + + function unwrapTweet(result) { + if (!result || typeof result !== "object") return null; + if (result.__typename === "TweetWithVisibilityResults") { + return result.tweet || null; + } + if (result.legacy || result.rest_id) return result; + if (result.tweet) return unwrapTweet(result.tweet); + return null; + } + + function categoryOf(injectionType, promoted) { + if (promoted || injectionType === "ForYouPromoted") return "promoted"; + switch (injectionType) { + case "ForYouInNetwork": + return "inNetwork"; + case "ForYouPopularPosts": + return "viral"; + case "ForYouPhoenixRetrievalCold": + return "phoenixCold"; + case "ForYouPhoenixRetrieval": + case "ForYouPhoenixRetrievalZeroFav": + return "phoenix"; + default: + return null; + } + } + + function normalizeEntry(entry) { + const content = entry?.content; + if (!content || content.entryType !== "TimelineTimelineItem") return null; + const item = content.itemContent; + if (!item || item.__typename !== "TimelineTweet") return null; + + const tweet = unwrapTweet(item.tweet_results?.result); + if (!tweet?.rest_id && !tweet?.legacy) return null; + const id = String(tweet.rest_id || tweet.legacy?.id_str || ""); + if (!id) return null; + + const cei = content.clientEventInfo || {}; + const injectionType = + cei.details?.timelinesDetails?.injectionType || null; + const promoted = + Boolean(item.promotedMetadata) || + String(entry.entryId || "").startsWith("promoted-tweet"); + + return { + id, + injectionType, + category: categoryOf(injectionType, promoted), + }; + } + + function getUrt(body) { + return ( + body?.data?.home?.home_timeline_urt || + body?.data?.home?.homeTimelineUrt || + body?.timeline || + null + ); + } + + function findBottomCursor(urt) { + if (!urt) return null; + for (const instr of urt.instructions || []) { + for (const entry of instr.entries || []) { + const c = entry?.content; + const id = String(entry?.entryId || ""); + if ( + c?.cursorType === "Bottom" || + id.startsWith("cursor-bottom") + ) { + return c?.value || null; + } + } + if (instr.direction === "Bottom" && instr.cursor) return instr.cursor; + } + return null; + } + + function collectFromBody(body) { + const items = []; + const urt = getUrt(body); + + function take(entries) { + if (!Array.isArray(entries)) return; + for (const entry of entries) { + const item = normalizeEntry(entry); + if (item) items.push(item); + } + } + + for (const instr of urt?.instructions || []) { + take(instr.entries); + if (instr.entry) take([instr.entry]); + } + take(body?.timeline?.instructions?.flatMap?.((i) => i.entries) || []); + + const page = urt?.metadata?.scribeConfig?.page; + if (page && page !== "for_you") return { items: [], cursor: null }; + + return { items, cursor: findBottomCursor(urt) }; + } + + function headersToObject(h) { + const out = {}; + if (!h) return out; + if (h instanceof Headers) { + h.forEach((v, k) => { + out[k] = v; + }); + return out; + } + if (Array.isArray(h)) { + for (const [k, v] of h) out[k] = v; + return out; + } + return { ...h }; + } + + function scrubHeaders(headers) { + const out = { ...headers }; + for (const key of Object.keys(out)) { + const low = key.toLowerCase(); + if ( + low === "content-length" || + low === "cookie" || + low === "host" || + low === "origin" || + low.startsWith("sec-") + ) { + delete out[key]; + } + } + return out; + } + + async function readBody(value) { + if (value == null) return null; + if (typeof value === "string") return value; + if (value instanceof URLSearchParams) return value.toString(); + if (value instanceof Blob) return await value.text(); + if (typeof value === "object" && typeof value.text === "function") { + try { + return await value.text(); + } catch { + return null; + } + } + try { + return String(value); + } catch { + return null; + } + } + + async function captureTemplate(args) { + const input = args[0]; + const init = args[1] || {}; + let url; + let method = (init.method || "GET").toUpperCase(); + let headers = scrubHeaders(headersToObject(init.headers)); + let body = await readBody(init.body); + + if (typeof input === "string") { + url = input; + } else if (input instanceof Request) { + url = input.url; + method = (input.method || method).toUpperCase(); + headers = scrubHeaders({ + ...headersToObject(input.headers), + ...headersToObject(init.headers), + }); + if (!body) { + try { + body = await input.clone().text(); + } catch { + body = null; + } + } + } else { + url = String(input?.url ?? input); + } + + lastTemplate = { url, method, headers, body: body || null }; + console.info("[x-filter] captured HomeTimeline template", { + method, + hasBody: Boolean(body), + hasVarsInUrl: new URL(url, location.origin).searchParams.has("variables"), + auth: Boolean(headers.authorization || headers.Authorization), + }); + } + + function withCursor(template, cursor) { + const headers = { + ...scrubHeaders(template.headers), + [PAGER_HEADER]: "1", + }; + + // POST JSON body (common for HomeTimeline) + if (template.body) { + try { + const parsed = JSON.parse(template.body); + if (parsed.variables != null) { + const vars = + typeof parsed.variables === "string" + ? JSON.parse(parsed.variables) + : { ...parsed.variables }; + vars.cursor = cursor; + // Keep seenTweetIds small / omit to avoid huge payloads + if (Array.isArray(vars.seenTweetIds) && vars.seenTweetIds.length > 40) { + vars.seenTweetIds = vars.seenTweetIds.slice(-40); + } + const next = { ...parsed }; + next.variables = + typeof parsed.variables === "string" + ? JSON.stringify(vars) + : vars; + return { + url: template.url.split("?")[0], // POST usually has clean path + method: template.method || "POST", + headers: { + ...headers, + "content-type": + headers["content-type"] || + headers["Content-Type"] || + "application/json", + }, + body: JSON.stringify(next), + }; + } + } catch (e) { + console.warn("[x-filter] body cursor rewrite failed", e); + } + } + + // GET ?variables= + const u = new URL(template.url, location.origin); + const rawVars = u.searchParams.get("variables"); + if (rawVars) { + const vars = JSON.parse(rawVars); + vars.cursor = cursor; + u.searchParams.set("variables", JSON.stringify(vars)); + return { + url: u.toString(), + method: template.method || "GET", + headers, + body: null, + }; + } + + u.searchParams.set("cursor", cursor); + return { + url: u.toString(), + method: template.method || "GET", + headers, + body: null, + }; + } + + function ingestItems(items) { + const fresh = []; + for (const item of items) { + if (!item?.id || seenIds.has(item.id)) continue; + seenIds.add(item.id); + fresh.push(item); + } + if (fresh.length) emit("feed-items", { items: fresh }); + emitStatus(); + return fresh.length; + } + + function sleep(ms) { + return new Promise((r) => setTimeout(r, ms)); + } + + function findScrollRoot() { + const tweet = document.querySelector('article[data-testid="tweet"]'); + let el = tweet?.parentElement; + while (el && el !== document.body) { + const style = getComputedStyle(el); + const oy = style.overflowY; + if ( + (oy === "auto" || oy === "scroll" || oy === "overlay") && + el.scrollHeight > el.clientHeight + 100 + ) { + return el; + } + el = el.parentElement; + } + return ( + document.scrollingElement || + document.documentElement || + document.body + ); + } + + async function scrollFallback() { + lastError = "API page2 failed — scrolling to load more"; + emitStatus(); + const root = findScrollRoot(); + let stagnant = 0; + let prev = seenIds.size; + + for (let i = 0; i < SCROLL_ROUNDS && seenIds.size < TARGET_POSTS; i++) { + root.scrollBy(0, SCROLL_STEP_PX); + window.scrollBy(0, SCROLL_STEP_PX); + await sleep(700); + if (seenIds.size <= prev) { + stagnant += 1; + if (stagnant >= 5) break; + } else { + stagnant = 0; + prev = seenIds.size; + } + emitStatus(); + } + lastError = seenIds.size > 40 ? "" : lastError; + emitStatus(); + } + + async function paginateFrom(cursor) { + if (paging) return; + paging = true; + lastError = ""; + emitStatus(); + + let next = cursor; + let apiPages = 0; + + try { + if (!lastTemplate) { + lastError = "no request template"; + } else if (!next) { + lastError = "no bottom cursor"; + } else { + while ( + next && + apiPages < MAX_PAGES && + seenIds.size < TARGET_POSTS + ) { + await sleep(PAGE_DELAY_MS); + const req = withCursor(lastTemplate, next); + const init = { + method: req.method, + headers: req.headers, + credentials: "include", + }; + if ( + req.body != null && + req.method !== "GET" && + req.method !== "HEAD" + ) { + init.body = req.body; + } + + const res = await origFetch(req.url, init); + if (!res.ok) { + lastError = `page2 HTTP ${res.status}`; + console.warn("[x-filter] pager HTTP", res.status, await res.text().catch(() => "")); + break; + } + const body = await res.json(); + apiPages += 1; + pageCount += 1; + const { items, cursor: bottom } = collectFromBody(body); + const added = ingestItems(items); + console.info("[x-filter] pager page", apiPages, "added", added, "total", seenIds.size); + if (!bottom || bottom === next || added === 0) { + if (added === 0 && apiPages === 1) { + lastError = "pager returned 0 new posts"; + } + break; + } + next = bottom; + } + } + } catch (e) { + lastError = String(e?.message || e); + console.warn("[x-filter] pagination failed", e); + } + + // If we only have the first paint (~30–40), try scrolling + if (seenIds.size < 60) { + await scrollFallback(); + } + + paging = false; + emitStatus(); + } + + function isPagerRequest(args) { + const init = args[1] || {}; + const headers = headersToObject(init.headers); + for (const [k, v] of Object.entries(headers)) { + if (k.toLowerCase() === PAGER_HEADER.toLowerCase() && v) return true; + } + if (args[0] instanceof Request) { + try { + return args[0].headers.has(PAGER_HEADER); + } catch { + return false; + } + } + return false; + } + + window.fetch = async function (...args) { + const req = args[0]; + const url = + typeof req === "string" + ? req + : req instanceof Request + ? req.url + : String(req?.url ?? ""); + const home = isHomeTimelineUrl(url); + const fromPager = isPagerRequest(args); + + let templateReady = Promise.resolve(); + if (home && !fromPager) { + templateReady = captureTemplate(args); + } + + const res = await origFetch(...args); + + if (home && !fromPager) { + try { + const clone = res.clone(); + void (async () => { + await templateReady; + try { + const body = JSON.parse(await clone.text()); + const { items, cursor } = collectFromBody(body); + seenIds.clear(); + pageCount = 1; + lastError = ""; + emit("sample-reset", {}); + ingestItems(items); + console.info( + "[x-filter] first page", + items.length, + "cursor", + Boolean(cursor), + "template", + Boolean(lastTemplate), + ); + void paginateFrom(cursor); + } catch (e) { + console.warn("[x-filter] first-page parse failed", e); + } + })(); + } catch { + /* ignore */ + } + } else if (home && fromPager) { + // Should not happen (pager uses origFetch); keep for safety + try { + const clone = res.clone(); + void clone.json().then((body) => { + pageCount += 1; + ingestItems(collectFromBody(body).items); + }); + } catch { + /* ignore */ + } + } + + return res; + }; + + const OrigXHR = window.XMLHttpRequest; + function PatchedXHR() { + const xhr = new OrigXHR(); + let url = ""; + let method = "GET"; + const open = xhr.open; + const setRequestHeader = xhr.setRequestHeader; + const headers = {}; + xhr.open = function (m, u, ...rest) { + method = String(m || "GET").toUpperCase(); + url = String(u || ""); + return open.call(xhr, m, u, ...rest); + }; + xhr.setRequestHeader = function (k, v) { + headers[k] = v; + return setRequestHeader.call(xhr, k, v); + }; + const send = xhr.send; + xhr.send = function (body) { + if (isHomeTimelineUrl(url)) { + lastTemplate = { + url, + method, + headers: scrubHeaders(headers), + body: body != null ? String(body) : null, + }; + } + return send.call(xhr, body); + }; + xhr.addEventListener("load", function () { + if (!isHomeTimelineUrl(url)) return; + try { + const body = JSON.parse(xhr.responseText); + const { items, cursor } = collectFromBody(body); + seenIds.clear(); + pageCount = 1; + lastError = ""; + emit("sample-reset", {}); + ingestItems(items); + void paginateFrom(cursor); + } catch { + /* ignore */ + } + }); + return xhr; + } + PatchedXHR.prototype = OrigXHR.prototype; + window.XMLHttpRequest = PatchedXHR; + + emitStatus(); + console.info("[x-filter] inject ready"); +})(); diff --git a/extensions/chrome-extension-x-filter/manifest.json b/extensions/chrome-extension-x-filter/manifest.json new file mode 100644 index 0000000..402df60 --- /dev/null +++ b/extensions/chrome-extension-x-filter/manifest.json @@ -0,0 +1,21 @@ +{ + "manifest_version": 3, + "name": "X For You Filter", + "version": "0.2.2", + "description": "Blur For You posts by source + live % via HomeTimeline pagination.", + "host_permissions": ["https://x.com/*", "https://twitter.com/*"], + "content_scripts": [ + { + "matches": ["https://x.com/*", "https://twitter.com/*"], + "js": ["content.js"], + "css": ["styles.css"], + "run_at": "document_start" + }, + { + "matches": ["https://x.com/*", "https://twitter.com/*"], + "js": ["inject.js"], + "run_at": "document_start", + "world": "MAIN" + } + ] +} diff --git a/extensions/chrome-extension-x-filter/styles.css b/extensions/chrome-extension-x-filter/styles.css new file mode 100644 index 0000000..a10ebf2 --- /dev/null +++ b/extensions/chrome-extension-x-filter/styles.css @@ -0,0 +1,80 @@ +.x-filter-panel { + position: fixed; + top: 72px; + right: 16px; + z-index: 2147483646; + width: 240px; + padding: 10px 12px; + border-radius: 12px; + background: rgba(15, 20, 25, 0.94); + color: #e7e9ea; + border: 1px solid rgba(255, 255, 255, 0.14); + box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45); + font: 12px/1.35 system-ui, -apple-system, sans-serif; + backdrop-filter: blur(8px); +} + +.x-filter-panel[hidden] { + display: none !important; +} + +.x-filter-panel h2 { + margin: 0 0 8px; + font-size: 12px; + font-weight: 700; + letter-spacing: 0.02em; +} + +.x-filter-panel label { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 4px 0; + cursor: pointer; + user-select: none; +} + +.x-filter-panel label .left { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; +} + +.x-filter-panel .pct { + font-variant-numeric: tabular-nums; + color: #8b98a5; + font-weight: 600; +} + +.x-filter-panel input { + accent-color: #1d9bf0; +} + +.x-filter-panel .x-filter-status { + margin: 8px 0 0; + color: #e7e9ea; + font-size: 11px; + font-weight: 600; +} + +.x-filter-panel .hint { + margin: 4px 0 0; + color: #8b98a5; + font-size: 11px; +} + +.x-filter-panel .x-filter-error { + margin: 4px 0 0; + color: #f4212e; + font-size: 11px; +} + +.x-filter-blurred { + filter: blur(7px) saturate(0.6); + opacity: 0.45; + pointer-events: none; + user-select: none; + transition: filter 0.15s ease, opacity 0.15s ease; +} diff --git a/extensions/chrome-extension-x/content.js b/extensions/chrome-extension-x/content.js new file mode 100644 index 0000000..910ea69 --- /dev/null +++ b/extensions/chrome-extension-x/content.js @@ -0,0 +1,311 @@ +/** + * Content script: i-icon next to each For You post timestamp; hover shows why. + */ + +const SOURCE = "x-foryou-why"; +const MARK = "data-x-why-icon"; + +/** @type {Map} tweet id -> meta */ +const byId = new Map(); + +window.addEventListener("message", (event) => { + if (event.source !== window) return; + const data = event.data; + if (!data || data.source !== SOURCE) return; + if (data.type === "feed-items") { + for (const item of data.items) upsert(item); + scheduleScan(); + } +}); + +function upsert(item) { + if (!item?.id) return; + const prev = byId.get(item.id) ?? {}; + byId.set(item.id, { ...prev, ...item, why: formatWhy({ ...prev, ...item }) }); +} + +function fmtNum(n) { + if (n == null || Number.isNaN(Number(n))) return "—"; + return Number(n).toLocaleString("en-US"); +} + +function shortSource(injectionType) { + if (!injectionType) return "unknown"; + return String(injectionType) + .replace(/^ForYou/, "") + .replace(/([a-z])([A-Z])/g, "$1 $2"); +} + +function formatWhy(item) { + const lines = []; + lines.push( + `source: ${item.injectionType || "unknown"} (${shortSource(item.injectionType)})`, + ); + if (item.component) lines.push(`component: ${item.component}`); + if (item.promoted) lines.push("promoted: yes"); + + if (item.authorHandle) { + const follow = + item.following === true + ? "following" + : item.following === false + ? "not following" + : "following ?"; + lines.push(`author: @${item.authorHandle} (${follow})`); + } else if (item.following != null) { + lines.push(`following author: ${item.following ? "yes" : "no"}`); + } + + if (item.followedBy === true) lines.push("follows you: yes"); + + lines.push(`likes: ${fmtNum(item.likes)}`); + lines.push(`reposts: ${fmtNum(item.retweets)}`); + lines.push(`replies: ${fmtNum(item.replies)}`); + lines.push(`quotes: ${fmtNum(item.quotes)}`); + lines.push(`bookmarks: ${fmtNum(item.bookmarks)}`); + lines.push(`views: ${fmtNum(item.views)}`); + lines.push(`id: ${item.id}`); + return lines.join("\n"); +} + +function idFromHref(href) { + try { + const u = new URL(href, location.origin); + const m = u.pathname.match(/\/status\/(\d+)/); + return m ? m[1] : null; + } catch { + return null; + } +} + +function findStatusAnchors(root = document) { + return root.querySelectorAll?.('a[href*="/status/"]') ?? []; +} + +function isTimestampLabel(text) { + const t = text + .replace(/^[·•.\u00b7]+\s*/u, "") + .trim() + .toLowerCase(); + if (!t) return false; + if (t === "now" || t === "maintenant") return true; + return ( + /^\d+\s*[smhdwyj]$/i.test(t) || + /^\d+\s*(min|mins|h|hr|hrs|d|j|jour|jours|sem|wk|w|mo|m|y|an|ans)$/i.test( + t, + ) + ); +} + +function pickHeaderAnchor(anchors) { + let best = null; + for (const a of anchors) { + const text = (a.textContent || "").trim(); + const aria = (a.getAttribute("aria-label") || "").toLowerCase(); + if ( + isTimestampLabel(text) || + /\b(20\d{2}|am|pm|at)\b/.test(aria) || + a.hasAttribute("data-tooltip") || + a.querySelector?.("time") + ) { + return a; + } + if (!best) best = a; + } + return best; +} + +function findIconsById(id) { + return [...document.querySelectorAll(".x-why-icon")].filter( + (el) => el.getAttribute(MARK) === id, + ); +} + +function findTipsById(id) { + return [...document.querySelectorAll(".x-why-tooltip")].filter( + (el) => el.getAttribute(MARK) === id, + ); +} + +function removeIconAndTip(el) { + const id = el.getAttribute(MARK); + el.remove(); + if (!id) return; + // Drop orphaned body-level tips when their icon goes away + if (!findIconsById(id).length) { + for (const tip of findTipsById(id)) tip.remove(); + } +} + +function dedupeIcons(id, keepNear = null) { + const icons = findIconsById(id); + if (icons.length <= 1) return icons[0] ?? null; + + let keep = null; + if (keepNear) { + keep = + icons.find( + (el) => + el.previousElementSibling === keepNear || + keepNear.parentElement?.contains(el), + ) ?? null; + } + if (!keep) keep = icons[0]; + + suppressingMutations = true; + for (const el of icons) { + if (el !== keep) removeIconAndTip(el); + } + // Keep a single tip for this id + const tips = findTipsById(id); + for (let i = 1; i < tips.length; i++) tips[i].remove(); + Promise.resolve().then(() => { + suppressingMutations = false; + }); + return keep; +} + +function ensureIcon(headerAnchor, id) { + const existing = dedupeIcons(id, headerAnchor); + if (existing) return false; + if (headerAnchor.nextElementSibling?.classList?.contains("x-why-icon")) { + return false; + } + if (headerAnchor.parentElement?.querySelector?.(":scope > .x-why-icon")) { + return false; + } + + const meta = byId.get(id); + const why = meta?.why ?? "Not seen in HomeTimeline capture yet — scroll/refresh For You."; + + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "x-why-icon"; + btn.setAttribute(MARK, id); + btn.setAttribute("aria-label", "Why is this in For You?"); + btn.appendChild(document.createTextNode("i")); + + const tip = document.createElement("div"); + tip.className = "x-why-tooltip"; + tip.setAttribute(MARK, id); + tip.hidden = true; + tip.textContent = why; + // Append at document root so feed stacking contexts cannot bury it + document.documentElement.appendChild(tip); + + function placeTip() { + const rect = btn.getBoundingClientRect(); + const tipW = tip.offsetWidth || 260; + const tipH = tip.offsetHeight || 160; + let left = rect.right - tipW; + let top = rect.bottom + 6; + if (left < 8) left = 8; + if (left + tipW > window.innerWidth - 8) { + left = Math.max(8, window.innerWidth - tipW - 8); + } + if (top + tipH > window.innerHeight - 8) { + top = Math.max(8, rect.top - tipH - 6); + } + tip.style.left = `${Math.round(left)}px`; + tip.style.top = `${Math.round(top)}px`; + } + + function show() { + tip.textContent = byId.get(id)?.why ?? why; + tip.hidden = false; + placeTip(); + // Re-measure after paint (height depends on text) + requestAnimationFrame(placeTip); + dedupeIcons(id, headerAnchor); + } + function hide() { + tip.hidden = true; + } + + btn.addEventListener("mouseenter", show); + btn.addEventListener("focus", show); + btn.addEventListener("mouseleave", hide); + btn.addEventListener("blur", hide); + + suppressingMutations = true; + headerAnchor.insertAdjacentElement("afterend", btn); + dedupeIcons(id, headerAnchor); + Promise.resolve().then(() => { + suppressingMutations = false; + }); + return true; +} + +function scan(root = document) { + /** @type {Map} */ + const groups = new Map(); + + for (const a of findStatusAnchors(root)) { + const id = idFromHref(a.getAttribute("href") || ""); + if (!id) continue; + if (!groups.has(id)) groups.set(id, []); + groups.get(id).push(a); + } + + let added = 0; + for (const [id, anchors] of groups) { + dedupeIcons(id); + const header = pickHeaderAnchor(anchors); + if (header && ensureIcon(header, id)) added += 1; + } + + if (added > 0 || groups.size > 0) { + console.debug( + `[x-why] posts=${groups.size} knownFeed=${byId.size} iconsAdded=${added}`, + ); + } +} + +let scanTimer = null; +let suppressingMutations = false; + +function scheduleScan() { + if (suppressingMutations) return; + if (scanTimer) return; + scanTimer = requestAnimationFrame(() => { + scanTimer = null; + if (!suppressingMutations) scan(); + }); +} + +const observer = new MutationObserver((mutations) => { + const relevant = mutations.some((m) => { + for (const n of m.addedNodes) { + if (n.nodeType !== 1) continue; + const el = /** @type {Element} */ (n); + if (el.classList?.contains("x-why-icon")) continue; + if (el.classList?.contains("x-why-tooltip")) continue; + if (el.closest?.(".x-why-icon")) continue; + return true; + } + for (const n of m.removedNodes) { + if (n.nodeType !== 1) continue; + const el = /** @type {Element} */ (n); + if (el.classList?.contains("x-why-icon")) continue; + return true; + } + return false; + }); + if (relevant) scheduleScan(); +}); + +function start() { + document.documentElement.setAttribute("data-x-why-ext", "1"); + console.info("[x-why] content script active"); + observer.observe(document.documentElement, { + childList: true, + subtree: true, + }); + scheduleScan(); + setTimeout(scheduleScan, 500); + setTimeout(scheduleScan, 1500); + setTimeout(scheduleScan, 3000); +} + +if (document.documentElement) start(); +else document.addEventListener("DOMContentLoaded", start); diff --git a/extensions/chrome-extension-x/inject.js b/extensions/chrome-extension-x/inject.js new file mode 100644 index 0000000..2dd9ea9 --- /dev/null +++ b/extensions/chrome-extension-x/inject.js @@ -0,0 +1,167 @@ +/** + * MAIN world: capture HomeTimeline (For You) payloads from fetch + XHR. + */ +(function () { + const SOURCE = "x-foryou-why"; + + function emitItems(items) { + if (!items.length) return; + window.postMessage({ source: SOURCE, type: "feed-items", items }, "*"); + } + + function isHomeTimelineUrl(url) { + const u = String(url || ""); + // GraphQL For You — exclude Following (HomeLatestTimeline) + if (/HomeLatestTimeline/i.test(u)) return false; + if (/HomeTimeline/i.test(u)) return true; + // REST-style home timeline (rare / older) + if (/\/2\/timeline\/home\.json/i.test(u)) return true; + return false; + } + + function unwrapTweet(result) { + if (!result || typeof result !== "object") return null; + if (result.__typename === "TweetWithVisibilityResults") { + return result.tweet || null; + } + if (result.legacy || result.rest_id) return result; + if (result.tweet) return unwrapTweet(result.tweet); + return null; + } + + function screenName(user) { + if (!user) return null; + return ( + user.core?.screen_name || + user.legacy?.screen_name || + null + ); + } + + function normalizeEntry(entry) { + const content = entry?.content; + if (!content || content.entryType !== "TimelineTimelineItem") return null; + const item = content.itemContent; + if (!item || item.__typename !== "TimelineTweet") return null; + + const tweet = unwrapTweet(item.tweet_results?.result); + if (!tweet?.rest_id && !tweet?.legacy) return null; + + const id = String(tweet.rest_id || tweet.legacy?.id_str || ""); + if (!id) return null; + + const cei = content.clientEventInfo || {}; + const timelinesDetails = cei.details?.timelinesDetails || {}; + const user = tweet.core?.user_results?.result || null; + const rel = user?.relationship_perspectives || {}; + const legacy = tweet.legacy || {}; + + return { + id, + injectionType: timelinesDetails.injectionType || null, + component: cei.component || null, + following: typeof rel.following === "boolean" ? rel.following : null, + followedBy: typeof rel.followed_by === "boolean" ? rel.followed_by : null, + authorHandle: screenName(user), + likes: legacy.favorite_count ?? null, + retweets: legacy.retweet_count ?? null, + replies: legacy.reply_count ?? null, + quotes: legacy.quote_count ?? null, + bookmarks: legacy.bookmark_count ?? null, + views: tweet.views?.count != null ? Number(tweet.views.count) : null, + promoted: Boolean(item.promotedMetadata) || + String(entry.entryId || "").startsWith("promoted-tweet"), + }; + } + + function collectEntries(body) { + const items = []; + const seen = new Set(); + + function take(entries) { + if (!Array.isArray(entries)) return; + for (const entry of entries) { + const item = normalizeEntry(entry); + if (!item || seen.has(item.id)) continue; + seen.add(item.id); + items.push(item); + } + } + + const urt = + body?.data?.home?.home_timeline_urt || + body?.data?.home?.homeTimelineUrt || + body?.timeline || + null; + + const instructions = urt?.instructions; + if (Array.isArray(instructions)) { + for (const instr of instructions) { + take(instr.entries); + if (instr.entry) take([instr.entry]); + } + } + + // REST home.json sometimes nests differently + take(body?.timeline?.instructions?.flatMap?.((i) => i.entries) || []); + + // Only keep For You–looking batches (skip if page is explicitly following) + const page = urt?.metadata?.scribeConfig?.page; + if (page && page !== "for_you") return []; + + return items; + } + + async function maybeCapture(text, url) { + try { + if (!isHomeTimelineUrl(url)) return; + const body = JSON.parse(text); + emitItems(collectEntries(body)); + } catch { + /* ignore */ + } + } + + const origFetch = window.fetch.bind(window); + window.fetch = async function (...args) { + const res = await origFetch(...args); + const req = args[0]; + const url = + typeof req === "string" + ? req + : req instanceof Request + ? req.url + : String(req?.url ?? ""); + try { + if (isHomeTimelineUrl(url)) { + const clone = res.clone(); + void clone.text().then((t) => maybeCapture(t, url)); + } + } catch { + /* ignore */ + } + return res; + }; + + const OrigXHR = window.XMLHttpRequest; + function PatchedXHR() { + const xhr = new OrigXHR(); + let url = ""; + const open = xhr.open; + xhr.open = function (method, u, ...rest) { + url = String(u || ""); + return open.call(xhr, method, u, ...rest); + }; + xhr.addEventListener("load", function () { + if (!isHomeTimelineUrl(url)) return; + try { + void maybeCapture(xhr.responseText, url); + } catch { + /* ignore */ + } + }); + return xhr; + } + PatchedXHR.prototype = OrigXHR.prototype; + window.XMLHttpRequest = PatchedXHR; +})(); diff --git a/extensions/chrome-extension-x/manifest.json b/extensions/chrome-extension-x/manifest.json new file mode 100644 index 0000000..79a5d52 --- /dev/null +++ b/extensions/chrome-extension-x/manifest.json @@ -0,0 +1,21 @@ +{ + "manifest_version": 3, + "name": "X For You Why", + "version": "0.1.0", + "description": "Hoverable why-info on X For You posts (injectionType, following, engagement).", + "host_permissions": ["https://x.com/*", "https://twitter.com/*"], + "content_scripts": [ + { + "matches": ["https://x.com/*", "https://twitter.com/*"], + "js": ["content.js"], + "css": ["styles.css"], + "run_at": "document_start" + }, + { + "matches": ["https://x.com/*", "https://twitter.com/*"], + "js": ["inject.js"], + "run_at": "document_start", + "world": "MAIN" + } + ] +} diff --git a/extensions/chrome-extension-x/styles.css b/extensions/chrome-extension-x/styles.css new file mode 100644 index 0000000..60134e0 --- /dev/null +++ b/extensions/chrome-extension-x/styles.css @@ -0,0 +1,49 @@ +.x-why-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + margin-left: 4px; + flex-shrink: 0; + border-radius: 999px; + border: 1px solid rgb(29, 155, 240); + color: rgb(29, 155, 240); + background: rgba(29, 155, 240, 0.12); + font: 700 12px/1 system-ui, -apple-system, sans-serif; + cursor: help; + user-select: none; + position: relative; + z-index: 30; + padding: 0; + vertical-align: middle; +} + +.x-why-icon:hover, +.x-why-icon:focus-visible { + color: #fff; + border-color: rgba(255, 255, 255, 0.7); + background: rgba(255, 255, 255, 0.08); +} + +/* Fixed to body so X feed stacking/overflow cannot clip it */ +.x-why-tooltip { + position: fixed; + min-width: 240px; + max-width: 340px; + padding: 8px 10px; + border-radius: 8px; + background: #1a1a1a; + color: #f4f4f4; + border: 1px solid rgba(255, 255, 255, 0.15); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45); + font: 12px/1.45 system-ui, -apple-system, sans-serif; + white-space: pre-wrap; + text-align: left; + pointer-events: none; + z-index: 2147483647; +} + +.x-why-tooltip[hidden] { + display: none !important; +} diff --git a/extensions/chrome-extension/content.js b/extensions/chrome-extension/content.js new file mode 100644 index 0000000..b13159c --- /dev/null +++ b/extensions/chrome-extension/content.js @@ -0,0 +1,546 @@ +/** + * Content script: inject info icons + show why on hover. + * + * Why source order: + * 1) feedContext from getFeed (if ChronoFair sets it) + * 2) enriched explanation (following ∩ reposters) via your bsky.app session + * 3) basic fallback from feed item (author / shown-as-repost) + */ + +const PDS = "https://bsky.social"; +const APPVIEW_PROXY = "did:web:api.bsky.app#bsky_appview"; +const MARK = "data-bsky-why-icon"; + +/** @type {Map} uri -> feed item meta + why */ +const byUri = new Map(); +/** @type {Map} path `/profile/x/post/y` -> uri */ +const byPath = new Map(); + +let followingCache = null; // Map did -> {did, handle} | Promise +let followingPromise = null; + +window.addEventListener("message", (event) => { + if (event.source !== window) return; + const data = event.data; + if (!data || data.source !== "bsky-chronofair-why") return; + if (data.type === "feed-items") { + for (const item of data.items) { + upsertItem(item); + } + scheduleScan(); + } +}); + +function upsertItem(item) { + const prev = byUri.get(item.uri) ?? {}; + const merged = { ...prev, ...item }; + if (!merged.why) merged.why = basicWhy(merged); + byUri.set(item.uri, merged); + + const path = uriToPath(item.uri, item.authorHandle); + if (path) byPath.set(path, item.uri); +} + +function uriToPath(uri, handle) { + // at://did:.../app.bsky.feed.post/rkey + const m = uri.match(/at:\/\/([^/]+)\/app\.bsky\.feed\.post\/([^/]+)/); + if (!m) return null; + const rkey = m[2]; + if (handle) return `/profile/${handle}/post/${rkey}`; + return `/profile/${m[1]}/post/${rkey}`; +} + +function basicWhy(item) { + if (item.feedContext) return String(item.feedContext); + const parts = []; + if (item.authorHandle) parts.push(`author @${item.authorHandle}`); + if (item.shownAsRepost && item.repostedByHandle) { + parts.push(`shown as repost by @${item.repostedByHandle}`); + } + if (!parts.length) return "Loading why…"; + return parts.join("; "); +} + +function parsePathKey(key) { + const m = String(key).match(/^\/profile\/([^/]+)\/post\/([^/]+)/); + if (!m) return null; + return { actor: decodeURIComponent(m[1]), rkey: m[2] }; +} + +async function resolveToAtUri(key, session) { + if (key.startsWith("at://")) return key; + const mapped = byPath.get(key); + if (mapped?.startsWith("at://")) return mapped; + + const parsed = parsePathKey(key); + if (!parsed) return null; + if (parsed.actor.startsWith("did:")) { + return `at://${parsed.actor}/app.bsky.feed.post/${parsed.rkey}`; + } + + // Resolve handle → did (public AppView is enough) + const url = new URL( + "https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle", + ); + url.searchParams.set("handle", parsed.actor); + const res = await fetch(url.toString()); + if (!res.ok) { + // fallback via authenticated getProfile + if (!session) return null; + const base = session.service?.replace(/\/$/, "") || PDS; + const p = new URL(`${base}/xrpc/app.bsky.actor.getProfile`); + p.searchParams.set("actor", parsed.actor); + const pr = await fetch(p, { headers: authHeaders(session.accessJwt) }); + if (!pr.ok) return null; + const profile = await pr.json(); + if (!profile.did) return null; + const uri = `at://${profile.did}/app.bsky.feed.post/${parsed.rkey}`; + byPath.set(key, uri); + return uri; + } + const body = await res.json(); + const uri = `at://${body.did}/app.bsky.feed.post/${parsed.rkey}`; + byPath.set(key, uri); + return uri; +} + +function getSession() { + try { + const raw = localStorage.getItem("BSKY_STORAGE"); + if (!raw) return null; + const parsed = JSON.parse(raw); + const currentDid = parsed?.session?.currentAccount?.did; + const accounts = parsed?.session?.accounts ?? []; + const account = + accounts.find((a) => a.did === currentDid) ?? accounts[0] ?? null; + if (!account?.accessJwt || !account?.did) return null; + return { + did: account.did, + handle: account.handle, + accessJwt: account.accessJwt, + service: account.service || PDS, + }; + } catch { + return null; + } +} + +function authHeaders(accessJwt) { + return { + authorization: `Bearer ${accessJwt}`, + "atproto-proxy": APPVIEW_PROXY, + accept: "application/json", + }; +} + +async function loadFollowing(session) { + if (followingCache) return followingCache; + if (followingPromise) return followingPromise; + + followingPromise = (async () => { + const map = new Map(); + let cursor; + const base = session.service?.replace(/\/$/, "") || PDS; + for (;;) { + const url = new URL(`${base}/xrpc/app.bsky.graph.getFollows`); + url.searchParams.set("actor", session.did); + url.searchParams.set("limit", "100"); + if (cursor) url.searchParams.set("cursor", cursor); + const res = await fetch(url, { headers: authHeaders(session.accessJwt) }); + if (!res.ok) throw new Error(`getFollows ${res.status}`); + const body = await res.json(); + for (const f of body.follows ?? []) { + map.set(f.did, { did: f.did, handle: f.handle }); + } + if (!body.cursor) break; + cursor = body.cursor; + } + followingCache = map; + return map; + })().finally(() => { + followingPromise = null; + }); + + return followingPromise; +} + +async function fetchFollowedReposters(session, postUri, following) { + const matched = []; + const seen = new Set(); + let cursor; + const base = session.service?.replace(/\/$/, "") || PDS; + + for (let page = 0; page < 3; page++) { + const url = new URL(`${base}/xrpc/app.bsky.feed.getRepostedBy`); + url.searchParams.set("uri", postUri); + url.searchParams.set("limit", "100"); + if (cursor) url.searchParams.set("cursor", cursor); + const res = await fetch(url, { headers: authHeaders(session.accessJwt) }); + if (!res.ok) break; + const body = await res.json(); + for (const actor of body.repostedBy ?? []) { + const f = following.get(actor.did); + if (f && !seen.has(f.did)) { + seen.add(f.did); + matched.push(f); + } + } + if (!body.cursor) break; + cursor = body.cursor; + } + return matched; +} + +function buildEnrichedWhy(item, following, repostByFollowed) { + if (item.feedContext) { + // Prefer explicit feedContext when ChronoFair sets a human-readable why + return String(item.feedContext); + } + const parts = []; + const authorFollowed = item.authorDid + ? following.has(item.authorDid) + : false; + if (item.authorHandle) { + parts.push( + authorFollowed + ? `author followed (@${item.authorHandle})` + : `author not in following (@${item.authorHandle})`, + ); + } + if (item.shownAsRepost && item.repostedByHandle) { + parts.push(`shown as repost by @${item.repostedByHandle}`); + } + if (repostByFollowed.length === 1) { + parts.push(`reposted by 1 followed: @${repostByFollowed[0].handle}`); + } else if (repostByFollowed.length > 1) { + const handles = repostByFollowed + .slice(0, 5) + .map((a) => `@${a.handle}`) + .join(", "); + const more = + repostByFollowed.length > 5 + ? ` (+${repostByFollowed.length - 5} more)` + : ""; + parts.push( + `reposted by ${repostByFollowed.length} followed: ${handles}${more}`, + ); + } + return parts.join("; ") || basicWhy(item); +} + +/** In-flight enrichments so parallel hovers share one result. */ +const enrichPromises = new Map(); + +async function enrichWhy(key) { + const existing = byUri.get(key); + if (existing?.enriched && existing.why && existing.why !== "Loading why…") { + return existing.why; + } + if (enrichPromises.has(key)) return enrichPromises.get(key); + + const run = (async () => { + const prev = byUri.get(key); + const session = getSession(); + let uri; + try { + uri = await resolveToAtUri(key, session); + } catch (e) { + const msg = `Could not resolve post URI (${String(e?.message || e)})`; + byUri.set(key, { ...(prev ?? {}), why: msg, enriched: true }); + return msg; + } + + if (!uri) { + const msg = + "Could not resolve post URI — are you on a /profile/…/post/… link?"; + byUri.set(key, { ...(prev ?? {}), why: msg, enriched: true }); + return msg; + } + + const item = { + ...(byUri.get(uri) ?? {}), + ...(prev ?? {}), + uri, + authorHandle: + byUri.get(uri)?.authorHandle || + prev?.authorHandle || + parsePathKey(key)?.actor || + null, + authorDid: + byUri.get(uri)?.authorDid || + uri.match(/^at:\/\/([^/]+)/)?.[1] || + null, + }; + + if (!session) { + item.why = basicWhy(item) + " (not logged in — limited why)"; + item.enriched = true; + byUri.set(uri, item); + byUri.set(key, item); + byPath.set(key, uri); + return item.why; + } + + try { + const following = await loadFollowing(session); + const repostByFollowed = await fetchFollowedReposters( + session, + uri, + following, + ); + item.why = buildEnrichedWhy(item, following, repostByFollowed); + } catch (e) { + item.why = `${basicWhy(item)} (enrichment failed: ${String(e?.message || e)})`; + } + item.enriched = true; + byUri.set(uri, item); + byUri.set(key, item); + byPath.set(key, uri); + return item.why; + })().finally(() => { + enrichPromises.delete(key); + }); + + enrichPromises.set(key, run); + return run; +} + +/** + * Stable DOM key: always the /profile/…/post/… path (never flip to at://). + * Flipping keys mid-hover was creating a second icon. + */ +function resolveKeyFromHref(href) { + try { + const u = new URL(href, location.origin); + const m = u.pathname.match(/^\/profile\/([^/]+)\/post\/([^/]+)/); + if (!m) return null; + const actor = decodeURIComponent(m[1]); + const rkey = m[2]; + return `/profile/${actor}/post/${rkey}`; + } catch { + return null; + } +} + +function findPostAnchors(root = document) { + return root.querySelectorAll?.('a[href*="/profile/"][href*="/post/"]') ?? []; +} + +function isTimestampLabel(text) { + // DOM often looks like "· 1d" (middle-dot + time) + const t = text + .replace(/^[·•.\u00b7]+\s*/u, "") + .trim() + .toLowerCase(); + if (!t) return false; + if (t === "now" || t === "maintenant") return true; + // en: 1d 2h | fr: 1j 2 h | "1 j" "3 sem" + return ( + /^\d+\s*[smhdwyj]$/i.test(t) || + /^\d+\s*(min|mins|h|hr|hrs|d|j|jour|jours|sem|wk|w|mo|m|y|an|ans)$/i.test( + t, + ) + ); +} + +function pickHeaderAnchor(anchorsForSamePost) { + let best = null; + for (const a of anchorsForSamePost) { + const text = (a.textContent || "").trim(); + // Prefer real timestamp links (aria-label is a full date) + const aria = (a.getAttribute("aria-label") || "").toLowerCase(); + if ( + isTimestampLabel(text) || + /\b(20\d{2}|am|pm|at)\b/.test(aria) || + a.hasAttribute("data-tooltip") + ) { + return a; + } + if (!best) best = a; + } + return best; +} + +/** Attribute match without CSS.escape (escape breaks `/profile/...` keys). */ +function findIconsByKey(key) { + return [...document.querySelectorAll(".bsky-why-icon")].filter( + (el) => el.getAttribute(MARK) === key, + ); +} + +function dedupeIconsForKey(key, keepNear = null) { + const icons = findIconsByKey(key); + if (icons.length <= 1) return icons[0] ?? null; + + let keep = null; + if (keepNear) { + keep = + icons.find( + (el) => + el.previousElementSibling === keepNear || + keepNear.parentElement?.contains(el), + ) ?? null; + } + if (!keep) keep = icons[0]; + + suppressingMutations = true; + for (const el of icons) { + if (el !== keep) el.remove(); + } + Promise.resolve().then(() => { + suppressingMutations = false; + }); + return keep; +} + +function ensureIcon(headerAnchor, key) { + // Dedupe by post key only (a wide "card" ancestor was wrapping the whole + // feed and blocked icons on every post after the first). + const existing = dedupeIconsForKey(key, headerAnchor); + if (existing) return false; + if (headerAnchor.nextElementSibling?.classList?.contains("bsky-why-icon")) { + return false; + } + if (headerAnchor.parentElement?.querySelector?.(":scope > .bsky-why-icon")) { + return false; + } + + if (!byUri.has(key)) { + const parsed = parsePathKey(key); + byUri.set(key, { + uri: key, + authorHandle: parsed?.actor ?? null, + why: "Hover for why", + }); + } + + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "bsky-why-icon"; + btn.setAttribute(MARK, key); + btn.setAttribute("aria-label", "Why is this in the feed?"); + // text node only — tooltip is a sibling-free child we manage carefully + const label = document.createTextNode("i"); + btn.appendChild(label); + + const tip = document.createElement("div"); + tip.className = "bsky-why-tooltip"; + tip.hidden = true; + tip.textContent = byUri.get(key)?.why ?? "Hover for why"; + btn.appendChild(tip); + + async function show() { + tip.hidden = false; + dedupeIconsForKey(key, headerAnchor); + const cached = byUri.get(key); + if (cached?.enriched && cached.why && cached.why !== "Loading why…") { + tip.textContent = cached.why; + return; + } + tip.textContent = "Loading why…"; + try { + const why = await enrichWhy(key); + tip.textContent = why; + for (const el of findIconsByKey(key)) { + const t = el.querySelector(".bsky-why-tooltip"); + if (t) t.textContent = why; + } + dedupeIconsForKey(key, headerAnchor); + } catch (e) { + tip.textContent = `Why failed: ${String(e?.message || e)}`; + } + } + function hide() { + tip.hidden = true; + } + + btn.addEventListener("mouseenter", show); + btn.addEventListener("focus", show); + btn.addEventListener("mouseleave", hide); + btn.addEventListener("blur", hide); + + suppressingMutations = true; + headerAnchor.insertAdjacentElement("afterend", btn); + dedupeIconsForKey(key, headerAnchor); + Promise.resolve().then(() => { + suppressingMutations = false; + }); + return true; +} + +function scan(root = document) { + /** @type {Map} */ + const groups = new Map(); + + for (const a of findPostAnchors(root)) { + const key = resolveKeyFromHref(a.getAttribute("href") || ""); + if (!key) continue; + // Only consider timestamp-like / post permalink anchors in headers + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(a); + } + + let added = 0; + for (const [key, anchors] of groups) { + dedupeIconsForKey(key); + const header = pickHeaderAnchor(anchors); + if (header && ensureIcon(header, key)) added += 1; + } + + if (added > 0 || groups.size > 0) { + console.debug( + `[bsky-why] posts=${groups.size} knownFeed=${byUri.size} iconsAdded=${added}`, + ); + } +} + +let scanTimer = null; +let suppressingMutations = false; + +function scheduleScan() { + if (suppressingMutations) return; + if (scanTimer) return; + scanTimer = requestAnimationFrame(() => { + scanTimer = null; + if (!suppressingMutations) scan(); + }); +} + +const observer = new MutationObserver((mutations) => { + // Ignore mutations that only touch our own icons/tooltips + const relevant = mutations.some((m) => { + for (const n of m.addedNodes) { + if (n.nodeType !== 1) continue; + const el = /** @type {Element} */ (n); + if (el.classList?.contains("bsky-why-icon")) continue; + if (el.classList?.contains("bsky-why-tooltip")) continue; + if (el.closest?.(".bsky-why-icon")) continue; + return true; + } + for (const n of m.removedNodes) { + if (n.nodeType !== 1) continue; + const el = /** @type {Element} */ (n); + if (el.classList?.contains("bsky-why-icon")) continue; + return true; + } + return false; + }); + if (relevant) scheduleScan(); +}); + +function start() { + document.documentElement.setAttribute("data-bsky-why-ext", "1"); + console.info("[bsky-why] content script active"); + observer.observe(document.documentElement, { + childList: true, + subtree: true, + }); + scheduleScan(); + // Re-scan a few times after load (virtualized feed mounts late) + setTimeout(scheduleScan, 500); + setTimeout(scheduleScan, 1500); + setTimeout(scheduleScan, 3000); +} + +if (document.documentElement) start(); +else document.addEventListener("DOMContentLoaded", start); diff --git a/extensions/chrome-extension/inject.js b/extensions/chrome-extension/inject.js new file mode 100644 index 0000000..43dd09b --- /dev/null +++ b/extensions/chrome-extension/inject.js @@ -0,0 +1,55 @@ +/** + * Runs in the page (MAIN world). Patches fetch to capture getFeed payloads. + */ +(function () { + const ORIG = window.fetch.bind(window); + + function emitItems(items) { + window.postMessage( + { source: "bsky-chronofair-why", type: "feed-items", items }, + "*", + ); + } + + function normalizeItem(item) { + if (!item?.post?.uri) return null; + const reasonType = item.reason?.$type ?? ""; + return { + uri: item.post.uri, + authorDid: item.post.author?.did ?? null, + authorHandle: item.post.author?.handle ?? null, + shownAsRepost: reasonType.includes("reasonRepost"), + repostedByDid: item.reason?.by?.did ?? null, + repostedByHandle: item.reason?.by?.handle ?? null, + feedContext: item.feedContext ?? null, + reqId: item.reqId ?? null, + }; + } + + async function maybeCapture(res, url) { + try { + if (!url.includes("app.bsky.feed.getFeed")) return; + const clone = res.clone(); + const body = await clone.json(); + const items = (body.feed ?? []) + .map(normalizeItem) + .filter(Boolean); + if (items.length) emitItems(items); + } catch { + /* ignore non-JSON / aborted */ + } + } + + window.fetch = async function (...args) { + const res = await ORIG(...args); + const req = args[0]; + const url = + typeof req === "string" + ? req + : req instanceof Request + ? req.url + : String(req?.url ?? ""); + void maybeCapture(res, url); + return res; + }; +})(); diff --git a/extensions/chrome-extension/manifest.json b/extensions/chrome-extension/manifest.json new file mode 100644 index 0000000..1b93e1a --- /dev/null +++ b/extensions/chrome-extension/manifest.json @@ -0,0 +1,27 @@ +{ + "manifest_version": 3, + "name": "Bluesky ChronoFair Why", + "version": "0.1.0", + "description": "Adds a hoverable why-info icon on Bluesky feed posts (ChronoFair / feedContext).", + "permissions": ["storage"], + "host_permissions": [ + "https://bsky.app/*", + "https://bsky.social/*", + "https://public.api.bsky.app/*", + "https://*.bsky.network/*" + ], + "content_scripts": [ + { + "matches": ["https://bsky.app/*"], + "js": ["content.js"], + "css": ["styles.css"], + "run_at": "document_start" + }, + { + "matches": ["https://bsky.app/*"], + "js": ["inject.js"], + "run_at": "document_start", + "world": "MAIN" + } + ] +} diff --git a/extensions/chrome-extension/styles.css b/extensions/chrome-extension/styles.css new file mode 100644 index 0000000..983da4f --- /dev/null +++ b/extensions/chrome-extension/styles.css @@ -0,0 +1,49 @@ +.bsky-why-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + margin-left: 4px; + flex-shrink: 0; + border-radius: 999px; + border: 1px solid rgb(32, 139, 254); + color: rgb(32, 139, 254); + background: rgba(32, 139, 254, 0.12); + font: 700 12px/1 system-ui, -apple-system, sans-serif; + cursor: help; + user-select: none; + position: relative; + z-index: 30; + padding: 0; +} + +.bsky-why-icon:hover, +.bsky-why-icon:focus-visible { + color: #fff; + border-color: rgba(255, 255, 255, 0.7); + background: rgba(255, 255, 255, 0.08); +} + +.bsky-why-tooltip { + position: absolute; + right: 0; + top: calc(100% + 6px); + min-width: 220px; + max-width: 320px; + padding: 8px 10px; + border-radius: 8px; + background: #1a1a1a; + color: #f4f4f4; + border: 1px solid rgba(255, 255, 255, 0.15); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45); + font: 12px/1.4 system-ui, -apple-system, sans-serif; + white-space: normal; + text-align: left; + pointer-events: none; + z-index: 9999; +} + +.bsky-why-tooltip[hidden] { + display: none !important; +}