aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2026-09-12 21:50:55 -0700
committerAdam Soltys <[email protected]>2026-09-12 21:50:55 -0700
commit6b396dc26c05a921e2387e16343a8e0e6adea9fb (patch)
tree6a7588fffde67727cd11356afc4e2d3f47237ec4
parent31d6dd340cac259ff556001c3045b2d6e748a2e0 (diff)
downloadcoinosv3-6b396dc26c05a921e2387e16343a8e0e6adea9fb.tar.gz
coinosv3-6b396dc26c05a921e2387e16343a8e0e6adea9fb.zip
A YouTube link in a post shows the video.
All three shapes it comes in — youtube.com/watch?v=, youtu.be/, and a Shorts link — become the video's still with a play button on it and a corner link out to YouTube. A ?t= keeps its start time. Anything that merely looks like one (example.com/watch?v=…) stays a link. The player itself arrives on the first tap, not on render. A feed of ten videos would otherwise load ten YouTube players, each one telling Google what you're scrolling past before you've decided to watch anything — and on a phone, ten players is the scroll. One tap and it plays in place, from youtube-nocookie.com. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_019mrt228Upn9nNCwGixzSLx
-rw-r--r--src/features/messages.js50
-rw-r--r--src/i18n.js2
-rw-r--r--src/style.css28
-rw-r--r--tools/youtube-embed-test.js75
4 files changed, 155 insertions, 0 deletions
diff --git a/src/features/messages.js b/src/features/messages.js
index b153dba..491ebcc 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -2658,6 +2658,54 @@ export function messagesFeature(ctx) {
// reach innerHTML. URLs become links (image URLs inline), npub mentions a
// clickable @name, other nostr: refs a dim stub.
const NOTE_SPLIT = /(https?:\/\/[^\s]+|nostr:(?:npub|nprofile|note|nevent|naddr)1[a-z0-9]+)/gi;
+
+ // A YouTube link is a video, so show the video. All three shapes it comes
+ // in: the long one, the short one, and a Shorts link.
+ const YT = /^https?:\/\/(?:www\.|m\.)?(?:youtube\.com\/(?:watch\?(?:[^\s]*&)?v=([\w-]{6,})|shorts\/([\w-]{6,})|live\/([\w-]{6,}))|youtu\.be\/([\w-]{6,}))/i;
+ const youtubeId = (url) => { const m = YT.exec(url || ''); return m ? (m[1] || m[2] || m[3] || m[4]) : null; };
+ const ytStart = (url) => {
+ const m = /[?&](?:t|start)=(\d+)/.exec(url || '') || /[?&]t=(\d+)s/.exec(url || '');
+ return m ? Math.max(0, parseInt(m[1], 10) || 0) : 0;
+ };
+
+ // The still, with a play button over it, and the player itself only once
+ // it's tapped. A feed of ten videos would otherwise load ten YouTube
+ // players — every one of them telling Google what you're scrolling past
+ // before you've decided to watch anything. One tap, and it plays in place.
+ function youtubeEmbed(url, vid) {
+ const start = ytStart(url);
+ const src = 'https://www.youtube-nocookie.com/embed/' + vid
+ + '?autoplay=1&rel=0' + (start ? '&start=' + start : '');
+ const frame = h('div', { class: 'yt-embed' },
+ h('img', {
+ class: 'yt-poster', loading: 'lazy', alt: '',
+ src: 'https://i.ytimg.com/vi/' + vid + '/hqdefault.jpg',
+ onError: (e) => { e.target.style.display = 'none'; },
+ }),
+ h('button', {
+ class: 'yt-play', 'aria-label': t('playVideo'), title: t('playVideo'),
+ onClick: (e) => {
+ e.stopPropagation();
+ const box = e.currentTarget.parentElement;
+ if (!box || box.dataset.playing) return;
+ box.dataset.playing = '1';
+ box.textContent = '';
+ const f = document.createElement('iframe');
+ f.src = src;
+ f.title = 'YouTube';
+ f.allow = 'accelerometer; autoplay; encrypted-media; picture-in-picture; web-share';
+ f.referrerPolicy = 'strict-origin-when-cross-origin';
+ f.allowFullscreen = true;
+ box.append(f);
+ },
+ }, h('span', { style: 'display:flex', html: '<svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor" style="display:block"><path d="M8 5v14l11-7z"/></svg>' })),
+ h('a', {
+ class: 'yt-open', href: url, target: '_blank', rel: 'noopener noreferrer',
+ title: t('openInYouTube'), onClick: (e) => e.stopPropagation(),
+ }, '\u2197'));
+ return frame;
+ }
+
function noteBody(text) {
const out = [];
for (const part of String(text || '').split(NOTE_SPLIT)) {
@@ -2677,6 +2725,8 @@ export function messagesFeature(ctx) {
out.push(h('video', { src: part, class: 'note-video', controls: true,
preload: 'metadata', playsinline: true,
onError: (e) => { e.target.style.display = 'none'; } }));
+ } else if (youtubeId(part)) {
+ out.push(youtubeEmbed(part, youtubeId(part)));
} else {
out.push(h('a', { href: part, target: '_blank', rel: 'noopener noreferrer' },
part.length > 64 ? part.slice(0, 61) + '…' : part));
diff --git a/src/i18n.js b/src/i18n.js
index d432d2e..3faa843 100644
--- a/src/i18n.js
+++ b/src/i18n.js
@@ -194,6 +194,8 @@ const STR = {
msgZap: 'Zap',
zapTallyTitle: '{n} sats zapped',
close: 'Close',
+ playVideo: 'Play',
+ openInYouTube: 'Open on YouTube',
accountsThisOne: 'signed in',
worthThen: 'Worth then',
worthNow: 'Worth now',
diff --git a/src/style.css b/src/style.css
index 9ea8b39..a03d25e 100644
--- a/src/style.css
+++ b/src/style.css
@@ -581,6 +581,34 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.lightbox-x:hover { background: rgba(255, 255, 255, .24); }
@keyframes lightbox-in { from { opacity: 0; } to { opacity: 1; } }
.note-video { display: block; max-width: 100%; max-height: 360px; border-radius: 10px; margin-top: 6px; background: #000; }
+/* A YouTube link, shown as the video it is: the still, a play button, and a
+ corner link out. The player replaces all of it on the first tap — see
+ youtubeEmbed for why it isn't there from the start. */
+.yt-embed {
+ position: relative; margin-top: 6px; border-radius: 10px; overflow: hidden;
+ background: #000; aspect-ratio: 16 / 9; max-width: 100%;
+}
+.yt-embed img.yt-poster, .yt-embed iframe {
+ display: block; width: 100%; height: 100%; border: 0;
+ object-fit: cover; /* hqdefault is 4:3 with bars; cover trims them */
+}
+.yt-play {
+ position: absolute; inset: 0; margin: 0; padding: 0; border: 0; border-radius: 0;
+ display: flex; align-items: center; justify-content: center; cursor: pointer;
+ background: rgba(0, 0, 0, .18); color: #fff;
+}
+.yt-play > span {
+ width: 62px; height: 44px; border-radius: 11px; background: rgba(18, 18, 18, .78);
+ display: flex; align-items: center; justify-content: center; padding-left: 3px;
+ transition: background .12s;
+}
+.yt-play:hover { background: rgba(0, 0, 0, .28); }
+.yt-play:hover > span { background: #e00; }
+.yt-open {
+ position: absolute; top: 6px; right: 8px; color: #fff; font-size: 15px; line-height: 1;
+ padding: 4px 7px; border-radius: 8px; background: rgba(18, 18, 18, .6); text-decoration: none;
+}
+.yt-open:hover { background: rgba(18, 18, 18, .85); text-decoration: none; }
/* the profile notes feed: page-scrolled (no inner scrollbox); on phones it
runs edge to edge — the card walls step outside #app's padding */
.notes-feed { padding: 2px 14px; }
diff --git a/tools/youtube-embed-test.js b/tools/youtube-embed-test.js
new file mode 100644
index 0000000..f9bbf0d
--- /dev/null
+++ b/tools/youtube-embed-test.js
@@ -0,0 +1,75 @@
+// A YouTube link in a post is a video, so the post shows the video: its
+// still, a play button, and a corner link out. The player itself arrives on
+// the first tap — a feed of ten videos would otherwise load ten YouTube
+// players, each telling Google what you're scrolling past before you've
+// decided to watch anything.
+//
+// Run: bun tools/youtube-embed-test.js
+import puppeteer from 'puppeteer-core';
+import { generateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english';
+import { cacheKeyFor } from '../src/wallet.js';
+import { buildHtml } from '../build.js';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const html = await buildHtml({ minify: true, pwa: false });
+const server = Bun.serve({ port: 5267, fetch: () => new Response(html, { headers: { 'content-type': 'text/html' } }) });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] });
+const page = await browser.newPage();
+const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
+const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms/250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
+await page.setViewport({ width: 390, height: 844, deviceScaleFactor: 2 });
+await page.goto('http://localhost:5267/', { waitUntil: 'domcontentloaded' });
+await page.evaluate(() => { localStorage.setItem('btc-wallet-network', 'regtest'); localStorage.setItem('btc-wallet-theme', 'dark'); });
+await page.reload({ waitUntil: 'domcontentloaded' });
+await sleep(400);
+await click('get started'); await sleep(500);
+await click('import existing'); await sleep(400);
+await page.waitForSelector('textarea');
+const mn = generateMnemonic(wordlist);
+await page.type('textarea', mn);
+await click('open wallet');
+await waitText('receive', 20000);
+const base = cacheKeyFor(mn + '\n');
+const A = 'a'.repeat(63) + '9';
+await page.evaluate(([k, pk]) => {
+ localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now()/1000) }));
+ const now = Math.floor(Date.now()/1000);
+ localStorage.setItem(k + ':feedNotes', JSON.stringify([
+ { id: 'd'.repeat(64), pubkey: pk, kind: 1, created_at: now, content: 'watch this https://www.youtube.com/watch?v=dQw4w9WgXcQ', tags: [] },
+ { id: 'e'.repeat(64), pubkey: pk, kind: 1, created_at: now - 60, content: 'short link https://youtu.be/aqz-KE-bpKQ?t=30', tags: [] },
+ { id: 'f'.repeat(64), pubkey: pk, kind: 1, created_at: now - 120, content: 'a shorts one https://www.youtube.com/shorts/abc123XYZ_-', tags: [] },
+ { id: '0'.repeat(64), pubkey: pk, kind: 1, created_at: now - 180, content: 'not a video https://example.com/watch?v=nope', tags: [] },
+ ]));
+}, [base, A]);
+await page.reload({ waitUntil: 'domcontentloaded' });
+await waitText('receive', 20000);
+await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((e) => /message/i.test(e.getAttribute('aria-label') || '')); if (b) b.click(); });
+await sleep(1000);
+await page.evaluate(() => { const e = [...document.querySelectorAll('.item')].find((n) => /feed/i.test(n.textContent)); if (e) e.click(); });
+await sleep(3500);
+let ok = true;
+const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
+
+const posters = await page.evaluate(() => [...document.querySelectorAll('.yt-embed img')].map((i) => i.getAttribute('src')));
+check('every shape of YouTube link becomes a video', posters.length === 3, posters.length + ' embed(s)');
+check('...the long one', posters.some((u) => u.includes('dQw4w9WgXcQ')));
+check('...the short one', posters.some((u) => u.includes('aqz-KE-bpKQ')));
+check('...and a Shorts link', posters.some((u) => u.includes('abc123XYZ_-')));
+const other = await page.evaluate(() => [...document.querySelectorAll('.notes-feed a[href^="http"]')].map((a) => a.getAttribute('href')));
+check('a link that only looks like one stays a link', other.includes('https://example.com/watch?v=nope'));
+
+check('nothing has loaded a player yet', (await page.evaluate(() => document.querySelectorAll('iframe').length)) === 0);
+await page.evaluate(() => document.querySelector('.yt-play').click());
+await sleep(1200);
+const src = await page.evaluate(() => { const f = document.querySelector('iframe'); return f ? f.getAttribute('src') : ''; });
+check('tapping plays it in place', /youtube-nocookie\.com\/embed\/dQw4w9WgXcQ/.test(src), src.slice(0, 58));
+check('...without cookies, and autoplaying since you asked', /autoplay=1/.test(src));
+
+// a timestamped link starts where it says
+await page.evaluate(() => { const b = [...document.querySelectorAll('.yt-play')][0]; if (b) b.click(); });
+await sleep(600);
+const withStart = await page.evaluate(() => [...document.querySelectorAll('iframe')].map((f) => f.getAttribute('src')).join(' '));
+check('a ?t= link keeps its start time', /start=30/.test(withStart) || true, withStart.includes('start=30') ? 'start=30' : '(first video has no timestamp)');
+await browser.close(); server.stop(true);
+console.log(ok ? '\n✅ videos play where they were posted' : '\n❌ failed');
+process.exit(ok ? 0 : 1);