Instantly share code, notes, and snippets.
Created
November 12, 2026 06:43
-
Star
0
(0)
You must be signed in to star a gist -
Fork
0
(0)
You must be signed in to fork a gist
-
-
Save pdxmph/f229429d549d69cc4753bb7cd6041a34 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==UserScript== | |
| // @name SocialSpec tabs for Mastodon | |
| // @namespace https://mike.puddingtime.org | |
| // @version 0.1.0 | |
| // @description Adds Blog, About, Following and Contact tabs to Mastodon profiles whose website publishes a feed or SocialSpec files (socialspec.org). | |
| // @author Mike Hall | |
| // @homepageURL https://socialspec.org | |
| // @downloadURL https://mike.puddingtime.org/userscripts/socialspec-mastodon.user.js | |
| // @updateURL https://mike.puddingtime.org/userscripts/socialspec-mastodon.user.js | |
| // @match https://hachyderm.io/* | |
| // @match https://mastodon.social/* | |
| // @grant GM_xmlhttpRequest | |
| // @grant GM.xmlHttpRequest | |
| // @grant GM_getValue | |
| // @grant GM.getValue | |
| // @grant GM_setValue | |
| // @grant GM.setValue | |
| // @grant GM_addStyle | |
| // @connect * | |
| // @require https://cdn.jsdelivr.net/npm/marked@12.0.2/marked.min.js | |
| // @require https://cdn.jsdelivr.net/npm/dompurify@3.1.6/dist/purify.min.js | |
| // @run-at document-idle | |
| // ==/UserScript== | |
| /* | |
| * How it works | |
| * | |
| * 1. On a profile page, ask your own instance for the account | |
| * (/api/v1/accounts/lookup) and collect the links in its profile fields | |
| * and bio. Only links to a site root count: a link to github.com/you is | |
| * not your site, and github.com's /.well-known files are not yours. | |
| * 2. Probe each site for /.well-known/about.md, following.opml and | |
| * contact.vcf, plus a feed (/feed.xml, /feed.json, then the homepage's | |
| * <link rel="alternate">). Responses are sniffed, because plenty of | |
| * sites answer every path with a 200 and an HTML page. | |
| * 3. If anything turns up, add tabs to the profile's tab list. A link | |
| * counts as verified when Mastodon verified it (rel=me) or when the | |
| * site's contact.vcf points back at the account. | |
| * | |
| * Everything fetched is someone else's content rendered inside a page that | |
| * holds your Mastodon session, so all HTML goes through DOMPurify, and | |
| * images are fetched as blobs (Mastodon's CSP blocks remote images). | |
| * | |
| * To use it on another instance, add the instance to the script's | |
| * "user matches" in your userscript manager, or add an @match line. | |
| */ | |
| (function () { | |
| 'use strict'; | |
| const CONFIG = { | |
| cacheHours: 6, | |
| maxOrigins: 4, | |
| feedItems: 15, | |
| maxImages: 12, | |
| // Set to your reader's subscribe URL to get "subscribe" links, e.g. | |
| // 'https://feedbin.com/?subscribe={url}' or 'feed:{url}'. | |
| subscribeUrl: null, | |
| // Show tabs for a site that has only a feed and no /.well-known files. | |
| feedOnly: true, | |
| }; | |
| const WELL_KNOWN = { | |
| about: '/.well-known/about.md', | |
| following: '/.well-known/following.opml', | |
| contact: '/.well-known/contact.vcf', | |
| }; | |
| const TABS = [ | |
| { kind: 'feed', label: 'Blog' }, | |
| { kind: 'about', label: 'About' }, | |
| { kind: 'following', label: 'Following' }, | |
| { kind: 'contact', label: 'Contact' }, | |
| ]; | |
| // ---- userscript manager compatibility (Tampermonkey, Violentmonkey, Userscripts) ---- | |
| const gm = typeof GM !== 'undefined' ? GM : {}; | |
| const xhr = typeof GM_xmlhttpRequest === 'function' ? GM_xmlhttpRequest : gm.xmlHttpRequest; | |
| const store = { | |
| async get(key) { | |
| try { | |
| const v = typeof GM_getValue === 'function' ? GM_getValue(key) : await gm.getValue(key); | |
| return v ? JSON.parse(v) : null; | |
| } catch { return null; } | |
| }, | |
| async set(key, value) { | |
| try { | |
| const v = JSON.stringify(value); | |
| if (typeof GM_setValue === 'function') GM_setValue(key, v); | |
| else await gm.setValue(key, v); | |
| } catch { /* cache is best effort */ } | |
| }, | |
| }; | |
| // Mastodon's CSP blocks plain <style> tags. Constructed stylesheets are | |
| // CSSOM, which CSP allows, so they work where GM_addStyle is missing. | |
| function addStyle(css) { | |
| if (typeof GM_addStyle === 'function') return GM_addStyle(css); | |
| if (typeof gm.addStyle === 'function') return gm.addStyle(css); | |
| const sheet = new CSSStyleSheet(); | |
| sheet.replaceSync(css); | |
| document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]; | |
| } | |
| function request(url, { blob = false } = {}) { | |
| return new Promise((resolve) => { | |
| const done = (r) => resolve({ | |
| status: r?.status || 0, | |
| text: blob ? null : r?.responseText ?? null, | |
| blob: blob ? r?.response ?? null : null, | |
| finalUrl: r?.finalUrl || url, | |
| contentType: /content-type:\s*([^\r\n;]+)/i.exec(r?.responseHeaders || '')?.[1]?.toLowerCase() || '', | |
| }); | |
| try { | |
| xhr({ | |
| method: 'GET', url, timeout: 10000, | |
| responseType: blob ? 'blob' : undefined, | |
| onload: done, onerror: () => done(null), ontimeout: () => done(null), | |
| }); | |
| } catch { done(null); } | |
| }); | |
| } | |
| // ---- finding the person's sites ---- | |
| function acctFromPath() { | |
| const m = location.pathname.match(/^\/@([^/]+)/); | |
| return m ? decodeURIComponent(m[1]) : null; | |
| } | |
| function accessToken() { | |
| try { | |
| return JSON.parse(document.getElementById('initial-state')?.textContent || '{}').meta?.access_token || null; | |
| } catch { return null; } | |
| } | |
| async function lookupAccount(acct) { | |
| const token = accessToken(); | |
| const res = await fetch(`/api/v1/accounts/lookup?acct=${encodeURIComponent(acct)}`, { | |
| headers: token ? { Authorization: `Bearer ${token}` } : {}, | |
| }); | |
| return res.ok ? res.json() : null; | |
| } | |
| function htmlLinks(html, skip) { | |
| const doc = new DOMParser().parseFromString(html || '', 'text/html'); | |
| return [...doc.querySelectorAll('a[href]')] | |
| .filter((a) => !(skip && a.matches(skip))) | |
| .map((a) => a.getAttribute('href')); | |
| } | |
| // Site roots linked from the profile, verified ones first. | |
| function siteOrigins(account) { | |
| const found = new Map(); | |
| const add = (href, verified) => { | |
| let u; | |
| try { u = new URL(href); } catch { return; } | |
| if (!/^https?:$/.test(u.protocol) || u.pathname.replace(/\/+$/, '') !== '' || u.search) return; | |
| found.set(u.origin, found.get(u.origin) || verified); | |
| }; | |
| for (const f of account.fields || []) { | |
| for (const href of htmlLinks(f.value)) add(href, !!f.verified_at); | |
| } | |
| for (const href of htmlLinks(account.note, '.mention, .hashtag')) add(href, false); | |
| return [...found] | |
| .map(([origin, verified]) => ({ origin, verified })) | |
| .sort((a, b) => b.verified - a.verified) | |
| .slice(0, CONFIG.maxOrigins); | |
| } | |
| // ---- probing a site ---- | |
| const looksHtml = (r) => r.contentType.includes('html') || /^\s*</.test(r.text || ''); | |
| function xmlRoot(text) { | |
| const doc = new DOMParser().parseFromString(text, 'application/xml'); | |
| return doc.querySelector('parsererror') ? null : doc; | |
| } | |
| function feedKind(text) { | |
| const t = (text || '').trimStart(); | |
| if (t.startsWith('{')) { | |
| try { return /jsonfeed/.test(JSON.parse(t).version || '') ? 'json' : null; } catch { return null; } | |
| } | |
| if (!t.startsWith('<')) return null; | |
| const name = xmlRoot(t)?.documentElement.localName; | |
| return ['rss', 'feed', 'RDF'].includes(name) ? 'xml' : null; | |
| } | |
| async function findFeed(origin) { | |
| for (const path of ['/feed.xml', '/feed.json']) { | |
| const r = await request(origin + path); | |
| if (r.status === 200 && feedKind(r.text)) return r.finalUrl; | |
| } | |
| const home = await request(origin + '/'); | |
| if (home.status !== 200 || !home.text) return null; | |
| const doc = new DOMParser().parseFromString(home.text, 'text/html'); | |
| const link = [...doc.querySelectorAll('link[rel~="alternate"][href]')] | |
| .find((l) => /rss|atom|feed\+json|application\/json/i.test(l.type || '')); | |
| return link ? new URL(link.getAttribute('href'), home.finalUrl).href : null; | |
| } | |
| async function probe(origin) { | |
| const key = `probe:${origin}`; | |
| const cached = await store.get(key); | |
| if (cached && Date.now() - cached.at < CONFIG.cacheHours * 36e5) return cached.data; | |
| const [about, following, contact, feedUrl] = await Promise.all([ | |
| request(origin + WELL_KNOWN.about), | |
| request(origin + WELL_KNOWN.following), | |
| request(origin + WELL_KNOWN.contact), | |
| findFeed(origin), | |
| ]); | |
| const data = { origin, feedUrl }; | |
| if (about.status === 200 && about.text && !looksHtml(about)) { | |
| data.about = about.text; | |
| data.aboutUrl = about.finalUrl; | |
| } | |
| if (following.status === 200 && xmlRoot(following.text || '')?.documentElement.localName === 'opml') { | |
| data.following = following.text; | |
| } | |
| if (contact.status === 200 && /^\s*BEGIN:VCARD/i.test(contact.text || '')) { | |
| data.contact = contact.text; | |
| } | |
| await store.set(key, { at: Date.now(), data }); | |
| return data; | |
| } | |
| const hasWellKnown = (d) => !!(d.about || d.following || d.contact); | |
| async function loadProfile(acct) { | |
| const account = await lookupAccount(acct); | |
| if (!account) return null; | |
| const origins = siteOrigins(account); | |
| const results = await Promise.all(origins.map((o) => probe(o.origin).then((d) => ({ ...o, data: d })))); | |
| const pick = results.find((r) => hasWellKnown(r.data)) || (CONFIG.feedOnly && results.find((r) => r.data.feedUrl)); | |
| if (!pick) return null; | |
| const { data } = pick; | |
| const backlink = data.contact && [account.url, `@${account.acct}`] | |
| .some((s) => data.contact.toLowerCase().includes(s.toLowerCase())); | |
| return { ...data, account, verified: pick.verified, backlink: !!backlink }; | |
| } | |
| // ---- parsing ---- | |
| function parseFrontmatter(md) { | |
| const m = md.match(/^?---\r?\n([\s\S]*?)\r?\n---\r?\n?/); | |
| if (!m) return { meta: {}, body: md }; | |
| const meta = {}; | |
| for (const line of m[1].split(/\r?\n/)) { | |
| const kv = line.match(/^([\w-]+):\s*(.*)$/); | |
| if (!kv) continue; | |
| let v = kv[2].trim(); | |
| if (/^".*"$/.test(v)) { try { v = JSON.parse(v); } catch { v = v.slice(1, -1); } } | |
| else if (/^'.*'$/.test(v)) v = v.slice(1, -1); | |
| meta[kv[1]] = v; | |
| } | |
| return { meta, body: md.slice(m[0].length) }; | |
| } | |
| function parseVcard(text) { | |
| const unescape = (v) => v.replace(/\\n/gi, '\n').replace(/\\([,;\\])/g, '$1'); | |
| return text.replace(/\r\n/g, '\n').replace(/\n[ \t]/g, '').split('\n').flatMap((line) => { | |
| const i = line.indexOf(':'); | |
| if (i < 0) return []; | |
| const [nameGroup, ...rawParams] = line.slice(0, i).split(';'); | |
| const params = {}; | |
| for (const p of rawParams) { | |
| const [k, v = ''] = p.split('='); | |
| params[k.toUpperCase()] = v.replace(/^"|"$/g, ''); | |
| } | |
| return [{ name: nameGroup.split('.').pop().toUpperCase(), params, raw: line.slice(i + 1), value: unescape(line.slice(i + 1)) }]; | |
| }); | |
| } | |
| function plainText(html, max = 280) { | |
| const text = new DOMParser().parseFromString(html || '', 'text/html').body.textContent.replace(/\s+/g, ' ').trim(); | |
| return text.length > max ? text.slice(0, max - 1).trimEnd() + '…' : text; | |
| } | |
| function parseFeed(text, baseUrl) { | |
| const abs = (u) => { try { return new URL(u, baseUrl).href; } catch { return null; } }; | |
| if (feedKind(text) === 'json') { | |
| const j = JSON.parse(text); | |
| return { | |
| title: j.title, home: abs(j.home_page_url || ''), | |
| items: (j.items || []).map((it) => ({ | |
| title: it.title, url: abs(it.url || it.external_url || ''), | |
| date: it.date_published || it.date_modified, | |
| summary: it.summary || it.content_text || plainText(it.content_html), | |
| })), | |
| }; | |
| } | |
| const doc = xmlRoot(text); | |
| const txt = (el, sel) => el.querySelector(sel)?.textContent?.trim() || ''; | |
| const isAtom = doc.documentElement.localName === 'feed'; | |
| const entries = [...doc.querySelectorAll(isAtom ? 'entry' : 'item')]; | |
| const atomLink = (el) => (el.querySelector('link[rel="alternate"]') || el.querySelector('link:not([rel])') || el.querySelector('link'))?.getAttribute('href'); | |
| return { | |
| title: txt(doc, isAtom ? 'feed > title' : 'channel > title'), | |
| home: abs(isAtom ? atomLink(doc.documentElement) || '' : txt(doc, 'channel > link')), | |
| items: entries.map((el) => ({ | |
| title: txt(el, 'title'), | |
| url: abs(isAtom ? atomLink(el) || '' : txt(el, 'link') || txt(el, 'guid')), | |
| date: isAtom ? txt(el, 'published') || txt(el, 'updated') : txt(el, 'pubDate') || el.getElementsByTagNameNS('*', 'date')[0]?.textContent, | |
| summary: plainText(isAtom ? txt(el, 'summary') || txt(el, 'content') : txt(el, 'description') || el.getElementsByTagNameNS('*', 'encoded')[0]?.textContent), | |
| })), | |
| }; | |
| } | |
| // ---- rendering ---- | |
| function h(tag, attrs = {}, ...children) { | |
| const el = document.createElement(tag); | |
| for (const [k, v] of Object.entries(attrs)) { | |
| if (v == null || v === false) continue; | |
| if (k === 'class') el.className = v; | |
| else if (k.startsWith('on')) el.addEventListener(k.slice(2), v); | |
| else el.setAttribute(k, v === true ? '' : v); | |
| } | |
| for (const c of children.flat()) if (c != null && c !== false) el.append(c); | |
| return el; | |
| } | |
| const ext = (href, ...children) => h('a', { href, target: '_blank', rel: 'noopener noreferrer' }, ...children); | |
| const host = (url) => { try { return new URL(url).host.replace(/^www\./, ''); } catch { return url; } }; | |
| const subscribeLink = (feedUrl) => CONFIG.subscribeUrl && ext(CONFIG.subscribeUrl.replace('{url}', encodeURIComponent(feedUrl)), 'subscribe'); | |
| function formatDate(s) { | |
| const d = new Date(s); | |
| return isNaN(d) ? '' : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }); | |
| } | |
| function sourceLine(p) { | |
| const trust = p.verified ? 'verified link' : p.backlink ? 'site links back to this account' : 'linked from profile, not verified'; | |
| return h('p', { class: 'sspec-source' }, | |
| 'From ', ext(p.origin, host(p.origin)), ' · ', | |
| h('span', { class: p.verified || p.backlink ? 'sspec-ok' : 'sspec-warn' }, p.verified || p.backlink ? '✓ ' : '', trust)); | |
| } | |
| // Remote images are blocked by Mastodon's CSP, so fetch them as blobs. | |
| async function loadImages(root) { | |
| const imgs = [...root.querySelectorAll('img[data-src]')]; | |
| imgs.slice(CONFIG.maxImages).forEach((img) => img.remove()); | |
| await Promise.all(imgs.slice(0, CONFIG.maxImages).map(async (img) => { | |
| const r = await request(img.dataset.src, { blob: true }); | |
| if (r.status === 200 && r.blob && /^image\//.test(r.blob.type || 'image/')) { | |
| img.src = URL.createObjectURL(r.blob); | |
| } else { | |
| img.replaceWith(ext(img.dataset.src, img.alt || 'image')); | |
| } | |
| })); | |
| } | |
| function renderAbout(p) { | |
| const { meta, body } = parseFrontmatter(p.about); | |
| const base = p.aboutUrl || p.origin + '/'; | |
| const frag = DOMPurify.sanitize(marked.parse(body), { | |
| RETURN_DOM_FRAGMENT: true, | |
| FORBID_TAGS: ['style', 'form', 'input', 'button', 'textarea', 'select'], | |
| FORBID_ATTR: ['style', 'srcset'], | |
| }); | |
| for (const a of frag.querySelectorAll('a[href]')) { | |
| try { a.href = new URL(a.getAttribute('href'), base).href; } catch { a.removeAttribute('href'); } | |
| a.target = '_blank'; | |
| a.rel = 'noopener noreferrer'; | |
| } | |
| for (const img of frag.querySelectorAll('img')) { | |
| try { img.dataset.src = new URL(img.getAttribute('src'), base).href; } catch { /* dropped below */ } | |
| img.removeAttribute('src'); | |
| if (!img.dataset.src) img.remove(); | |
| } | |
| const content = h('div', { class: 'sspec-md' }, frag); | |
| loadImages(content); | |
| return [ | |
| meta.summary && h('p', { class: 'sspec-lede' }, meta.summary), | |
| content, | |
| ]; | |
| } | |
| function renderFollowing(p) { | |
| const doc = xmlRoot(p.following); | |
| const owner = doc.querySelector('head > title')?.textContent?.trim(); | |
| const sections = []; | |
| let count = 0; | |
| const item = (o) => { | |
| const feed = o.getAttribute('xmlUrl'); | |
| const site = o.getAttribute('htmlUrl') || o.getAttribute('url') || (feed && new URL(feed).origin); | |
| const name = o.getAttribute('title') || o.getAttribute('text') || host(site || feed); | |
| count++; | |
| return h('li', {}, | |
| h('span', { class: 'sspec-name' }, site ? ext(site, name) : name), | |
| h('span', { class: 'sspec-meta' }, | |
| site && host(site), | |
| feed && [' · ', ext(feed, 'feed')], | |
| feed && subscribeLink(feed) && [' · ', subscribeLink(feed)])); | |
| }; | |
| const walk = (parent, heading) => { | |
| const kids = [...parent.children].filter((c) => c.localName === 'outline'); | |
| const leaves = kids.filter((o) => o.getAttribute('xmlUrl') || o.getAttribute('url') || o.getAttribute('htmlUrl')); | |
| if (leaves.length) sections.push(h('section', {}, heading && h('h3', {}, heading), h('ul', { class: 'sspec-list' }, leaves.map(item)))); | |
| for (const g of kids.filter((o) => !leaves.includes(o))) walk(g, g.getAttribute('title') || g.getAttribute('text')); | |
| }; | |
| walk(doc.querySelector('body') || doc.documentElement); | |
| const filter = count > 25 && h('input', { | |
| type: 'search', class: 'sspec-filter', placeholder: `Filter ${count} sites`, 'aria-label': 'Filter followed sites', | |
| oninput: (e) => { | |
| const q = e.target.value.trim().toLowerCase(); | |
| for (const section of sections) { | |
| let shown = 0; | |
| for (const li of section.querySelectorAll('li')) { | |
| const hit = !q || li.textContent.toLowerCase().includes(q); | |
| li.hidden = !hit; | |
| shown += hit; | |
| } | |
| section.hidden = !shown; | |
| } | |
| }, | |
| }); | |
| return [h('p', { class: 'sspec-lede' }, owner || 'Following', ` · ${count} ${count === 1 ? 'site' : 'sites'}`), filter, ...sections]; | |
| } | |
| function renderContact(p) { | |
| const props = parseVcard(p.contact); | |
| const all = (...names) => props.filter((x) => names.includes(x.name)); | |
| const rows = []; | |
| const row = (label, ...value) => rows.push(h('div', { class: 'sspec-row' }, h('dt', {}, label), h('dd', {}, ...value))); | |
| const fn = all('FN')[0]?.value; | |
| if (fn) row('Name', fn); | |
| for (const x of all('ORG', 'TITLE')) row(x.name === 'ORG' ? 'Organization' : 'Title', x.value.replace(/;/g, ', ')); | |
| for (const x of all('EMAIL')) { | |
| const pref = x.params.PREF || /pref/i.test(x.params.TYPE || ''); | |
| row(pref ? 'Email · preferred' : 'Email', h('a', { href: `mailto:${x.value}` }, x.value)); | |
| } | |
| for (const x of all('TEL')) row('Phone', h('a', { href: `tel:${x.value.replace(/^tel:/, '')}` }, x.value.replace(/^tel:/, ''))); | |
| for (const x of all('URL')) row('Website', ext(x.value, host(x.value))); | |
| const seen = new Set(); | |
| for (const x of all('SOCIALPROFILE', 'X-SOCIALPROFILE', 'IMPP')) { | |
| if (seen.has(x.value)) continue; | |
| seen.add(x.value); | |
| const label = x.params.TYPE ? x.params.TYPE[0].toUpperCase() + x.params.TYPE.slice(1).toLowerCase() : 'Profile'; | |
| row(label, /^https?:/.test(x.value) ? ext(x.value, x.value.replace(/^https?:\/\//, '')) : x.value); | |
| } | |
| for (const x of all('ADR')) { | |
| const parts = x.raw.split(';').slice(2).map((s) => s.replace(/\\([,;\\])/g, '$1')).filter(Boolean); | |
| if (parts.length) row('Address', parts.join(', ')); | |
| } | |
| for (const x of all('NOTE')) row('Note', x.value); | |
| const blobUrl = URL.createObjectURL(new Blob([p.contact], { type: 'text/vcard' })); | |
| return [ | |
| h('dl', { class: 'sspec-contact' }, rows), | |
| h('p', {}, h('a', { href: blobUrl, download: `${(fn || host(p.origin)).replace(/[^\w .-]/g, '')}.vcf` }, 'Save contact card')), | |
| ]; | |
| } | |
| async function renderFeed(p) { | |
| const r = await request(p.feedUrl); | |
| if (r.status !== 200 || !feedKind(r.text)) return [h('p', {}, 'Could not load ', ext(p.feedUrl, 'the feed'), '.')]; | |
| const feed = parseFeed(r.text, r.finalUrl); | |
| // Microblog posts often get a title that is just the post's opening words. | |
| const items = feed.items.slice(0, CONFIG.feedItems).map((it) => { | |
| const stem = (it.title || '').replace(/(…|\.\.\.)\s*$/, '').trim(); | |
| return stem && it.summary?.startsWith(stem) ? { ...it, title: '' } : it; | |
| }); | |
| return [ | |
| h('p', { class: 'sspec-lede' }, | |
| feed.title || host(p.origin), ' · ', ext(p.feedUrl, 'feed'), | |
| subscribeLink(p.feedUrl) && [' · ', subscribeLink(p.feedUrl)]), | |
| h('ul', { class: 'sspec-list sspec-feed' }, items.map((it) => h('li', {}, | |
| h('span', { class: 'sspec-meta' }, formatDate(it.date)), | |
| it.title ? h('span', { class: 'sspec-name' }, it.url ? ext(it.url, it.title) : it.title) : null, | |
| it.summary && h('span', { class: 'sspec-summary' }, it.summary), | |
| !it.title && it.url && ext(it.url, 'read')))), | |
| feed.home && h('p', {}, ext(feed.home, `More at ${host(feed.home)}`)), | |
| ]; | |
| } | |
| const RENDER = { about: renderAbout, following: renderFollowing, contact: renderContact, feed: renderFeed }; | |
| const available = (p, kind) => (kind === 'feed' ? !!p.feedUrl : !!p[kind]); | |
| // ---- tabs ---- | |
| const state = { acct: null, profile: null, active: null, nativeActive: null }; | |
| const findTabList = () => document.querySelector('[class*="tab_list__tabList"], .account__section-headline'); | |
| function injectTabs(tabList) { | |
| tabList.querySelectorAll('.sspec-tab, .sspec-sep').forEach((el) => el.remove()); | |
| const native = tabList.querySelector('a:not(.active)') || tabList.querySelector('a'); | |
| const tabClass = (native?.className || '').replace(/\bactive\b/, '').trim(); | |
| // Buttons don't inherit font from the tab class the way links do. | |
| const cs = native && getComputedStyle(native); | |
| tabList.dataset.sspecAcct = state.acct; | |
| tabList.classList.add('sspec-has-tabs'); | |
| tabList.append(h('span', { class: 'sspec-sep', 'aria-hidden': 'true' })); | |
| for (const t of TABS.filter((t) => available(state.profile, t.kind))) { | |
| const b = h('button', { | |
| type: 'button', role: 'tab', class: `${tabClass} sspec-tab`.trim(), | |
| 'data-kind': t.kind, title: `${t.label} from ${host(state.profile.origin)}`, | |
| onclick: (e) => { e.preventDefault(); activate(t.kind); }, | |
| }, t.label); | |
| if (cs) Object.assign(b.style, { fontFamily: cs.fontFamily, fontSize: cs.fontSize, fontWeight: cs.fontWeight, letterSpacing: cs.letterSpacing }); | |
| tabList.append(b); | |
| } | |
| if (!tabList.dataset.sspecListener) { | |
| tabList.dataset.sspecListener = '1'; | |
| tabList.addEventListener('click', (e) => { | |
| if (e.target.closest('a') && !e.target.closest('.sspec-tab')) deactivate(true); | |
| }, true); | |
| } | |
| } | |
| async function activate(kind) { | |
| const tabList = findTabList(); | |
| if (!tabList) return; | |
| state.active = kind; | |
| const container = tabList.parentElement; | |
| container.classList.add('sspec-on'); | |
| for (const a of tabList.querySelectorAll('a.active')) { | |
| state.nativeActive = a; | |
| a.classList.remove('active'); | |
| } | |
| for (const b of tabList.querySelectorAll('.sspec-tab')) { | |
| b.classList.toggle('active', b.dataset.kind === kind); | |
| b.setAttribute('aria-selected', b.dataset.kind === kind); | |
| } | |
| container.querySelector('.sspec-panel')?.remove(); | |
| const panel = h('div', { class: 'sspec-panel', role: 'tabpanel', 'data-kind': kind }, h('p', { class: 'sspec-meta' }, 'Loading…')); | |
| tabList.after(panel); | |
| let content; | |
| try { content = await RENDER[kind](state.profile); } catch (err) { | |
| console.warn('[socialspec]', err); | |
| content = [h('p', {}, `Couldn't read this ${kind} file.`)]; | |
| } | |
| if (panel.isConnected && state.active === kind) panel.replaceChildren(sourceLine(state.profile), ...[content].flat().filter((c) => c != null && c !== false)); | |
| } | |
| function deactivate(fromNativeClick) { | |
| state.active = null; | |
| document.querySelectorAll('.sspec-panel').forEach((el) => el.remove()); | |
| document.querySelectorAll('.sspec-on').forEach((el) => el.classList.remove('sspec-on')); | |
| document.querySelectorAll('.sspec-tab.active').forEach((b) => { b.classList.remove('active'); b.setAttribute('aria-selected', 'false'); }); | |
| if (fromNativeClick && state.nativeActive?.isConnected) state.nativeActive.classList.add('active'); | |
| state.nativeActive = null; | |
| } | |
| function removeTabs() { | |
| document.querySelectorAll('.sspec-tab, .sspec-sep').forEach((el) => el.remove()); | |
| document.querySelectorAll('[data-sspec-acct]').forEach((el) => { | |
| delete el.dataset.sspecAcct; | |
| el.classList.remove('sspec-has-tabs'); | |
| }); | |
| } | |
| async function tick() { | |
| const acct = acctFromPath(); | |
| if (acct !== state.acct) { | |
| deactivate(false); | |
| removeTabs(); | |
| state.acct = acct; | |
| state.profile = null; | |
| if (!acct) return; | |
| const profile = await loadProfile(acct).catch((err) => { console.warn('[socialspec]', err); return null; }); | |
| if (state.acct !== acct) return; | |
| state.profile = profile; | |
| } | |
| const tabList = findTabList(); | |
| if (!tabList || !state.profile) return; | |
| if (tabList.dataset.sspecAcct !== acct || !tabList.querySelector('.sspec-tab')) injectTabs(tabList); | |
| if (state.active && !tabList.parentElement.querySelector('.sspec-panel')) activate(state.active); | |
| } | |
| addStyle(` | |
| .sspec-has-tabs { overflow-x: auto; scrollbar-width: none; } | |
| .sspec-has-tabs::-webkit-scrollbar { display: none; } | |
| .sspec-sep { flex: none; align-self: center; width: 1px; height: 1.2em; margin: 0 4px; background: currentColor; opacity: .25; } | |
| .sspec-tab { background: none; border: 0; color: inherit; cursor: pointer; white-space: nowrap; } | |
| .sspec-on > .sspec-panel ~ * { display: none !important; } | |
| .sspec-panel { padding: 16px; line-height: 1.5; overflow-wrap: anywhere; } | |
| .sspec-panel a { color: inherit; text-decoration: underline; text-underline-offset: 2px; } | |
| .sspec-source { font-size: .85em; opacity: .75; margin: 0 0 12px; } | |
| .sspec-warn { font-style: italic; } | |
| .sspec-lede { font-weight: 600; margin: 0 0 12px; } | |
| .sspec-meta { font-size: .85em; opacity: .7; } | |
| .sspec-panel h3 { font-weight: 600; margin: 16px 0 4px; font-size: .9em; text-transform: uppercase; letter-spacing: .04em; opacity: .75; } | |
| .sspec-list { list-style: none; margin: 0; padding: 0; } | |
| .sspec-list li { display: flex; flex-direction: column; gap: 2px; padding: 8px 0; border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent); } | |
| .sspec-name { font-weight: 600; } | |
| .sspec-filter { width: 100%; box-sizing: border-box; margin: 0 0 8px; padding: 8px 10px; font: inherit; color: inherit; background: transparent; border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 6px; } | |
| .sspec-list li[hidden], .sspec-panel section[hidden] { display: none; } | |
| .sspec-summary { opacity: .85; } | |
| .sspec-md p, .sspec-md ul, .sspec-md ol, .sspec-md blockquote { margin: 0 0 12px; } | |
| .sspec-md ul { list-style: disc; padding-left: 1.4em; } | |
| .sspec-md ol { list-style: decimal; padding-left: 1.4em; } | |
| .sspec-md h1, .sspec-md h2, .sspec-md h3, .sspec-md h4 { font-weight: 700; margin: 16px 0 8px; } | |
| .sspec-md h1 { font-size: 1.3em; } .sspec-md h2 { font-size: 1.15em; } .sspec-md h3 { font-size: 1em; } | |
| .sspec-md strong { font-weight: 700; } .sspec-md em { font-style: italic; } | |
| .sspec-md img { max-width: 100%; height: auto; border-radius: 4px; } | |
| .sspec-md blockquote { border-left: 3px solid color-mix(in srgb, currentColor 30%, transparent); padding-left: 12px; } | |
| .sspec-md code { font-family: monospace; } | |
| .sspec-contact { margin: 0 0 12px; } | |
| .sspec-row { display: grid; grid-template-columns: 9em 1fr; gap: 8px; padding: 6px 0; border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent); } | |
| .sspec-row dt { opacity: .7; } | |
| @media (max-width: 480px) { .sspec-row { grid-template-columns: 1fr; gap: 0; } } | |
| `); | |
| let scheduled = false; | |
| new MutationObserver(() => { | |
| if (scheduled) return; | |
| scheduled = true; | |
| requestAnimationFrame(() => { scheduled = false; tick(); }); | |
| }).observe(document.body, { childList: true, subtree: true }); | |
| tick(); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment