Files
shadowdaoandClaude Sonnet 5.5 9249b80cb6
Test and Release / test (push) Successful in 1m16s
Test and Release / release (push) Successful in 5s
Donation form: non-refundable notice under the PayPal buttons (editable in Settings)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:34:54 -08:00

247 lines
13 KiB
JavaScript

/* StreamGoals donate form (vanilla JS). Config comes from window.StreamGoalsDonate. */
(function () {
'use strict';
var C = window.StreamGoalsDonate;
if (!C) { return; }
var T = C.i18n || {};
var sdkPromise = null, sdkCurrency = null;
function el(tag, attrs, children) {
var n = document.createElement(tag);
Object.keys(attrs || {}).forEach(function (k) {
if (k === 'text') { n.textContent = attrs[k]; } else { n.setAttribute(k, attrs[k]); }
});
(children || []).forEach(function (c) { n.appendChild(c); });
return n;
}
function row(children) { return el('div', { 'class': 'sg-row' }, children); }
function api(path, opts) {
opts = opts || {};
return fetch(C.restUrl + path, {
method: opts.method || 'GET',
headers: { 'Content-Type': 'application/json' },
body: opts.body ? JSON.stringify(opts.body) : undefined,
credentials: 'omit'
}).then(function (r) {
return r.json().then(function (j) {
if (!r.ok) { var e = new Error(j && j.message ? j.message : T.error); e.status = r.status; throw e; }
return j;
}, function () { if (!r.ok) { throw new Error(T.error); } return {}; });
});
}
// The PayPal SDK is bound to one currency per page load; reload it if the selected goal differs.
function loadSdk(currency) {
if (sdkPromise && sdkCurrency === currency) { return sdkPromise; }
var old = document.getElementById('sg-paypal-sdk');
if (old) { old.parentNode.removeChild(old); try { delete window.paypal; } catch (e) { window.paypal = undefined; } }
sdkCurrency = currency;
sdkPromise = new Promise(function (resolve, reject) {
var s = document.createElement('script');
s.id = 'sg-paypal-sdk';
s.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(C.clientId) +
'&currency=' + encodeURIComponent(currency) + '&intent=capture&components=buttons' +
((C.disableFunding && C.disableFunding.length) ? '&disable-funding=' + encodeURIComponent(C.disableFunding.join(',')) : '');
s.onload = function () { window.paypal ? resolve(window.paypal) : reject(new Error(T.sdkError)); };
s.onerror = function () { reject(new Error(T.sdkError)); };
document.head.appendChild(s);
});
return sdkPromise;
}
function fmt(minor, exp, cur) {
var v = minor / Math.pow(10, exp);
try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: cur }).format(v); }
catch (e) { return v.toFixed(exp) + ' ' + cur; }
}
// Preset buttons, minus any below the minimum donation (values are whole currency units, or minor units for zero-decimal).
function presets(exp) {
var base = exp === 0 ? [500, 1000, 2500, 5000] : [5, 10, 25, 50];
return base.filter(function (p) { return (exp === 0 ? p : p * 100) >= (C.minMinor || 0); });
}
function sprintf1(tpl, v) { return String(tpl || '%s').replace('%s', v); }
function init(root) {
var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0;
var goals = C.goals.filter(function (g) { return !pinned || g.id === pinned; });
if (!goals.length) { return; }
var uid = 'sg' + Math.random().toString(36).slice(2, 8);
var state = { goal: goals[0], renderToken: 0, quote: null };
var goalSel = el('select', { id: uid + '-goal' });
goals.forEach(function (g) { goalSel.appendChild(el('option', { value: g.id, text: g.title + ' (' + g.currency + ')' })); });
var amount = el('input', { type: 'text', inputmode: 'decimal', id: uid + '-amt', autocomplete: 'off', placeholder: T.customPlaceholder || 'Other amount', 'aria-describedby': uid + '-hint ' + uid + '-total' });
var hint = el('div', { 'class': 'sg-hint', id: uid + '-hint' });
var presetBox = el('div', { 'class': 'sg-presets' });
var name = el('input', { type: 'text', id: uid + '-name', maxlength: '100', autocomplete: 'nickname' });
var anon = el('input', { type: 'checkbox', id: uid + '-anon' });
var msg = el('textarea', { id: uid + '-msg', rows: '3', maxlength: String(C.messageMax) });
var cover = el('input', { type: 'checkbox', id: uid + '-cover' });
var total = el('div', { 'class': 'sg-total', id: uid + '-total', 'aria-live': 'polite' });
var status = el('div', { 'class': 'sg-msg', role: 'status' });
var buttons = el('div', { 'class': 'sg-buttons' });
// "Next unlock" line for tiered goals (server computes title + remaining minor units per goal).
var nextLine = el('p', { 'class': 'sg-next-unlock', 'aria-live': 'polite' });
nextLine.hidden = true;
function showNext() {
var n = state.goal.nextUnlock;
if (!n || !n.title || !(n.remaining_minor > 0)) { nextLine.hidden = true; nextLine.textContent = ''; return; }
nextLine.textContent = String(T.nextUnlock || 'Next unlock: %1$s \u2014 %2$s to go')
.replace('%1$s', function () { return n.title; })
.replace('%2$s', function () { return fmt(n.remaining_minor, state.goal.exp, state.goal.currency); });
nextLine.hidden = false;
}
root.appendChild(nextLine);
if (goals.length > 1) { root.appendChild(row([el('label', { 'for': uid + '-goal', text: T.goal }), goalSel])); }
root.appendChild(row([el('label', { text: T.amount }), presetBox, el('label', { 'class': 'sg-sub', 'for': uid + '-amt', text: T.customAmount || 'Or enter your own amount' }), amount, hint]));
var nameRow = row([el('label', { 'for': uid + '-name', text: T.name }), name]);
var anonRow = row([el('label', { 'class': 'sg-inline', 'for': uid + '-anon' }, [anon, document.createTextNode(T.anonymous)])]);
if (C.policy === 'force_anonymous') { anon.checked = true; anon.disabled = true; nameRow.hidden = true; }
else if (C.policy === 'require_name') { anonRow.hidden = true; name.required = true; }
root.appendChild(nameRow);
root.appendChild(anonRow);
root.appendChild(row([el('label', { 'for': uid + '-msg', text: T.message }), msg]));
var tip = el('div', { 'class': 'sg-tip', id: uid + '-tip', role: 'note', text: T.coverInfo || '' });
tip.hidden = true;
var info = el('button', { type: 'button', 'class': 'sg-info', 'aria-label': T.coverInfoLabel || 'What does this mean?', 'aria-expanded': 'false', 'aria-controls': uid + '-tip', text: 'i' });
var pinnedOpen = false;
function showTip(open) { tip.hidden = !open; info.setAttribute('aria-expanded', String(open)); }
// Click toggles a "pinned" state independent of hover (a tap fires hover first, so reading tip.hidden would undo itself).
info.addEventListener('click', function () { pinnedOpen = !pinnedOpen; showTip(pinnedOpen); });
info.addEventListener('mouseenter', function () { showTip(true); });
info.addEventListener('mouseleave', function () { if (!pinnedOpen) { showTip(false); } });
info.addEventListener('blur', function () { pinnedOpen = false; showTip(false); });
info.addEventListener('keydown', function (e) { if (e.key === 'Escape') { pinnedOpen = false; showTip(false); } });
root.appendChild(row([
el('div', { 'class': 'sg-cover' }, [el('label', { 'class': 'sg-inline', 'for': uid + '-cover' }, [cover, document.createTextNode(T.coverFees)]), info]),
tip
]));
root.appendChild(row([total]));
root.appendChild(status); // messages sit above the PayPal buttons, next to the form fields
root.appendChild(buttons);
if (C.notice) { root.appendChild(el('p', { 'class': 'sg-notice', text: String(C.notice) })); } // e.g. "Donations are non-refundable." right where the donor pays
function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); }
function amountStr() { return amount.value.trim().replace(',', '.'); }
function anonNow() { return anon.checked; }
anon.addEventListener('change', function () { nameRow.hidden = anon.checked || C.policy === 'force_anonymous'; });
// Actions (rewards) for the selected goal, minus any below the minimum. They replace the generic presets.
function goalActions() {
return (state.goal.actions || []).filter(function (a) {
return a && a.amount_minor > 0 && a.amount_minor >= (C.minMinor || 0);
});
}
function minorToStr(minor, exp) { return (minor / Math.pow(10, exp)).toFixed(exp); }
function amountMinorNow() {
var typed = parseFloat(amountStr());
return isFinite(typed) ? Math.round(typed * Math.pow(10, state.goal.exp)) : -1;
}
function buildPresets() {
presetBox.textContent = '';
hint.textContent = sprintf1(T.minHint, fmt(C.minMinor || 0, state.goal.exp, state.goal.currency));
var acts = goalActions();
presetBox.className = 'sg-presets' + (acts.length ? ' sg-actions' : '');
if (acts.length) {
acts.forEach(function (a) {
var money = fmt(a.amount_minor, state.goal.exp, state.goal.currency);
var lead = a.mode === 'every' ? sprintf1(T.everyLabel || 'Every %s', money) : money;
var kids = [el('span', { 'class': 'sg-act-title', text: lead + ': ' + a.title })];
if (a.description) { kids.push(el('span', { 'class': 'sg-act-desc', text: a.description })); }
var b = el('button', { type: 'button', 'class': 'sg-action', 'aria-pressed': 'false' }, kids);
b.addEventListener('click', function () { amount.value = minorToStr(a.amount_minor, state.goal.exp); refresh(); });
presetBox.appendChild(b);
});
return;
}
presets(state.goal.exp).forEach(function (p) {
var b = el('button', { type: 'button', 'aria-pressed': 'false', text: fmt(state.goal.exp === 0 ? p : p * 100, state.goal.exp, state.goal.currency) });
b.addEventListener('click', function () { amount.value = String(p); refresh(); });
presetBox.appendChild(b);
});
}
function markPresets() {
var acts = goalActions();
if (acts.length) {
var now = amountMinorNow();
Array.prototype.forEach.call(presetBox.children, function (b, i) {
b.setAttribute('aria-pressed', String(!!acts[i] && acts[i].amount_minor === now));
});
return;
}
var cur = amountStr();
Array.prototype.forEach.call(presetBox.children, function (b, i) {
b.setAttribute('aria-pressed', String(String(presets(state.goal.exp)[i]) === cur));
});
}
// Server-authoritative total preview (debounced). The server recomputes it again when the order is created.
var timer = null, seq = 0;
function refresh() {
markPresets();
state.quote = null;
buttons.setAttribute('data-disabled', 'true');
clearTimeout(timer);
if (!amountStr()) { total.textContent = ''; say(''); return; }
var typed = parseFloat(amountStr());
if (isFinite(typed) && Math.round(typed * Math.pow(10, state.goal.exp)) < (C.minMinor || 0)) {
total.textContent = ''; say(sprintf1(T.belowMin, fmt(C.minMinor, state.goal.exp, state.goal.currency)), 'sg-error'); return;
}
var mine = ++seq;
timer = setTimeout(function () {
var qs = 'goal_id=' + state.goal.id + '&amount=' + encodeURIComponent(amountStr()) + '&cover_fees=' + (cover.checked ? '1' : '0');
api('/fee-preview?' + qs).then(function (q) {
if (mine !== seq) { return; }
state.quote = q;
var t = T.total + ': ' + fmt(q.total_minor, state.goal.exp, q.currency);
if (q.fee_minor > 0) { t += ' (' + fmt(q.fee_minor, state.goal.exp, q.currency) + ')'; }
total.textContent = t; say('');
buttons.removeAttribute('data-disabled');
}, function (e) { if (mine === seq) { total.textContent = ''; say(e.message, 'sg-error'); } });
}, 250);
}
[amount, cover].forEach(function (n) { n.addEventListener(n === cover ? 'change' : 'input', refresh); });
function payload() {
return {
goal_id: state.goal.id, amount: amountStr(), display_name: name.value, anonymous: anonNow(),
message: msg.value, cover_fees: cover.checked
};
}
function renderButtons() {
var token = ++state.renderToken;
buttons.textContent = '';
loadSdk(state.goal.currency).then(function (paypal) {
if (token !== state.renderToken) { return; }
paypal.Buttons({
onClick: function (d, actions) {
if (!state.quote || (C.policy === 'require_name' && !name.value.trim())) { if (!status.textContent) { say(T.fixForm, 'sg-error'); } return actions.reject(); }
say('');
},
createOrder: function () {
return api('/orders', { method: 'POST', body: payload() }).then(function (r) { return r.order_id; });
},
onApprove: function (data) {
return api('/orders/' + encodeURIComponent(data.orderID) + '/capture', { method: 'POST' }).then(function (r) {
say(r.status === 'completed' ? T.thanks : T.processing, 'sg-ok');
});
},
onError: function (err) { say((err && err.message) || T.error, 'sg-error'); }
}).render(buttons);
}, function (e) { say(e.message, 'sg-error'); });
}
goalSel.addEventListener('change', function () {
state.goal = goals.filter(function (g) { return String(g.id) === goalSel.value; })[0] || goals[0];
showNext(); buildPresets(); refresh(); renderButtons();
});
showNext(); buildPresets(); refresh(); renderButtons();
}
function boot() { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate'), init); }
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); }
})();