NGU-Web/src/lib/embeds.ts
Zaldimmar 57f8020542 Video stills skip YouTube's gray placeholder; timeline back to teal dots; people rows fill
- A still that fails or comes back as YouTube's 120 x 90 "no
  thumbnail" image gives way to the next; with none left the player
  is a flat teal panel with the play button showing.
- Timeline: solid teal dots, a solid teal rail and teal decade tags
  (still on their branch), one color throughout, until a vine or
  tree drawing replaces them. The leaf colors are gone.
- People tiles fill each row with as many as fit (2 to 10), one
  fewer only when the last row would be a single tile, instead of
  evening rows out (8 where 6 fit had come out 4 and 4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:44:42 -05:00

144 lines
5.7 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
EMBEDS
Turns the link an admin pastes into the URL an <iframe> can
load. People paste the page they're looking at (a YouTube watch
or live link, a Facebook video, a Vimeo page), not the embed
form, so those are recognized and rewritten. Anything else that
is https is assumed to already be an embed URL and passed
through; anything that isn't https is refused, so the hero never
frames a plain-http or javascript: URL.
Streams start playing, muted: browsers only autoplay muted
video, and a hero that starts shouting is worse than one that
asks. A featured video doesn't start at all: it's a recording,
so the visitor presses play.
A featured video can also be a file rather than a link: a
filename in the uploads directory, a /path, or an https URL ending
in a video extension. videoSource() says which, so the hero can
hand a file to <video> and a link to an <iframe>.
═══════════════════════════════════════════════════════════════ */
import { mediaUrl } from './media.ts'
const VIDEO_FILE = /\.(mp4|webm|m4v|mov|ogv)$/i
function youtubeId(url: URL): string | null {
const host = url.hostname.replace(/^www\.|^m\./, '')
if (host === 'youtu.be') return url.pathname.slice(1) || null
if (host !== 'youtube.com' && host !== 'youtube-nocookie.com') return null
const v = url.searchParams.get('v')
if (v) return v
// /live/ID, /embed/ID, /shorts/ID
const match = url.pathname.match(/^\/(?:live|embed|shorts)\/([\w-]+)/)
return match?.[1] ?? null
}
/** An iframe src for a pasted link, or null if it can't be framed. */
function embedUrl(raw: string | null | undefined, autoplay: boolean): string | null {
if (!raw) return null
let url: URL
try {
url = new URL(raw.trim())
} catch {
return null
}
if (url.protocol !== 'https:') return null
const yt = youtubeId(url)
if (yt) {
const play = autoplay ? '?autoplay=1&mute=1&playsinline=1' : '?playsinline=1'
return `https://www.youtube-nocookie.com/embed/${encodeURIComponent(yt)}${play}`
}
const host = url.hostname.replace(/^www\./, '')
if (host === 'vimeo.com') {
const id = url.pathname.match(/^\/(?:event\/)?(\d+)/)?.[1]
if (id) {
const play = autoplay ? '?autoplay=1&muted=1' : ''
return url.pathname.startsWith('/event/')
? `https://vimeo.com/event/${id}/embed${play}`
: `https://player.vimeo.com/video/${id}${play}`
}
}
if ((host === 'facebook.com' || host === 'fb.watch') && !url.pathname.startsWith('/plugins/')) {
const play = autoplay ? '&autoplay=1&mute=1' : ''
return `https://www.facebook.com/plugins/video.php?href=${encodeURIComponent(url.href)}${play}`
}
return url.href
}
/** An iframe src for a pasted stream link, or null if it can't be framed. */
export function livestreamEmbedUrl(raw?: string | null): string | null {
return embedUrl(raw, true)
}
export type VideoSource = { kind: 'file' | 'embed'; src: string }
/** How to play a featured video: a file for <video>, an embed for
* an <iframe>, or null when it's neither (the hero then links to
* it instead). Files follow the same https-only rule as embeds. */
export function videoSource(raw?: string | null): VideoSource | null {
const value = raw?.trim()
if (!value) return null
if (VIDEO_FILE.test(value.split(/[?#]/)[0])) {
if (/^https:\/\//i.test(value) || !/^[a-z][a-z0-9+.-]*:/i.test(value)) {
const src = mediaUrl(value)
if (src) return { kind: 'file', src }
}
return null
}
const src = embedUrl(value, false)
return src ? { kind: 'embed', src } : null
}
/* ── Click to play ─────────────────────────────────────────────
A featured card shows a still and swaps in the player when it's
pressed, so the page loads no iframes until someone asks for
one. The press is the user gesture browsers want before playing
with sound, so the player can start at once, unmuted.
───────────────────────────────────────────────────────────── */
/** The same source, set to start playing as soon as it loads. */
export function playingSource(source: VideoSource): VideoSource {
if (source.kind === 'file') return source
let url: URL
try {
url = new URL(source.src)
} catch {
return source
}
const host = url.hostname.replace(/^www\./, '')
if (host === 'youtube-nocookie.com' || host === 'player.vimeo.com' || host === 'vimeo.com' || host === 'facebook.com') {
url.searchParams.set('autoplay', '1')
}
return { kind: 'embed', src: url.toString() }
}
/** A still for a video link: YouTube's own thumbnail. Other hosts
* need an API call to find theirs, so they return null and the
* card uses its uploaded image or a plain panel. */
export function videoThumbnails(raw?: string | null): string[] {
if (!raw) return []
try {
const id = youtubeId(new URL(raw.trim()))
if (!id) return []
// hq720 is a 16:9 frame but some videos lack it; hqdefault is 4:3
// with black bars baked in (VideoPlayer crops them). A private or
// removed video has neither, and YouTube answers with a gray
// placeholder instead of an error, which VideoPlayer also skips.
const base = `https://i.ytimg.com/vi/${encodeURIComponent(id)}`
return [`${base}/hq720.jpg`, `${base}/hqdefault.jpg`]
} catch {
return []
}
}