Repository navigation
Expand file tree
/
Copy pathembeds.js
More file actions
123 lines (112 loc) · 5.86 KB
/
Copy pathembeds.js
File metadata and controls
123 lines (112 loc) · 5.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Shared by the homepage and the generated /people/<slug>/ pages.
// Renders Instagram / X posts as lazy iframes, sized via the platforms' own postMessage reports.
function el(tag, attrs = {}, text) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v);
if (text != null) n.textContent = text;
return n;
}
// Broad to narrow, on one line: "United States, Utah, Salt Lake City"
const fullPlace = (p) => [p.country, p.region, p.city].filter(Boolean).join(", ") || "Location unspecified";
// Which platform a post_url points at, plus the ID we need to embed it.
function source(url = "") {
let m = url.match(/instagram\.com\/(?:p|reel)\/([A-Za-z0-9_-]+)/);
if (m) return { kind: "ig", code: m[1] };
m = url.match(/threads\.(?:com|net)\/@([^/]+)\/post\/([A-Za-z0-9_-]+)/);
if (m) return { kind: "threads", user: m[1], code: m[2] };
m = url.match(/(?:x|twitter)\.com\/[^/]+\/status\/(\d+)/);
if (m) return { kind: "x", id: m[1] };
return null;
}
// Both platforms encode the post time in the ID itself.
// Instagram: shortcode -> media ID, top bits = ms since 2011-08-24. X: snowflake, top bits = ms since 2010-11-04.
const IG_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
function postedAt(p) {
if (p.posted) return new Date(p.posted);
const s = source(p.post_url);
if (s?.kind === "ig" || s?.kind === "threads") { // Threads (Meta) uses Instagram's ID scheme
let id = 0n;
for (const ch of s.code.slice(0, 11)) id = id * 64n + BigInt(IG_ALPHABET.indexOf(ch));
return new Date(Number(id >> 23n) + 1314220021721);
}
if (s?.kind === "x") return new Date(Number(BigInt(s.id) >> 22n) + 1288834974657);
return null;
}
const fmtDate = (d) => d.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
// Profiles with a bio get their own page (generated by build.py).
const slugOf = (p) => p.slug || p.id;
const personUrl = (p) => (p.bio ? `/people/${slugOf(p)}/` : null);
// Embeds are plain iframes with loading="lazy": nothing from Instagram or X loads until a
// card is about to scroll into view, and no embed.js / widgets.js scripts are needed at all.
const dark = matchMedia("(prefers-color-scheme: dark)").matches;
const PLATFORM = { ig: "Instagram", threads: "Threads", x: "X" };
function frameSrc(s) {
if (s.kind === "ig") return `https://www.instagram.com/p/${s.code}/embed/captioned/`;
if (s.kind === "threads") return `https://www.threads.com/@${s.user}/post/${s.code}/embed`;
return `https://platform.twitter.com/embed/Tweet.html?id=${s.id}&dnt=true&theme=${dark ? "dark" : "light"}`;
}
// Age-restricted posts can't be embedded (Instagram only shows them to logged-in adults),
// nor can posts whose author turned embedding off, so show a link panel instead of an empty frame.
function restrictedFrame(postUrl, adult = true) {
const s = source(postUrl);
const frame = el("a", { class: "frame restricted", href: postUrl, target: "_blank", rel: "noopener" });
if (adult) frame.append(el("span", { class: "r-badge" }, "18+"));
frame.append(el("span", { class: "r-title" }, adult ? "Age-restricted post" : "Watch the post"),
el("span", { class: "r-sub" }, `Open on ${PLATFORM[s?.kind] || "Instagram"} →`));
return frame;
}
function embedFrame(postUrl, opts = {}) {
if (opts.restricted) return restrictedFrame(postUrl);
if (opts.noEmbed) return restrictedFrame(postUrl, false);
const s = source(postUrl);
const frame = el("div", { class: `frame ${s.kind}` });
frame.append(el("a", { class: "fallback", href: postUrl, target: "_blank", rel: "noopener" },
`View on ${PLATFORM[s.kind]} →`));
const f = el("iframe", {
title: `Post on ${PLATFORM[s.kind]}`, scrolling: "no", referrerpolicy: "strict-origin-when-cross-origin",
});
f.dataset.src = frameSrc(s);
// X sometimes never sends its size on the first load; reload the frame once if so.
let retried = false;
f.addEventListener("load", () => {
if (!f.getAttribute("src")) return; // ignore the initial about:blank load
setTimeout(() => {
if (!frame.classList.contains("ready") && !retried) { retried = true; f.src = f.src; }
}, 5000);
});
frame.append(f);
if (opts.eager) startFrame(f); else preloader.observe(f);
return frame;
}
// Preloading: tiles near the top load immediately; the rest start loading about three
// screens before they scroll into view, so they are ready by the time you get there.
function startFrame(f) {
if (!f.getAttribute("src") && f.dataset.src) f.src = f.dataset.src;
}
const preloader = "IntersectionObserver" in window
? new IntersectionObserver((entries) => {
for (const e of entries) if (e.isIntersecting) { startFrame(e.target); preloader.unobserve(e.target); }
}, { rootMargin: "300% 0px" })
: { observe: startFrame, unobserve() {} };
// Turn static <div data-post-url="..."> placeholders into live embeds (used on people pages).
function upgradeEmbeds(root = document) {
for (const n of root.querySelectorAll("[data-post-url]")) {
if (source(n.dataset.postUrl)) n.replaceWith(embedFrame(n.dataset.postUrl));
}
}
// Both embeds report their real height via postMessage; size each iframe to fit.
addEventListener("message", (e) => {
let host;
try { host = new URL(e.origin).hostname; } catch { return; }
if (!/(^|\.)(instagram|threads)\.(com|net)$|^platform\.twitter\.com$/.test(host)) return;
let msg = e.data, h;
try { if (typeof msg === "string") msg = JSON.parse(msg); } catch { return; }
if (typeof msg === "number") h = msg; // Threads sends a bare height
if (msg?.type === "MEASURE") h = msg.details?.height;
const x = msg?.["twttr.embed"];
if (x?.method === "twttr.private.resize") h = x.params?.[0]?.height;
if (!h) return;
for (const f of document.querySelectorAll(".frame iframe")) {
if (f.contentWindow === e.source) { f.style.height = `${Math.ceil(h)}px`; f.parentElement.classList.add("ready"); }
}
});