Files
2026-07-17 16:57:55 +02:00

454 lines
18 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Phenocheck – X.com content script
// Country comes from X's "Account based in" (AboutAccountQuery), fetched in background.js
const PC = {
enabled: false,
cache: {}, // handle -> { country, phenos } | undefined
observer: null,
btnObserver: null,
IMG_BASE: chrome.runtime.getURL('images/phenotypes/'),
};
// ─── Per-handle phenotype overrides ─────────────────────────────────
// Maps handle (lowercase) → { imgSrc, name }
const HANDLE_OVERRIDES = {
'cobardeeres10': {
imgSrc: chrome.runtime.getURL('images/phenotypes/custom/cobardeeres10.png'),
name: 'Eluservo',
},
};
// ─── Country → flag emoji ────────────────────────────────────────────
const COUNTRY_ISO = {
'spain':'ES','france':'FR','germany':'DE','italy':'IT','portugal':'PT',
'united kingdom':'GB','united states':'US','canada':'CA','australia':'AU',
'new zealand':'NZ','ireland':'IE','netherlands':'NL','belgium':'BE',
'sweden':'SE','norway':'NO','denmark':'DK','finland':'FI','poland':'PL',
'czech republic':'CZ','czechia':'CZ','austria':'AT','switzerland':'CH',
'russia':'RU','ukraine':'UA','turkey':'TR','greece':'GR','hungary':'HU',
'romania':'RO','serbia':'RS','croatia':'HR','slovakia':'SK','slovenia':'SI',
'bulgaria':'BG','albania':'AL','bosnia and herzegovina':'BA',
'north macedonia':'MK','moldova':'MD','belarus':'BY','estonia':'EE',
'latvia':'LV','lithuania':'LT','iceland':'IS','luxembourg':'LU',
'malta':'MT','cyprus':'CY','mexico':'MX','argentina':'AR','brazil':'BR',
'colombia':'CO','chile':'CL','peru':'PE','venezuela':'VE','ecuador':'EC',
'bolivia':'BO','paraguay':'PY','uruguay':'UY','cuba':'CU',
'costa rica':'CR','panama':'PA','honduras':'HN','guatemala':'GT',
'el salvador':'SV','nicaragua':'NI','dominican republic':'DO',
'puerto rico':'PR','japan':'JP','china':'CN','south korea':'KR',
'india':'IN','pakistan':'PK','indonesia':'ID','malaysia':'MY',
'thailand':'TH','vietnam':'VN','philippines':'PH','singapore':'SG',
'bangladesh':'BD','iran':'IR','iraq':'IQ','saudi arabia':'SA',
'israel':'IL','egypt':'EG','south africa':'ZA','nigeria':'NG',
'kenya':'KE','morocco':'MA','algeria':'DZ','tunisia':'TN',
'ethiopia':'ET','ghana':'GH','tanzania':'TZ','senegal':'SN',
'united arab emirates':'AE','qatar':'QA','kuwait':'KW','jordan':'JO',
'lebanon':'LB','syria':'SY','afghanistan':'AF','nepal':'NP',
'sri lanka':'LK','myanmar':'MM','cambodia':'KH','taiwan':'TW',
'hong kong':'HK','ukraine':'UA',
};
function countryFlag(rawCountry) {
if (!rawCountry) return '';
const code = COUNTRY_ISO[rawCountry.toLowerCase().trim()];
if (!code) return '';
return String.fromCodePoint(...[...code].map(c => 0x1F1E6 + c.charCodeAt(0) - 65));
}
// ─── Country → phenotype lookup ─────────────────────────────────────
function resolveCountry(rawCountry) {
if (!rawCountry || typeof rawCountry !== 'string') return null;
const s = rawCountry.trim().toLowerCase();
if (PHENOCHECK.countryLookup[s]) return s;
if (PHENOCHECK.aliases[s]) return PHENOCHECK.aliases[s];
// Try substring against known country names
for (const country of Object.keys(PHENOCHECK.countryLookup)) {
if (s.includes(country)) return country;
}
return null;
}
function pickPhenotype(phenos, handle) {
if (!phenos || !phenos.length) return null;
let hash = 0;
for (let i = 0; i < handle.length; i++) hash = ((hash << 5) - hash + handle.charCodeAt(i)) | 0;
return phenos[Math.abs(hash) % phenos.length];
}
function pickGender(handle) {
let hash = 0;
for (let i = 0; i < handle.length; i++) hash = ((hash << 3) + handle.charCodeAt(i) * 31) | 0;
return Math.abs(hash) % 2 === 0 ? 'm' : 'f';
}
let _allPhenos = null;
function randomPheno() {
if (!_allPhenos) {
_allPhenos = [];
for (const list of Object.values(PHENOCHECK.countryLookup)) _allPhenos.push(...list);
}
return _allPhenos[Math.floor(Math.random() * _allPhenos.length)];
}
// ─── Button ─────────────────────────────────────────────────────────
const SKULL_SVG = `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="width:26px;height:26px;min-width:26px;" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M12 2C7.58 2 4 5.58 4 10c0 3.07 1.67 5.76 4.16 7.22L8 20a1 1 0 001 1h6a1 1 0 001-1l-.16-2.78C18.33 15.76 20 13.07 20 10c0-4.42-3.58-8-8-8zM9 10a2 2 0 110 .001A2 2 0 019 10zm6 0a2 2 0 110 .001A2 2 0 0115 10zm-3.5 3a1.5 1.75 0 110 .001A1.5 1.75 0 0111.5 13zM9.5 20v-2h1.25v2H9.5zm3.75 0v-2H14.5v2h-1.25z"/>
</svg>`;
function createButton() {
const el = document.createElement('div');
el.id = 'phenocheck-btn';
el.setAttribute('role', 'button');
el.setAttribute('tabindex', '0');
el.setAttribute('aria-label', 'Phenocheck');
const inner = document.createElement('div');
inner.className = 'phenocheck-inner';
inner.innerHTML = SKULL_SVG + '<span>Phenocheck</span>';
el.appendChild(inner);
inner.addEventListener('mouseenter', () => { if (!PC.enabled) inner.style.background = 'rgba(120,86,255,0.1)'; });
inner.addEventListener('mouseleave', () => { if (!PC.enabled) inner.style.background = ''; });
el.addEventListener('click', toggleEnabled);
el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleEnabled(); } });
return el;
}
function injectButton() {
if (document.getElementById('phenocheck-btn')) return;
const homeLink = document.querySelector('[data-testid="AppTabBar_Home_Link"]');
if (!homeLink) return;
const nav = homeLink.closest('nav');
if (!nav) return;
const btn = createButton();
const chatLink = nav.querySelector('[data-testid="AppTabBar_DirectMessage_Link"]');
if (chatLink) {
nav.insertBefore(btn, chatLink);
} else {
const grokLink = nav.querySelector('a[href="/i/grok"], a[aria-label="Grok"]');
if (grokLink) nav.insertBefore(btn, grokLink);
else nav.appendChild(btn);
}
}
function startButtonObserver() {
if (PC.btnObserver) return;
PC.btnObserver = new MutationObserver(injectButton);
PC.btnObserver.observe(document.body, { childList: true, subtree: true });
injectButton();
}
// ─── Toggle ─────────────────────────────────────────────────────────
function toggleEnabled() {
PC.enabled = !PC.enabled;
const inner = document.querySelector('#phenocheck-btn .phenocheck-inner');
if (inner) {
inner.style.color = PC.enabled ? '#7856FF' : '';
inner.style.background = PC.enabled ? 'rgba(120,86,255,0.1)' : '';
}
if (PC.enabled) {
processAllVisibleTweets();
startTweetObserver();
} else {
stopTweetObserver();
removeAllBadges();
}
}
// ─── Handle extraction ──────────────────────────────────────────────
function getTweetHandle(article) {
// Prefer the author handle from User-Name block (handles quote tweets correctly)
const nameBlock = article.querySelector('[data-testid="User-Name"]');
if (nameBlock) {
for (const a of nameBlock.querySelectorAll('a[href^="/"][role="link"]')) {
const m = a.getAttribute('href')?.match(/^\/([A-Za-z0-9_]+)$/);
if (m && !isReserved(m[1])) return m[1];
}
}
for (const a of article.querySelectorAll('a[href^="/"][role="link"]')) {
const m = a.getAttribute('href')?.match(/^\/([A-Za-z0-9_]+)$/);
if (m && !isReserved(m[1])) return m[1];
}
return null;
}
function isReserved(h) {
return ['home', 'explore', 'notifications', 'messages', 'search', 'i', 'settings', 'compose'].includes(h.toLowerCase());
}
// ─── Tweet processing ───────────────────────────────────────────────
async function processTweet(article) {
if (!PC.enabled) return;
if (article.dataset.phenocheck === 'pending' || article.dataset.phenocheck === 'done') return;
if (article.querySelector('.phenocheck-badge') && article.dataset.phenocheck === 'done') return;
const handle = getTweetHandle(article);
if (!handle) return;
const key = handle.toLowerCase();
article.dataset.phenocheck = 'pending';
let entry = PC.cache[key];
if (entry === undefined) {
const resp = await fetchBasedIn(handle);
if (!PC.enabled) { delete article.dataset.phenocheck; return; }
if (!resp || resp.status === 'unavailable') {
// Rate-limited / network error: show placeholder, allow later retry
injectResidence(article, '?');
if (article.querySelector('.phenocheck-badge')) return;
const badge = buildUnavailableBadge();
injectBadge(article, badge);
delete article.dataset.phenocheck; // retry on next pass
return;
}
const country = resolveCountry(resp.country);
const phenos = country ? PHENOCHECK.countryLookup[country] : null;
entry = { rawCountry: resp.country, country, phenos };
PC.cache[key] = entry;
}
if (!PC.enabled) { delete article.dataset.phenocheck; return; }
injectResidence(article, residenceLabel(entry));
if (article.querySelector('.phenocheck-badge')) { article.dataset.phenocheck = 'done'; return; }
const badge = buildBadge(handle, entry);
injectBadge(article, badge);
article.dataset.phenocheck = 'done';
}
// Text "Reside en: <country>" placed right after the tweet date.
function residenceLabel(entry) {
if (entry.rawCountry) return entry.rawCountry;
if (entry.country) return entry.country.charAt(0).toUpperCase() + entry.country.slice(1);
return '?';
}
function injectResidence(article, label) {
if (!label) return;
const nameBlock = article.querySelector('[data-testid="User-Name"]');
if (!nameBlock) return;
let span = nameBlock.querySelector('.pc-residence');
const flag = countryFlag(label);
const text = 'Reside en: ' + label + (flag ? ' ' + flag : '');
if (span) { span.textContent = text; return; }
span = document.createElement('span');
span.className = 'pc-residence';
span.textContent = text;
const timeEl = nameBlock.querySelector('time');
if (timeEl) {
// Normal feed tweet: insert right after the date link
const anchor = timeEl.closest('a') || timeEl.parentElement;
if (anchor?.parentElement) {
anchor.parentElement.insertBefore(span, anchor.nextSibling);
return;
}
}
// Detail view: no inline time — append at end of the last flex row in User-Name
const rows = nameBlock.querySelectorAll(':scope > div');
const lastRow = rows[rows.length - 1] || nameBlock;
lastRow.appendChild(span);
}
function fetchBasedIn(handle) {
return new Promise((resolve) => {
try {
chrome.runtime.sendMessage({ type: 'FETCH_BASED_IN', handle }, (resp) => {
if (chrome.runtime.lastError) { resolve({ status: 'unavailable' }); return; }
resolve(resp ?? { status: 'unavailable' });
});
} catch {
resolve({ status: 'unavailable' });
}
});
}
// ─── Badge ──────────────────────────────────────────────────────────
function buildBadge(handle, { rawCountry, country, phenos }) {
// Per-handle override takes priority
const override = HANDLE_OVERRIDES[handle.toLowerCase()];
if (override) {
return buildOverrideBadge(override, rawCountry, country);
}
// No recognized phenotype data → treat as unavailable placeholder
if (!phenos || phenos.length === 0) {
return buildUnavailableBadge(rawCountry);
}
const wrap = document.createElement('div');
wrap.className = 'phenocheck-badge';
const pheno = pickPhenotype(phenos, handle);
const gender = pickGender(handle);
const imgSrc = PC.IMG_BASE + pheno.img + gender + '.jpg';
const imgAlt = PC.IMG_BASE + pheno.img + (gender === 'm' ? 'f' : 'm') + '.jpg';
const locLabel = country ? country.charAt(0).toUpperCase() + country.slice(1) : '';
wrap.innerHTML = `
<img class="pc-thumb" src="${imgSrc}" alt="${pheno.name}">
<div class="pc-name">${pheno.name}</div>
<div class="pc-tooltip">
<img src="${imgSrc}" alt="${pheno.name}">
<b>${pheno.name}</b>
${locLabel ? `<span>${locLabel}</span>` : ''}
</div>
`;
const thumb = wrap.querySelector('img.pc-thumb');
if (thumb) thumb.onerror = () => { thumb.src = imgAlt; thumb.onerror = null; };
wrap.addEventListener('mouseenter', () => positionTooltip(wrap));
return wrap;
}
function buildOverrideBadge({ imgSrc, name }, rawCountry, country) {
const wrap = document.createElement('div');
wrap.className = 'phenocheck-badge';
const locLabel = country ? country.charAt(0).toUpperCase() + country.slice(1) : (rawCountry || '');
wrap.innerHTML = `
<img class="pc-thumb" src="${imgSrc}" alt="${name}">
<div class="pc-name">${name}</div>
<div class="pc-tooltip">
<img src="${imgSrc}" alt="${name}">
<b>${name}</b>
${locLabel ? `<span>${locLabel}</span>` : ''}
</div>
`;
wrap.addEventListener('mouseenter', () => positionTooltip(wrap));
return wrap;
}
function buildUnavailableBadge(rawCountry) {
const wrap = document.createElement('div');
wrap.className = 'phenocheck-badge pc-unavailable';
const pheno = randomPheno();
const gender = Math.random() < 0.5 ? 'm' : 'f';
const imgSrc = PC.IMG_BASE + pheno.img + gender + '.jpg';
wrap.innerHTML = `
<div class="pc-thumb-wrap">
<img class="pc-thumb" src="${imgSrc}" alt="Unavailable">
<div class="pc-q">?</div>
</div>
<div class="pc-name">Unavailable</div>
`;
if (rawCountry) wrap.title = rawCountry;
return wrap;
}
function positionTooltip(badge) {
const tip = badge.querySelector('.pc-tooltip');
if (!tip) return;
const r = badge.getBoundingClientRect();
tip.style.left = (r.right + 8) + 'px';
tip.style.top = Math.max(4, r.top - 20) + 'px';
}
const BADGE_TOTAL_H = 62; // approx: 44px thumb + name + padding
function isDetailViewTweet(article) {
const avatar = article.querySelector('[data-testid="Tweet-User-Avatar"]');
if (!avatar) return false;
const mainRow = avatar.parentElement?.parentElement;
if (!mainRow) return false;
const rightCol = mainRow.children[1];
const tweetText = article.querySelector('[data-testid="tweetText"]');
// Detail view: mainRow is very short (just avatar+username row) AND text is NOT inside rightCol
return mainRow.offsetHeight < 60 && !rightCol?.contains(tweetText);
}
function injectBadge(article, badge) {
const avatar = article.querySelector('[data-testid="Tweet-User-Avatar"]');
if (avatar) {
const leftCol = avatar.parentElement;
const mainRow = leftCol.parentElement;
if (isDetailViewTweet(article)) {
// Detail/focused tweet: text is full-width below the avatar row.
// Place badge as small overlay on bottom-right of avatar to avoid overlapping text.
badge.classList.add('pc-detail');
avatar.appendChild(badge);
return;
}
// Normal feed tweet: badge goes below avatar in leftCol (same stacking context as thread line).
const avatarH = avatar.offsetHeight;
badge.style.top = (avatarH + 4) + 'px';
leftCol.appendChild(badge);
// Ensure leftCol (and thus the article) is tall enough so overflow:hidden on article doesn't clip the badge.
const neededH = avatarH + 4 + BADGE_TOTAL_H;
if (leftCol.offsetHeight < neededH) {
leftCol.style.minHeight = neededH + 'px';
}
return;
}
article.style.position = 'relative';
badge.classList.add('pc-corner');
article.appendChild(badge);
}
function processAllVisibleTweets() {
document.querySelectorAll('article[data-testid="tweet"]').forEach(a => processTweet(a));
}
function removeAllBadges() {
document.querySelectorAll('.phenocheck-badge').forEach(el => el.remove());
document.querySelectorAll('.pc-residence').forEach(el => el.remove());
// Remove minHeight injected on leftCols for short tweets
document.querySelectorAll('article[data-testid="tweet"] [data-testid="Tweet-User-Avatar"]').forEach(avatar => {
if (avatar.parentElement) avatar.parentElement.style.minHeight = '';
});
document.querySelectorAll('article[data-phenocheck]').forEach(a => delete a.dataset.phenocheck);
}
// ─── Tweet observer ─────────────────────────────────────────────────
function startTweetObserver() {
if (PC.observer) return;
PC.observer = new MutationObserver(mutations => {
if (!PC.enabled) return;
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node.nodeType !== 1) continue;
if (node.matches?.('article[data-testid="tweet"]')) processTweet(node);
else node.querySelectorAll?.('article[data-testid="tweet"]').forEach(a => processTweet(a));
}
}
});
PC.observer.observe(document.body, { childList: true, subtree: true });
}
function stopTweetObserver() {
PC.observer?.disconnect();
PC.observer = null;
}
// ─── Init ───────────────────────────────────────────────────────────
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', startButtonObserver);
} else {
startButtonObserver();
}
let lastPath = location.pathname;
new MutationObserver(() => {
if (location.pathname !== lastPath) {
lastPath = location.pathname;
setTimeout(injectButton, 800);
}
}).observe(document.body, { childList: true, subtree: true });