2026-11-15 08:45:17 -08:00
( function () {
'use strict' ;
var body = document . body ;
var widget = body . getAttribute ( 'data-widget' );
var endpoint = body . getAttribute ( 'data-endpoint' );
var poll = Math . max ( 1000 , parseInt ( body . getAttribute ( 'data-poll' ), 10 ) || 2500 );
var root = document . getElementById ( 'sg-root' );
2026-11-15 12:26:03 -08:00
var etag = null , failures = 0 , skew = 0 , timerState = null ;
2026-11-15 08:45:17 -08:00
var queue = [], showing = false ;
function el ( tag , cls , text ) {
var e = document . createElement ( tag );
if ( cls ) e . className = cls ;
if ( text != null ) e . textContent = text ;
return e ;
}
// ---- goal ----
2026-11-15 13:09:18 -08:00
var goal = null , shownRaised = 0 , raf = 0 , lastTierKey = null , celebrateTimer = 0 ;
2026-11-15 08:45:17 -08:00
function renderGoal ( d ) {
2026-11-15 13:09:18 -08:00
if ( ! d . active ) { root . textContent = '' ; goal = null ; lastTierKey = null ; return ; }
2026-11-15 08:45:17 -08:00
if ( ! goal ) {
root . textContent = '' ;
var card = el ( 'div' , 'sg-card' );
2026-11-15 13:09:18 -08:00
goal = { card : card , tier : el ( 'div' , 'sg-tier' ), title : el ( 'div' , 'sg-title' ), fill : el ( 'div' , 'sg-fill' ), pct : el ( 'div' , 'sg-pct' ),
2026-11-15 08:45:17 -08:00
raised : el ( 'span' ), target : el ( 'span' ) };
var track = el ( 'div' , 'sg-track' );
track . appendChild ( goal . fill ); track . appendChild ( goal . pct );
var nums = el ( 'div' , 'sg-nums' ); nums . appendChild ( goal . raised ); nums . appendChild ( goal . target );
2026-11-15 13:09:18 -08:00
goal . tier . hidden = true ;
card . appendChild ( goal . title ); card . appendChild ( goal . tier ); card . appendChild ( track ); card . appendChild ( nums );
2026-11-15 08:45:17 -08:00
root . appendChild ( card );
}
goal . title . textContent = d . title ;
goal . target . textContent = d . target_display ;
goal . fill . style . width = d . percent + '%' ;
goal . pct . textContent = d . percent + '%' ;
2026-11-15 13:09:18 -08:00
renderTier ( d . tiers );
2026-11-15 08:45:17 -08:00
tweenRaised ( d );
}
2026-11-15 13:09:18 -08:00
// Tiered goals only (d.tiers present): "Tier 2 of 4 \u00b7 title" above the bar, or "All tiers unlocked!".
// Untiered goals keep the tier line hidden, so they look exactly as before. textContent only.
function renderTier ( t ) {
var valid = t && typeof t === 'object' && isFinite ( Number ( t . count )) && Number ( t . count ) > 0 ;
goal . tier . hidden = ! valid ;
goal . card . classList . toggle ( 'sg-tiered' , !! valid );
goal . card . classList . toggle ( 'sg-tiers-done' , !! ( valid && t . all_reached ));
if ( ! valid ) { goal . tier . textContent = '' ; lastTierKey = null ; return ; }
var cur = t . current && typeof t . current === 'object' ? t . current : null ;
goal . tier . textContent = t . all_reached || ! cur
? 'All tiers unlocked!'
: 'Tier ' + parseInt ( t . index , 10 ) + ' of ' + parseInt ( t . count , 10 ) + ' \u00b7 ' + String ( cur . title || '' );
// Celebrate when the current tier changed between polls (never on the first poll / after a reload).
var key = ( t . all_reached ? 'done' : String ( t . index )) + '/' + t . count ;
if ( lastTierKey !== null && lastTierKey !== key ) {
goal . card . classList . remove ( 'sg-tier-up' );
void goal . card . offsetWidth ; // restart the animation
goal . card . classList . add ( 'sg-tier-up' );
clearTimeout ( celebrateTimer );
var card = goal . card ;
celebrateTimer = setTimeout ( function () { card . classList . remove ( 'sg-tier-up' ); }, 2600 );
}
lastTierKey = key ;
}
2026-11-15 08:45:17 -08:00
function tweenRaised ( d ) {
cancelAnimationFrame ( raf );
var from = shownRaised , to = d . raised_minor , t0 = performance . now (), dur = 1200 ;
var sym = d . raised_display . replace ( /[\d.,]+$/ , '' );
var dec = /\.\d+$/ . test ( d . raised_display ) ? 2 : 0 ;
function fmt ( minor ) {
var v = dec ? minor / 100 : minor ;
return sym + v . toLocaleString ( 'en-US' , { minimumFractionDigits : dec , maximumFractionDigits : dec });
}
function step ( now ) {
var p = Math . min ( 1 , ( now - t0 ) / dur ), e = 1 - Math . pow ( 1 - p , 3 );
shownRaised = Math . round ( from + ( to - from ) * e );
goal . raised . textContent = p >= 1 ? d . raised_display : fmt ( shownRaised );
if ( p < 1 ) raf = requestAnimationFrame ( step );
}
raf = requestAnimationFrame ( step );
}
// ---- timer ----
var timerEls = null ;
function renderTimer ( d , receivedAtMs ) {
timerState = d ;
// skew = serverClock - clientClock, measured at receipt, so local ticking is immune to a wrong PC clock.
skew = d . server_now - receivedAtMs / 1000 ;
if ( ! timerEls ) {
root . textContent = '' ;
var card = el ( 'div' , 'sg-card' ); timerEls = { big : el ( 'div' , 'sg-big' , '--:--:--' ) };
card . appendChild ( timerEls . big ); root . appendChild ( card );
}
}
function pad ( n ) { return ( n < 10 ? '0' : '' ) + n ; }
function tickTimer () {
var d = timerState ;
if ( d && timerEls ) {
var rem ;
if ( ! d . active ) rem = null ;
else if ( d . paused ) rem = d . remaining_seconds ;
else rem = Math . max ( 0 , Math . ceil ( d . ends_at - ( Date . now () / 1000 + skew )));
if ( rem === null ) timerEls . big . textContent = '--:--:--' ;
else timerEls . big . textContent = pad ( Math . floor ( rem / 3600 )) + ':' + pad ( Math . floor ( rem / 60 ) % 60 ) + ':' + pad ( rem % 60 );
timerEls . big . classList . toggle ( 'sg-expired' , rem === 0 );
timerEls . big . classList . toggle ( 'sg-paused' , !! ( d && d . paused ));
}
setTimeout ( tickTimer , 250 );
}
// ---- counter ----
function renderCounter ( d ) {
root . textContent = '' ;
var card = el ( 'div' , 'sg-card' );
card . appendChild ( el ( 'div' , 'sg-big' , Number ( d . value ). toLocaleString ( 'en-US' )));
if ( d . label ) card . appendChild ( el ( 'div' , 'sg-label' , d . label ));
root . appendChild ( card );
}
// ---- alerts ----
2026-11-15 12:26:03 -08:00
// Why not a `since` cursor: with moderation, a held donation keeps a low id. If a newer donation is shown
// first, the cursor moves past it and the later approval would never be returned. So we poll ?recent=1
// (newest 20 approved alerts) and dedupe by id here. First successful poll only seeds seenIds, so
// refreshing OBS never replays old alerts. Limit: a message approved after 20+ newer donations is
// no longer in the window and is not shown.
var seenIds = {}, seenOrder = [], firstAlertPoll = true , SEEN_MAX = 200 ;
function markSeen ( id ) {
seenIds [ id ] = true ; seenOrder . push ( id );
while ( seenOrder . length > SEEN_MAX ) delete seenIds [ seenOrder . shift ()];
}
2026-11-15 08:45:17 -08:00
function renderAlerts ( d ) {
2026-11-15 12:26:03 -08:00
var list = ( d . alerts || []). slice (). sort ( function ( a , b ) { return a . id - b . id ; });
for ( var i = 0 ; i < list . length ; i ++ ) {
var a = list [ i ];
if ( seenIds [ a . id ]) continue ;
markSeen ( a . id );
if ( ! firstAlertPoll ) queue . push ( a );
}
firstAlertPoll = false ;
2026-11-15 08:45:17 -08:00
next ();
}
2026-11-15 13:01:31 -08:00
// Alert media (optional per alert): {visual:{type,url}|null, sound:{url}|null, volume, duration_ms, message}.
// Everything is built with createElement + property assignment; nothing from the server is parsed as HTML.
var MEDIA_TIMEOUT = 8000 , DEFAULT_HOLD = 6500 , VIDEO_CAP = 30000 ;
function okUrl ( u ) { return typeof u === 'string' && /^(https?:\/\/|\/)/i . test ( u ); }
function cleanMedia ( m ) {
if ( ! m || typeof m !== 'object' ) return null ;
var v = m . visual && typeof m . visual === 'object' && okUrl ( m . visual . url ) && ( m . visual . type === 'image' || m . visual . type === 'video' ) ? m . visual : null ;
var s = m . sound && typeof m . sound === 'object' && okUrl ( m . sound . url ) ? m . sound : null ;
var msg = typeof m . message === 'string' && m . message ? m . message : null ;
if ( ! v && ! s && ! msg ) return null ;
var vol = Number ( m . volume ); if ( ! isFinite ( vol )) vol = 80 ;
var dur = Number ( m . duration_ms ); if ( ! isFinite ( dur ) || dur <= 0 ) dur = DEFAULT_HOLD ;
return { visual : v , sound : s , volume : Math . max ( 0 , Math . min ( 100 , vol )) / 100 , duration : Math . max ( 1000 , Math . min ( 60000 , dur )), message : msg };
}
// Loads visual + sound before the card appears (no flash of an empty frame). Anything that fails or takes
// longer than MEDIA_TIMEOUT is dropped, so the alert falls back to text and the queue never stalls.
function preload ( m , cb ) {
var out = { visual : null , sound : null }, pending = 0 , fired = false , timer = 0 ;
function finish () { if ( fired ) return ; fired = true ; clearTimeout ( timer ); cb ( out ); }
function part () { pending ++ ; var once = false ; return function ( ok , set ) { if ( once ) return ; once = true ; if ( ok && set ) set (); if ( -- pending <= 0 ) finish (); }; }
try {
if ( m . visual ) {
var vd = part ();
if ( m . visual . type === 'image' ) {
var img = new Image ();
img . onload = function () { vd ( true , function () { out . visual = img ; }); };
img . onerror = function () { vd ( false ); };
img . src = m . visual . url ;
} else {
var vid = document . createElement ( 'video' );
vid . preload = 'auto' ; vid . playsInline = true ; vid . muted = true ;
vid . setAttribute ( 'playsinline' , '' ); vid . setAttribute ( 'muted' , '' );
vid . onloadeddata = function () { vd ( true , function () { out . visual = vid ; }); };
vid . onerror = function () { vd ( false ); };
vid . src = m . visual . url ;
try { vid . load (); } catch ( e ) { vd ( false ); }
}
}
if ( m . sound ) {
var sd = part ();
var au = new Audio ();
au . preload = 'auto' ;
au . oncanplaythrough = function () { sd ( true , function () { out . sound = au ; }); };
au . onerror = function () { sd ( false ); };
au . src = m . sound . url ;
try { au . load (); } catch ( e2 ) { sd ( false ); }
}
} catch ( e3 ) { /* fall through to the timeout/finish below */ }
if ( ! pending ) { finish (); return ; }
timer = setTimeout ( finish , MEDIA_TIMEOUT );
}
2026-11-15 08:45:17 -08:00
function next () {
if ( showing || ! queue . length ) return ;
showing = true ;
var a = queue . shift ();
2026-11-15 13:01:31 -08:00
var m = null ;
try { m = cleanMedia ( a . media ); } catch ( e ) { m = null ; }
if ( ! m ) { present ( a , null , null ); return ; }
var called = false ;
function go ( assets ) { if ( called ) return ; called = true ; try { present ( a , m , assets ); } catch ( err ) { forceDone (); } }
try { preload ( m , go ); } catch ( e2 ) { go ({ visual : null , sound : null }); }
}
function forceDone () { root . textContent = '' ; showing = false ; setTimeout ( next , 0 ); }
function present ( a , m , assets ) {
2026-11-15 08:45:17 -08:00
root . textContent = '' ;
var card = el ( 'div' , 'sg-alert' );
var head = el ( 'div' , 'sg-alert-head' );
2026-11-15 13:01:31 -08:00
var vis = assets && assets . visual , snd = assets && assets . sound ;
if ( vis ) {
var box = el ( 'div' , 'sg-alert-media' );
box . appendChild ( vis );
card . appendChild ( box );
card . classList . add ( 'sg-has-media' );
}
if ( m && m . message ) {
head . textContent = m . message ;
} else {
head . appendChild ( el ( 'b' , null , a . name ));
head . appendChild ( document . createTextNode ( ' donated ' ));
head . appendChild ( el ( 'b' , null , a . amount_display ));
}
2026-11-15 08:45:17 -08:00
card . appendChild ( head );
2026-11-15 12:07:06 -08:00
var bonuses = Array . isArray ( a . bonuses ) ? a . bonuses : [];
if ( bonuses . length ) {
card . classList . add ( 'sg-bonus' );
for ( var j = 0 ; j < bonuses . length ; j ++ ) {
card . appendChild ( el ( 'div' , 'sg-bonus-line' , 'BONUS: ' + String ( bonuses [ j ]) + '!' ));
}
}
2026-11-15 12:36:28 -08:00
var acts = Array . isArray ( a . actions ) ? a . actions : [];
2026-11-15 13:09:18 -08:00
var tiersUnlocked = Array . isArray ( a . tiers ) ? a . tiers : [];
if ( acts . length || tiersUnlocked . length ) card . classList . add ( 'sg-bonus' );
2026-11-15 12:36:28 -08:00
for ( var k = 0 ; k < acts . length ; k ++ ) {
var times = parseInt ( acts [ k ]. times , 10 ) || 1 ;
card . appendChild ( el ( 'div' , 'sg-bonus-line' , 'ACTION: ' + String ( acts [ k ]. title ) + ( times > 1 ? ' x' + times : '' )));
}
2026-11-15 13:09:18 -08:00
for ( var q = 0 ; q < tiersUnlocked . length ; q ++ ) {
var tt = tiersUnlocked [ q ] && tiersUnlocked [ q ]. title ;
if ( tt ) card . appendChild ( el ( 'div' , 'sg-bonus-line sg-tier-line' , 'TIER UNLOCKED: ' + String ( tt )));
}
2026-11-15 08:45:17 -08:00
if ( a . message ) card . appendChild ( el ( 'div' , 'sg-alert-msg' , a . message ));
root . appendChild ( card );
2026-11-15 13:01:31 -08:00
var finished = false , holdTimer = 0 , capTimer = 0 ;
function stopMedia () {
try { if ( snd ) snd . pause (); } catch ( e ) { /* ignore */ }
try { if ( vis && vis . tagName === 'VIDEO' ) { vis . pause (); vis . removeAttribute ( 'src' ); vis . load (); } } catch ( e2 ) { /* ignore */ }
}
function exit () {
if ( finished ) return ;
finished = true ;
clearTimeout ( holdTimer ); clearTimeout ( capTimer );
stopMedia ();
2026-11-15 08:45:17 -08:00
card . classList . add ( 'sg-out' );
setTimeout ( function () { root . textContent = '' ; showing = false ; next (); }, 500 );
2026-11-15 13:01:31 -08:00
}
var hold = m ? m . duration : DEFAULT_HOLD , isVideo = false ;
if ( snd ) {
try {
snd . volume = m . volume ; snd . currentTime = 0 ;
var sp = snd . play ();
if ( sp && typeof sp . catch === 'function' ) sp . catch ( function () { /* autoplay blocked: silent alert */ });
} catch ( e3 ) { /* ignore */ }
}
if ( vis && vis . tagName === 'VIDEO' ) {
isVideo = true ;
try {
vis . loop = false ;
vis . muted = !! snd || m . volume === 0 ; // a separate sound wins; otherwise the clip's own audio at the set volume
vis . volume = m . volume ;
vis . onended = exit ;
vis . onerror = exit ;
var vp = vis . play ();
if ( vp && typeof vp . catch === 'function' ) {
vp . catch ( function () {
// Autoplay with sound refused: retry muted so the picture still plays; give up (text only) if that fails too.
try {
vis . muted = true ;
var again = vis . play ();
if ( again && typeof again . catch === 'function' ) again . catch ( function () { if ( vis . parentNode ) vis . parentNode . removeChild ( vis ); clearTimeout ( capTimer ); holdTimer = setTimeout ( exit , DEFAULT_HOLD ); });
} catch ( e4 ) { exit (); }
});
}
} catch ( e5 ) { isVideo = false ; }
}
if ( isVideo ) capTimer = setTimeout ( exit , VIDEO_CAP ); // videos play to the end, never longer than 30 s
else holdTimer = setTimeout ( exit , hold );
2026-11-15 08:45:17 -08:00
}
2026-11-15 12:36:28 -08:00
// ---- actions (reward menu) ----
2026-11-15 12:53:07 -08:00
// Renders nothing visible when there are no actions. The card hugs its content and the text is scaled to the
// LARGEST size that still fits the browser-source window (shrinks for long lists, grows for short ones), and
// re-fits when the window is resized. Only if even the smallest size does not fit does it fall back to a gentle scroll.
var actionsSig = null , menuEls = null , fitTimer = 0 ;
var MENU_MIN = 0.5 , MENU_MAX = 1.8 ;
function fitMenu () {
if ( ! menuEls ) return ;
var card = menuEls . card , view = menuEls . view , track = menuEls . track , ul = menuEls . ul ;
// reset any previous scroll fallback
track . classList . remove ( 'sg-scrolling' );
while ( track . children . length > 1 ) track . removeChild ( track . lastChild );
view . style . height = '' ;
var cs = getComputedStyle ( root );
var inner = root . clientHeight - parseFloat ( cs . paddingTop ) - parseFloat ( cs . paddingBottom );
if ( inner <= 0 ) return ;
function fits ( scale ) {
card . style . setProperty ( '--sg-menu-scale' , String ( scale ));
return card . offsetHeight <= inner ;
}
var lo = MENU_MIN , hi = MENU_MAX , best = null ;
if ( fits ( hi )) { best = hi ; }
else if ( ! fits ( lo )) { best = null ; }
else { for ( var i = 0 ; i < 9 ; i ++ ) { var mid = ( lo + hi ) / 2 ; if ( fits ( mid )) { lo = mid ; } else { hi = mid ; } } best = lo ; }
if ( best !== null ) { card . style . setProperty ( '--sg-menu-scale' , String ( best )); return ; }
// Even the smallest size overflows: use the smallest and scroll gently inside the window.
card . style . setProperty ( '--sg-menu-scale' , String ( MENU_MIN ));
var chrome = card . offsetHeight - view . offsetHeight ;
view . style . height = Math . max ( 40 , inner - chrome ) + 'px' ;
var dup = ul . cloneNode ( true );
dup . setAttribute ( 'aria-hidden' , 'true' );
track . appendChild ( dup );
track . style . setProperty ( '--sg-scroll-s' , Math . max ( 8 , menuEls . count * 3 ) + 's' );
track . classList . add ( 'sg-scrolling' );
}
function scheduleFit () { clearTimeout ( fitTimer ); fitTimer = setTimeout ( fitMenu , 120 ); }
window . addEventListener ( 'resize' , scheduleFit );
if ( typeof ResizeObserver === 'function' ) { try { new ResizeObserver ( scheduleFit ). observe ( document . documentElement ); } catch ( e ) { /* resize event is the fallback */ } }
2026-11-15 12:36:28 -08:00
function renderActions ( d ) {
var list = Array . isArray ( d . actions ) ? d . actions : [];
var sig = JSON . stringify ( list );
if ( sig === actionsSig ) return ;
actionsSig = sig ;
root . textContent = '' ;
2026-11-15 12:53:07 -08:00
menuEls = null ;
2026-11-15 12:36:28 -08:00
if ( ! d . active || ! list . length ) return ;
var card = el ( 'div' , 'sg-card sg-menu' );
var view = el ( 'div' , 'sg-menu-view' );
var ul = el ( 'ul' , 'sg-menu-list' );
list . forEach ( function ( a ) {
var li = el ( 'li' , 'sg-menu-item' );
var lead = ( a . mode === 'every' ? 'Every ' : '' ) + a . amount_display ;
li . appendChild ( el ( 'b' , null , lead ));
li . appendChild ( document . createTextNode ( ' \u2014 ' + String ( a . title )));
if ( a . description ) li . appendChild ( el ( 'span' , 'sg-menu-desc' , String ( a . description )));
ul . appendChild ( li );
});
var track = el ( 'div' , 'sg-menu-track' );
track . appendChild ( ul );
view . appendChild ( track );
card . appendChild ( view );
root . appendChild ( card );
2026-11-15 12:53:07 -08:00
menuEls = { card : card , view : view , track : track , ul : ul , count : list . length };
requestAnimationFrame ( fitMenu );
2026-11-15 12:36:28 -08:00
}
2026-11-15 08:45:17 -08:00
// ---- polling ----
function url () {
var u = endpoint ;
2026-11-15 12:26:03 -08:00
if ( widget === 'alerts' ) u += ( u . indexOf ( '?' ) < 0 ? '?' : '&' ) + 'recent=1' ;
2026-11-15 08:45:17 -08:00
return u ;
}
function schedule () {
var delay = failures ? Math . min ( 15000 , poll * Math . pow ( 2 , Math . min ( failures , 3 ))) : poll ;
setTimeout ( tick , delay );
}
function tick () {
var ctrl = typeof AbortController === 'function' ? new AbortController () : null ;
var to = ctrl ? setTimeout ( function () { ctrl . abort (); }, 8000 ) : 0 ;
var headers = { 'Accept' : 'application/json' };
if ( etag ) headers [ 'If-None-Match' ] = etag ;
fetch ( url (), { headers : headers , cache : 'no-store' , signal : ctrl ? ctrl . signal : undefined })
. then ( function ( r ) {
clearTimeout ( to );
if ( r . status === 304 ) return null ;
if ( ! r . ok ) throw new Error ( 'http ' + r . status );
var et = r . headers . get ( 'ETag' );
return r . json (). then ( function ( j ) { etag = et ; return j ; });
})
. then ( function ( d ) {
failures = 0 ; body . classList . remove ( 'sg-offline' );
if ( d ) apply ( d );
schedule ();
})
. catch ( function () {
clearTimeout ( to );
failures ++ ; if ( failures >= 2 ) body . classList . add ( 'sg-offline' ); // keep last good state on screen
schedule ();
});
}
function apply ( d ) {
var now = Date . now ();
if ( widget === 'goal' ) renderGoal ( d );
else if ( widget === 'timer' ) renderTimer ( d , now );
else if ( widget === 'counter' ) renderCounter ( d );
else if ( widget === 'alerts' ) renderAlerts ( d );
2026-11-15 12:36:28 -08:00
else if ( widget === 'actions' ) renderActions ( d );
2026-11-15 08:45:17 -08:00
}
if ( widget === 'timer' ) tickTimer ();
tick ();
})();