Vue kit: Bhote Koshi's buttons and media cards are kit controls and a view

The reconstruction panel's buttons (previous and next beat, Play, Play
scene, Cinematic, Full story, Open original, Lower gorge, the field
reports and Open public map) are ghost UiButtons that keep their
data-action hooks. Cinematic is a pressed toggle: the event layer now
presents its state as the record's `pressed` instead of writing an
aria-pressed attribute, so it is no longer an exception in
viewControls.test.mjs; bhote-koshi.css still reads aria-pressed, so it
takes no pressed class.

The embedded media cards (frame, leader line, title, status, original
link) and the hidden YouTube preload are drawn by BhoteKoshiMediaCards,
which bhoteKoshiEmbeddedMedia.js renders into its overlay root with h()
and render() on every change and on a locale change, in place of the
markup it built with createElement and innerHTML. Placement after each
frame, provider loading, preloads, timers and teardown are unchanged. The
script still builds the SDK script and preconnect tags, the overlay root
and the Facebook player node, which is warmed hidden before its card
exists and carried loaded into the card, where the SDK replaces it.

bhoteKoshiControls.test.mjs pins it; the media tests run on a DOM.

Co-authored-by: Manjunath Paparaju <[email protected]>
This commit is contained in:
Sameh KhamisandManjunath Paparaju committed 2026-11-19 13:01:28 -08:00
1 parent bcc25be07a
commit 545beaee87
12 files changed
+614 -269

No files matched your search

+173 -179
View File
@@ -6,6 +6,8 @@ import {
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
import { h, render as renderVue } from 'vue';
import BhoteKoshiMediaCards from '../ui/bhoteKoshi/BhoteKoshiMediaCards.vue';
const YOUTUBE_HOSTS = new Set([
'youtube.com',
@@ -98,6 +100,7 @@ export function bhoteEventText(value) {
let _xWidgetsPromise = null;
let _facebookSdkPromise = null;
let _facebookEmbedSequence = 0;
let _cardSequence = 0;
const youtubeApis = new WeakMap();
function loadYouTubeApi(documentRef, globalRef) {
@@ -682,32 +685,61 @@ export function createBhoteKoshiEmbeddedMedia({
let record = null;
let warmRecord = null;
let generation = 0;
// Text the cards show, kept as the calls that word it so a locale change
// words it again. A node is forgotten once it has left the page.
const worded = new Map();
function forgetDetached() {
for (const node of worded.keys())
if (!node.isConnected) worded.delete(node);
let destroyed = false;
// The cards in the root, in the order they were shown: the current one and
// any still leaving. Their text is kept as the calls that word it, so a
// locale change words it again.
const cards = [];
/** Render the cards and the YouTube preload into the root, synchronously. */
function render() {
if (destroyed) return;
const warmFrame = warmRecord?.frame;
renderVue(
h(BhoteKoshiMediaCards, {
warm: warmFrame
? {
key: warmRecord.key,
src: warmFrame.src,
title: warmFrame.title(),
}
: null,
cards: cards.map((current) => ({
id: current.id,
provider: current.source.provider,
portrait: current.portrait,
entering: current.entering,
leaving: current.leaving,
unavailable: current.unavailable,
label: current.label(),
title: current.title(),
status: current.status(),
url: current.source.url,
frame: current.frame && {
src: current.frame.src,
title: current.frame.title(),
onLoad: current.frame.onLoad,
},
bind: current.bind,
})),
}),
root,
);
}
function word(node, property, text) {
let properties = worded.get(node);
if (!properties) worded.set(node, (properties = new Map()));
properties.set(property, text);
writeWord(node, property, text());
}
function writeWord(node, property, value) {
if (property === 'textContent' || property === 'title')
node[property] = value;
else node.setAttribute(property, value);
}
const offLocale = onLocaleChange(() => {
forgetDetached();
for (const [node, properties] of worded)
for (const [property, text] of properties)
writeWord(node, property, text());
});
const offLocale = onLocaleChange(render);
const leavingRecords = new Set();
/** Word a card's status and draw it. */
function setStatus(current, text) {
current.status = text;
render();
}
/** Mark a card unavailable or not and draw it. */
function setUnavailable(current, unavailable) {
current.unavailable = unavailable;
render();
}
const prefersReducedMotion = () =>
globalRef.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches ===
true;
@@ -848,9 +880,10 @@ export function createBhoteKoshiEmbeddedMedia({
if (current.exitTimer != null) globalRef.clearTimeout?.(current.exitTimer);
destroyFacebookSession(current.facebookSession);
current.youtubeSession?.destroy();
current.card?.remove?.();
const at = cards.indexOf(current);
if (at !== -1) cards.splice(at, 1);
leavingRecords.delete(current);
forgetDetached();
render();
}
const position = () => {
@@ -866,7 +899,8 @@ export function createBhoteKoshiEmbeddedMedia({
current.enterFrame = scheduleFrame(() => {
current.enterFrame = null;
if (token !== generation || record !== current) return;
current.card.classList.add('is-entering');
current.entering = true;
render();
});
}
}
@@ -888,9 +922,10 @@ export function createBhoteKoshiEmbeddedMedia({
removeRecord(current);
return;
}
current.card.classList.remove('is-entering');
current.card.classList.add('is-leaving');
current.entering = false;
current.leaving = true;
leavingRecords.add(current);
render();
current.exitTimer =
globalRef.setTimeout?.(
() => removeRecord(current),
@@ -900,11 +935,10 @@ export function createBhoteKoshiEmbeddedMedia({
function clearWarm(key = null) {
if (!warmRecord || (key && warmRecord.key !== key)) return;
if (warmRecord.facebookSession)
destroyFacebookSession(warmRecord.facebookSession);
else warmRecord.iframe?.remove?.();
const facebookSession = warmRecord.facebookSession;
warmRecord = null;
forgetDetached();
if (facebookSession) destroyFacebookSession(facebookSession);
else render();
}
function takeWarmFacebook(key, host) {
@@ -944,29 +978,26 @@ export function createBhoteKoshiEmbeddedMedia({
warmRecord = { key, facebookSession };
return true;
}
const iframe = documentRef.createElement('iframe');
iframe.className = 'bhote-embedded-media-warmup';
iframe.src = embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
});
word(iframe, 'title', () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
);
iframe.tabIndex = -1;
iframe.setAttribute('aria-hidden', 'true');
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
root.append(iframe);
warmRecord = { key, iframe };
warmRecord = {
key,
frame: {
src: embeddedMediaFrameUrl(source, {
autoplay: false,
startAtSec,
endAtSec,
}),
title: () =>
t('Preloading {provider} media', {
provider: providerLabel(source.provider),
}),
},
};
render();
return true;
}
async function mountX(current, token) {
word(current.status, 'textContent', () => t('LOADING X POST…'));
setStatus(current, () => t('LOADING X POST…'));
try {
const api = await xLoader(documentRef, globalRef);
if (token !== generation || record !== current) return;
@@ -986,14 +1017,12 @@ export function createBhoteKoshiEmbeddedMedia({
throw new Error(
msg('The X post is unavailable or cannot be embedded.'),
);
word(current.status, 'textContent', () =>
t('X POST · PROVIDER CONTROLS'),
);
setStatus(current, () => t('X POST · PROVIDER CONTROLS'));
position();
} catch (error) {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(String(error?.message || msg('X embed unavailable'))),
}),
@@ -1010,16 +1039,14 @@ export function createBhoteKoshiEmbeddedMedia({
session.shouldPlay = autoplay === true;
session.onReady = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('FACEBOOK · PROVIDER CONTROLS'),
);
current.card.classList.remove('is-unavailable');
current.status = () => t('FACEBOOK · PROVIDER CONTROLS');
setUnavailable(current, false);
position();
};
session.onError = (error) => {
if (token !== generation || record !== current) return;
current.card.classList.add('is-unavailable');
word(current.status, 'textContent', () =>
current.unavailable = true;
setStatus(current, () =>
t('{reason} OPEN ORIGINAL.', {
reason: t(
String(error?.message || msg('Facebook embed unavailable')),
@@ -1030,9 +1057,7 @@ export function createBhoteKoshiEmbeddedMedia({
};
session.onPlaybackBlocked = () => {
if (token !== generation || record !== current) return;
word(current.status, 'textContent', () =>
t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'),
);
setStatus(current, () => t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'));
};
if (session.ready) session.onReady();
else if (session.error) session.onError(session.error);
@@ -1078,104 +1103,69 @@ export function createBhoteKoshiEmbeddedMedia({
if (warmRecord && warmRecord.key !== warmKey) clearWarm();
hide({ preserveWarm: true });
const token = ++generation;
const card = documentRef.createElement('section');
const portraitClass = isPortraitMedia(media) ? ' is-portrait' : '';
card.className = `bhote-embedded-callout is-${source.provider}${portraitClass}`;
card.dataset.provider = source.provider;
word(card, 'aria-label', () =>
t('Embedded {provider} media for {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
const leader = documentRef.createElementNS(
'http://www.w3.org/2000/svg',
'svg',
);
leader.classList.add('bhote-embedded-callout-leader');
leader.setAttribute('aria-hidden', 'true');
leader.innerHTML =
'<path pathLength="1" fill="none" stroke="rgba(147,213,228,.72)" stroke-width="1.5"/><circle r="4" fill="#6be8ff" stroke="#ffffff" stroke-width="1.5"/>';
const player = documentRef.createElement('div');
player.className = 'bhote-embedded-callout-player ui-scroll';
const footer = documentRef.createElement('footer');
const title = documentRef.createElement('strong');
word(title, 'textContent', () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
);
const status = documentRef.createElement('small');
status.setAttribute('role', 'status');
word(status, 'textContent', () =>
t('{provider} · EMBEDDED SOURCE', {
provider: providerLabel(source.provider),
}),
);
const link = documentRef.createElement('a');
link.href = source.url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
word(link, 'textContent', () => t('OPEN ORIGINAL ↗'));
footer.append(title, status, link);
const body = documentRef.createElement('div');
body.className = 'bhote-embedded-callout-body';
// The card takes taps (its container and leader do not); Stories keeps that.
body.setAttribute('data-overlay-input', '');
body.append(player, footer);
card.append(leader, body);
root.append(card);
record = {
const providerName = () => providerLabel(source.provider);
const sourceName = () =>
observation?.title
? bhoteEventText(observation.title)
: t('witness source');
const current = {
id: ++_cardSequence,
key,
source,
anchor,
card,
leader,
player,
status,
portrait: isPortraitMedia(media),
entering: false,
leaving: false,
unavailable: false,
label: () =>
t('Embedded {provider} media for {source}', {
provider: providerName(),
source: sourceName(),
}),
title: () =>
bhoteEventText(
observation?.shortTitle || observation?.title || t('Witness source'),
).toUpperCase(),
status: () =>
t('{provider} · EMBEDDED SOURCE', { provider: providerName() }),
frame: null,
frameElement: null,
card: null,
leader: null,
player: null,
entered: false,
};
if (source.provider === 'x') {
void mountX(record, token);
} else if (source.provider === 'facebook') {
bindFacebook(record, token, warmKey, autoplay);
} else {
const iframe = documentRef.createElement('iframe');
iframe.src = embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
});
const controlled =
// The elements the card's view draws: placed after each frame, filled by
// the provider.
current.bind = (name, element) => {
if (element) current[name] = element;
};
let controlled = false;
if (source.provider === 'youtube') {
const url = new URL(
embeddedMediaFrameUrl(source, {
autoplay,
startAtSec,
endAtSec,
}),
);
controlled =
autoplay &&
Number.isFinite(Number(endAtSec)) &&
Number(endAtSec) > startAtSec;
if (controlled) {
const url = new URL(iframe.src);
url.searchParams.set('enablejsapi', '1');
if (globalRef.location?.origin)
url.searchParams.set('origin', globalRef.location.origin);
iframe.src = url.href;
}
word(iframe, 'title', () =>
t('{provider} media: {source}', {
provider: providerLabel(source.provider),
source: observation?.title
? bhoteEventText(observation.title)
: t('witness source'),
}),
);
iframe.allow =
'autoplay; encrypted-media; picture-in-picture; fullscreen';
iframe.allowFullscreen = true;
iframe.loading = 'eager';
iframe.referrerPolicy = 'strict-origin-when-cross-origin';
iframe.addEventListener?.(
'load',
() => {
current.frame = {
src: url.href,
title: () =>
t('{provider} media: {source}', {
provider: providerName(),
source: sourceName(),
}),
onLoad: () => {
if (token !== generation || record?.key !== key) return;
clearWarm(warmKey);
if (
@@ -1184,38 +1174,41 @@ export function createBhoteKoshiEmbeddedMedia({
record.youtubeSession.getState().phase,
)
) {
word(status, 'textContent', () =>
t('{provider} · PROVIDER CONTROLS', {
provider: providerLabel(source.provider),
}),
setStatus(current, () =>
t('{provider} · PROVIDER CONTROLS', { provider: providerName() }),
);
}
position();
},
{ once: true },
);
player.append(iframe);
if (controlled) {
const current = record;
current.youtubeSession = createTrimmedYouTubePlayback({
iframe,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
word(status, 'textContent', () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
};
}
record = current;
cards.push(current);
render();
if (source.provider === 'x') {
void mountX(current, token);
} else if (source.provider === 'facebook') {
bindFacebook(current, token, warmKey, autoplay);
} else if (controlled) {
current.youtubeSession = createTrimmedYouTubePlayback({
iframe: current.frameElement,
endAtSec: Number(endAtSec),
startAtSec,
globalRef,
loadApi: () => youtubeLoader(documentRef, globalRef),
isCurrent: () => token === generation && record === current,
onStatus: (phase) => {
if (phase !== 'completed')
setStatus(current, () =>
t('YOUTUBE {state} · OPEN ORIGINAL', {
state: YOUTUBE_PHASE_LABELS[phase]
? t(YOUTUBE_PHASE_LABELS[phase])
: phase.toUpperCase(),
}),
);
},
});
}
position();
return true;
@@ -1223,11 +1216,12 @@ export function createBhoteKoshiEmbeddedMedia({
function destroy() {
offLocale();
worded.clear();
hide({ immediate: true });
for (const current of [...leavingRecords]) removeRecord(current);
clearWarm();
removePostRender?.();
destroyed = true;
renderVue(null, root);
root.remove();
}
+171 -68
View File
@@ -1,3 +1,4 @@
import '../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
@@ -12,6 +13,31 @@ import {
} from './bhoteKoshiEmbeddedMedia.js';
import { bindRenderer } from '../render/rendererOf.js';
// The cards draw provider frames; the tests never load their pages, and the
// page's note that each one is not loaded is dropped.
window.happyDOM.settings.disableIframePageLoading = true;
const consoleError = console.error;
console.error = (error, ...rest) => {
if (!/Iframe page loading is disabled/.test(String(error?.message)))
consoleError(error, ...rest);
};
/**
* Embedded media in a fresh globe container of the page, and the overlay
* root it renders into.
*/
function domFixture(options = {}) {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const media = createBhoteKoshiEmbeddedMedia({
viewer: { container },
documentRef: document,
globalRef: {},
...options,
});
return { media, container, root: container.firstElementChild };
}
test('Pinokio fallback never creates provider DOM or loads SDKs', async () => {
const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); };
const media = createBhoteKoshiEmbeddedMedia({
@@ -186,31 +212,138 @@ test('trimmed YouTube teardown revokes pending SDK and player callbacks', async
});
test('pausing YouTube removes its frame and rejects a late load from the stopped generation', () => {
const nodes = [];
class Element extends EventTarget {
constructor(tag) { super(); this.tag = tag; this.children = []; this.dataset = {}; this.classList = { add() {}, remove() {} }; nodes.push(this); }
setAttribute() {}
append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {} });
const { media, container, root } = domFixture();
const options = { observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {}, autoplay: true };
assert.equal(media.show(options), true);
const frame = nodes.find((node) => node.tag === 'iframe');
const card = nodes.find((node) => node.tag === 'section');
assert.ok(card.parent);
const card = root.querySelector('section');
const frame = card.querySelector('iframe');
assert.ok(card.isConnected);
assert.equal(media.pause(), true);
assert.equal(card.parent, null);
assert.equal(card.isConnected, false);
frame.dispatchEvent(new Event('load'));
assert.equal(card.parent, null);
assert.equal(root.querySelector('section'), null);
assert.equal(media.show(options), true, 'an explicit replay creates a fresh player');
assert.notEqual(root.querySelector('section iframe'), frame);
media.destroy();
assert.equal(container.children.length, 0);
});
test('a card draws its provider, source, status and original link, and words them again in a new locale', async () => {
const { setLocale } = await import('../i18n/index.js');
const { media, root } = domFixture();
assert.equal(media.show({
observation: { title: 'Flood footage', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k', orientation: 'portrait' } },
anchor: {},
}), true);
const card = root.querySelector('section');
assert.equal(card.className, 'bhote-embedded-callout is-youtube is-portrait');
assert.equal(card.dataset.provider, 'youtube');
assert.equal(card.getAttribute('aria-label'), 'Embedded YOUTUBE media for Flood footage');
const leader = card.firstElementChild;
assert.equal(leader.namespaceURI, 'http://www.w3.org/2000/svg');
assert.equal(leader.getAttribute('class'), 'bhote-embedded-callout-leader');
assert.equal(leader.getAttribute('aria-hidden'), 'true');
assert.equal(leader.querySelector('path').getAttribute('pathLength'), '1');
assert.equal(leader.querySelector('circle').getAttribute('r'), '4');
const body = card.querySelector('.bhote-embedded-callout-body');
assert.equal(body.getAttribute('data-overlay-input'), '');
const player = body.firstElementChild;
assert.equal(player.className, 'bhote-embedded-callout-player ui-scroll');
const frame = player.firstElementChild;
assert.equal(frame.tagName, 'IFRAME');
assert.equal(new URL(frame.src).pathname, '/embed/DbqRexFxv3k');
assert.equal(frame.title, 'YOUTUBE media: Flood footage');
assert.equal(frame.getAttribute('allow'), 'autoplay; encrypted-media; picture-in-picture; fullscreen');
assert.equal(frame.hasAttribute('allowfullscreen'), true);
assert.equal(frame.getAttribute('referrerpolicy'), 'strict-origin-when-cross-origin');
const [title, status, link] = body.querySelector('footer').children;
assert.equal(title.tagName, 'STRONG');
assert.equal(title.textContent, 'FLOOD FOOTAGE');
assert.equal(status.getAttribute('role'), 'status');
assert.equal(status.textContent, 'YOUTUBE · EMBEDDED SOURCE');
assert.equal(link.href, 'https://www.youtube.com/watch?v=DbqRexFxv3k');
assert.equal(link.target, '_blank');
assert.equal(link.rel, 'noopener noreferrer');
assert.equal(link.textContent, 'OPEN ORIGINAL ↗');
frame.dispatchEvent(new Event('load'));
assert.equal(status.textContent, 'YOUTUBE · PROVIDER CONTROLS');
try {
await setLocale('es');
assert.notEqual(link.textContent, 'OPEN ORIGINAL ↗', 'the link is worded again');
assert.notEqual(status.textContent, 'YOUTUBE · PROVIDER CONTROLS', 'the status is worded again');
assert.ok(root.querySelector('section') === card, 'in place');
} finally {
await setLocale('en');
}
media.destroy();
});
test('an X post is built by the provider inside the card and its failure marks the card', async () => {
let fail = false;
const { media, root } = domFixture({
xLoader: async () => ({ widgets: { createTweet: async (id, target) => {
if (fail) return null;
target.append(Object.assign(document.createElement('div'), { className: 'twitter-tweet', textContent: id }));
return {};
} } }),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://x.com/Indowatchosint/status/2092640554568007958' } };
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const status = card.querySelector('[role="status"]');
assert.equal(status.textContent, 'LOADING X POST…');
await new Promise((resolve) => setTimeout(resolve));
assert.equal(card.querySelector('.bhote-embedded-callout-player .twitter-tweet').textContent, '2092640554568007958');
assert.equal(status.textContent, 'X POST · PROVIDER CONTROLS');
assert.equal(card.classList.contains('is-unavailable'), false);
media.hide({ immediate: true });
fail = true;
assert.equal(media.show({ observation, anchor: {} }), true);
await new Promise((resolve) => setTimeout(resolve));
const failed = root.querySelector('section');
assert.ok(failed.classList.contains('is-unavailable'));
assert.equal(failed.querySelector('[role="status"]').textContent, 'The X post is unavailable or cannot be embedded. OPEN ORIGINAL.');
media.destroy();
});
test('a warmed Facebook player moves into the card and stays through its redraws', async () => {
let ready;
const { media, root } = domFixture({
facebookLoader: async () => ({
Event: { subscribe(_name, callback) { ready = callback; }, unsubscribe() {} },
XFBML: { parse() {} },
}),
});
const observation = { title: 'Clip', media: { sourceUrl: 'https://www.facebook.com/reel/1571491657757829' } };
media.warm({ observation });
await Promise.resolve(); await Promise.resolve();
const host = root.querySelector('.bhote-embedded-media-warmup');
const embed = host.querySelector('.fb-video');
assert.equal(media.show({ observation, anchor: {} }), true);
const card = root.querySelector('section');
const player = card.querySelector('.bhote-embedded-callout-player');
assert.ok(host.parentNode === player, 'the warmed player is carried over, not rebuilt');
assert.equal(host.className, 'bhote-facebook-player-host');
assert.equal(host.hasAttribute('aria-hidden'), false);
ready({ type: 'video', id: embed.id, instance: { mute() {}, play() {}, pause() {} } });
assert.equal(card.querySelector('[role="status"]').textContent, 'FACEBOOK · PROVIDER CONTROLS');
assert.ok(host.parentNode === player, 'a redraw keeps the provider player');
media.destroy();
});
test('a leaving card animates out and is removed after its exit', () => {
const timers = [];
const { media, root } = domFixture({ globalRef: { setTimeout: (fn) => timers.push(fn), clearTimeout() {} } });
media.show({ observation: { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {} });
const card = root.querySelector('section');
card.hidden = false;
media.hide();
assert.ok(card.isConnected);
assert.ok(card.classList.contains('is-leaving'));
assert.equal(card.classList.contains('is-entering'), false);
timers.forEach((fn) => fn());
assert.equal(card.isConnected, false);
media.destroy();
assert.equal(documentRef.body.children.length, 0);
});
test('resolves supported embedded callout providers from canonical public URLs', () => {
@@ -303,28 +436,8 @@ test('Mailung playback stops at source timestamp 0:07 without changing other cli
});
function preloadFixture(options = {}) {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
append(...children) {
for (const child of children) { child.remove(); child.parent = this; this.children.push(child); }
}
remove() {
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
this.parent = null;
}
}
const documentRef = {
body: new Element('body'),
createElement: tag => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {}, ...options });
return { media, root: documentRef.body.children[0] };
const { media, root } = domFixture(options);
return { media, root };
}
for (const operation of ['pause', 'hide', 'destroy']) {
@@ -343,16 +456,18 @@ test('camera updates retain a preload until the visible player loads', () => {
const observation = { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } };
media.warm({ observation });
const frame = root.children[0];
assert.equal(frame.className, 'bhote-embedded-media-warmup');
assert.equal(frame.getAttribute('aria-hidden'), 'true');
assert.equal(frame.tabIndex, -1);
assert.equal(frame.title, 'Preloading YOUTUBE media');
media.hide({ preserveWarm: true });
media.warm({ observation });
assert.equal(root.children[0], frame);
assert.ok(root.children[0] === frame);
assert.equal(media.show({ observation, anchor: {} }), true);
assert.equal(frame.parent, root, 'keep the preload while the visible player starts');
const card = root.children.find(node => node.tag === 'section');
const body = card.children.find(node => node.className === 'bhote-embedded-callout-body');
const player = body.children.find(node => node.className.split(' ').includes('bhote-embedded-callout-player'));
player.children.find(node => node.tag === 'iframe').dispatchEvent(new Event('load'));
assert.equal(frame.parent, null, 'visible player readiness releases the preload');
assert.ok(frame.parentNode === root, 'keep the preload while the visible player starts');
root.querySelector('section .bhote-embedded-callout-body > .bhote-embedded-callout-player > iframe')
.dispatchEvent(new Event('load'));
assert.equal(frame.isConnected, false, 'visible player readiness releases the preload');
media.destroy();
assert.equal(root.children.length, 0);
});
@@ -420,25 +535,9 @@ test('a media card stays between the panels when right-to-left swaps their sides
});
test('a shown card follows its anchor through the renderer ports', () => {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
querySelector() { return null; }
getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; }
append(...children) { for (const child of children) { child.remove(); child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const listeners = new Set();
const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
const container = document.body.appendChild(document.createElement('div'));
const viewer = { container, canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } };
const projected = [];
// The renderer's canvas, not the viewer's, places the card.
@@ -454,14 +553,18 @@ test('a shown card follows its anchor through the renderer ports', () => {
},
},
});
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} });
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef: document, globalRef: {} });
const root = container.firstElementChild;
root.getBoundingClientRect = () => ({ left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 });
assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']);
const anchor = { x: 10, y: 0, z: 0 };
assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true);
const card = documentRef.body.children[0].children.find((node) => node.tag === 'section');
const card = root.querySelector('section');
assert.equal(card.hidden, false);
assert.equal(projected.at(-1), anchor);
assert.equal(card.style.left, `${300 + 10 + 42}px`);
// The leader runs from the anchor to the card's near edge.
assert.equal(card.querySelector('path').getAttribute('d'), `M ${300 + 10 - 352} ${200 + 5 - parseFloat(card.style.top)} L 0 ${Math.max(16, Math.min(360 - 16, 200 + 5 - parseFloat(card.style.top)))}`);
// Behind the eye: hidden on the next drawn frame.
pose = { ...pose, direction: { x: -1, y: 0, z: 0 } };
for (const [, cb] of listeners) cb();
+3 -2
View File
@@ -989,9 +989,10 @@ function createPanelRecords(event) {
textContent: t('▶ PLAY SCENE'),
hidden: true,
}),
// `pressed` is the button's pressed state; the view renders it as one.
cinematicButton: panelRecord({
textContent: t('◉ CINEMATIC'),
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: panelRecord({ textContent: t('↺ FULL STORY') }),
corridorButton: panelRecord(),
@@ -2860,7 +2861,7 @@ export function createBhoteKoshiEventLayer({
'textContent',
_cinematicActive ? t('■ RELEASE CAMERA') : t('◉ CINEMATIC'),
);
setElementAttribute(button, 'aria-pressed', String(_cinematicActive));
setElementProperty(button, 'pressed', _cinematicActive);
return true;
}
+8 -1
View File
@@ -38,7 +38,7 @@ function presentation(patch = {}) {
playSceneButton: record({ textContent: '▶ PLAY SCENE', hidden: true }),
cinematicButton: record({
textContent: '◉ CINEMATIC',
attributes: { 'aria-pressed': 'false' },
pressed: false,
}),
storyReplayButton: record({ textContent: '↺ FULL STORY' }),
corridorButton: record(),
@@ -156,6 +156,10 @@ test('a later presentation updates the controls in place', async (t) => {
disabled: true,
attributes: { 'aria-label': 'Play Global context' },
});
next.refs.cinematicButton = record({
textContent: '■ RELEASE CAMERA',
pressed: true,
});
next.refs.progressInput = record({ value: '250', hidden: true });
next.refs.imagerySection = record({ hidden: true });
store.publish(next);
@@ -164,6 +168,9 @@ test('a later presentation updates the controls in place', async (t) => {
assert.equal(play.textContent, '▶ PLAY SHOT');
assert.equal(play.disabled, true);
assert.equal(play.getAttribute('aria-label'), 'Play Global context');
const cinematic = $('[data-action="cinematic"]');
assert.equal(cinematic.getAttribute('aria-pressed'), 'true');
assert.equal(cinematic.textContent, '■ RELEASE CAMERA');
assert.ok(
$('#bhote-koshi-event-panel').classList.contains('bhote-event-scene-beat'),
);