import { t } from '../i18n/index.js'; import { formatDateTime } from '../i18n/format.js'; import { authService } from '../state.js'; import { getSolanaCluster } from '../services/solana-rpc-gateway.js'; import { formatStarAmount, formatStars } from '../services/shine-support-amount.js'; import { iconHtml } from './ui-icon.js'; import { playSupportShine, prefersReducedMotion } from './support-shine-effects.js'; const GOO_FILTER_ID = 'profile-support-goo'; // Порядок совпадает с supportStatsValues(). tone — класс цвета метрики (CSS задаёт --ps-tone); // подписи берутся при отрисовке: словари грузятся асинхронно и язык можно сменить. const METRICS = [ { tone: 'is-sent', icon: 'heart', key: 'sent' }, { tone: 'is-received', icon: 'trend-up', key: 'received' }, { tone: 'is-shine', icon: 'sparkle', key: 'shine' }, ]; let panelSeq = 0; export function supportStatsValues(stats = {}) { const sent = BigInt(stats.supportSent ?? 0); const received = BigInt(stats.supportReceived ?? 0); const daoDirect = BigInt(stats.daoDirect ?? 0); return [sent, received, daoDirect]; } // Фильтр «жидкого света» один на документ (тот же приём, что fg-shine-glow у прежних «Связей»): // размытие + порог альфы сливают капли света в одну вязкую форму. Применяется только к слою // света под текстом кнопки — на всю кнопку его вешать нельзя, порог «съест» тонкие буквы. function ensureGooFilter() { if (typeof document === 'undefined' || document.getElementById(GOO_FILTER_ID)) return; const holder = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); holder.setAttribute('width', '0'); holder.setAttribute('height', '0'); holder.setAttribute('aria-hidden', 'true'); holder.setAttribute('focusable', 'false'); holder.style.position = 'absolute'; holder.innerHTML = `` + '' + '' + '' + ''; document.body.append(holder); } // Видимо — только число и SVG-звезда; скринридер получает прежнюю полную запись «0.10 ⭐». // data-cents — точная сумма для счёта от нуля (support-shine-effects.js). function renderAmount(cents, sign = '') { const wrap = document.createElement('span'); wrap.className = 'profile-support-amount'; const value = document.createElement('span'); value.className = 'profile-support-amount__value'; value.setAttribute('aria-hidden', 'true'); value.dataset.cents = String(cents); value.textContent = formatStarAmount(cents) ? `${sign}${formatStarAmount(cents)}` : ''; const spoken = document.createElement('span'); spoken.className = 'sr-only'; spoken.textContent = formatStarAmount(cents) ? `${sign}${formatStars(cents)}` : '⭐'; wrap.append(value); wrap.insertAdjacentHTML('beforeend', iconHtml('star', true, 'profile-support-amount__star')); wrap.append(spoken); return wrap; } function renderChip({ tone, icon }, cents) { const chip = document.createElement('span'); chip.className = cents === 0n ? `profile-support-chip ${tone} is-zero` : `profile-support-chip ${tone}`; chip.innerHTML = iconHtml(icon, false, 'profile-support-chip__icon'); const value = document.createElement('span'); value.textContent = formatStarAmount(cents); chip.append(value); chip.insertAdjacentHTML('beforeend', iconHtml('star', true, 'profile-support-chip__star')); return chip; } // Капля света из точки касания + две капельки-спутника: фильтр сливает их в жидкую вспышку. // Удаляется по окончании своей анимации — без таймеров, переживающих страницу. function spawnLiquidLight(layer, event) { if (prefersReducedMotion()) return; const rect = layer.getBoundingClientRect(); const group = document.createElement('span'); group.className = 'profile-support-goo'; group.style.left = `${event.clientX - rect.left}px`; group.style.top = `${event.clientY - rect.top}px`; const main = document.createElement('span'); main.className = 'profile-support-goo__drop is-main'; const left = document.createElement('span'); left.className = 'profile-support-goo__drop is-left'; const right = document.createElement('span'); right.className = 'profile-support-goo__drop is-right'; group.append(main, left, right); // animationcancel — на случай прерванной анимации (элемент скрыли/сменили), иначе капли остались бы в DOM. const removeGroup = () => group.remove(); main.addEventListener('animationend', removeGroup, { once: true }); main.addEventListener('animationcancel', removeGroup, { once: true }); layer.append(group); } /** * Adds an independent asynchronous block: a thin totals line that expands into the support card. * Failure/Free accounts do not get fictitious statistics. */ export function attachSupportStats(parent, { login, isActive = () => true }) { ensureGooFilter(); const panelId = `profile-support-panel-${panelSeq += 1}`; const section = document.createElement('section'); section.className = 'profile-support'; section.dataset.expanded = 'false'; // Свёрнутый блок-строка: ♡ сумма · ↗ сумма · ✦ сумма ⌄. Пока данных нет — неактивен и показывает статус. const line = document.createElement('div'); line.className = 'profile-support__line'; const summary = document.createElement('button'); summary.type = 'button'; summary.className = 'profile-support__summary'; summary.disabled = true; summary.setAttribute('aria-expanded', 'false'); summary.setAttribute('aria-controls', panelId); summary.textContent = t('screens.support_phase2.loading'); line.append(summary); // Раскрываемая карточка. inert, пока свёрнута: её кнопки не ловят фокус и не читаются скринридером. const panel = document.createElement('div'); panel.className = 'profile-support__panel'; panel.id = panelId; panel.inert = true; const card = document.createElement('div'); card.className = 'profile-support-stats'; const title = document.createElement('button'); title.type = 'button'; title.className = 'profile-support-stats__title'; title.setAttribute('aria-expanded', 'true'); title.setAttribute('aria-controls', panelId); const titleLabel = document.createElement('span'); titleLabel.textContent = t('screens.support_phase2.statistics'); title.append(titleLabel); title.insertAdjacentHTML('beforeend', iconHtml('chevron-up', false, 'profile-support-stats__title-chevron')); const content = document.createElement('div'); content.className = 'profile-support-stats__content'; card.append(title, content); const history = document.createElement('details'); history.className = 'profile-support-history'; const historySummary = document.createElement('summary'); historySummary.className = 'profile-support-history__toggle'; const light = document.createElement('span'); light.className = 'profile-support-history__light'; light.setAttribute('aria-hidden', 'true'); const historyLabel = document.createElement('span'); historyLabel.className = 'profile-support-history__label'; historyLabel.textContent = t('screens.support_phase2.history'); historySummary.append(light, historyLabel); historySummary.insertAdjacentHTML('beforeend', iconHtml('chevron', false, 'profile-support-history__chevron')); // is-pressed дублирует :active: iOS Safari не включает :active без обработчика касаний. const setPressed = (pressed) => historySummary.classList.toggle('is-pressed', pressed); historySummary.addEventListener('pointerdown', (event) => { if (event.button > 0) return; setPressed(true); spawnLiquidLight(light, event); }); for (const type of ['pointerup', 'pointercancel', 'pointerleave']) { historySummary.addEventListener(type, () => setPressed(false)); } const historyRows = document.createElement('div'); historyRows.className = 'profile-support-history__rows'; history.append(historySummary, historyRows); card.append(history); panel.append(card); section.append(line, panel); parent.append(section); let expanded = false; let toggleSeq = 0; let stopShine = null; const shine = () => { stopShine = playSupportShine(card, { isActive }); }; // Карточка раскрывается вниз: если строка стоит у нижнего края экрана, без подкрутки карточка и её сияние // оказались бы под панелью навигации. Пока идёт «выезд», каждый кадр держим карточку в видимой области. const followReveal = (seq) => { const step = () => { if (seq !== toggleSeq || !expanded || !isActive() || !section.isConnected) return; card.scrollIntoView({ block: 'nearest' }); if (!section.classList.contains('is-settled')) requestAnimationFrame(step); }; requestAnimationFrame(step); }; const setExpanded = (next) => { if (next === expanded || !section.isConnected) return; expanded = next; const seq = toggleSeq += 1; section.dataset.expanded = String(next); section.classList.remove('is-settled'); summary.setAttribute('aria-expanded', String(next)); // Сначала снимаем inert, потом переводим фокус: в inert-поддерево фокус не попадает. line.inert = next; panel.inert = !next; if (!next) { stopShine?.(); stopShine = null; card.classList.remove('is-pressed'); } (next ? title : summary).focus({ preventScroll: true }); if (!next) return; followReveal(seq); // Пока карточка «выезжает», панель обрезает содержимое; орбита и искры выходят за край карточки, // поэтому сияние запускается после окончания перехода. Нет перехода (reduced-motion) — сразу. const transitions = section.getAnimations?.() ?? []; Promise.all(transitions.map((animation) => animation.finished)).then(() => { if (seq !== toggleSeq || !isActive() || !section.isConnected) return; section.classList.add('is-settled'); card.scrollIntoView({ block: 'nearest' }); shine(); }, () => {}); }; summary.addEventListener('click', () => setExpanded(true)); title.addEventListener('click', () => setExpanded(false)); // Тап по карточке (кроме заголовка и истории): вдавливание .97, пружинный возврат и повтор сияния. const isCardSurface = (target) => !target.closest('.profile-support-stats__title, .profile-support-history'); card.addEventListener('pointerdown', (event) => { if (event.button > 0 || !isCardSurface(event.target)) return; card.classList.add('is-pressed'); }); for (const type of ['pointerup', 'pointercancel', 'pointerleave']) { card.addEventListener(type, () => card.classList.remove('is-pressed')); } card.addEventListener('click', (event) => { if (expanded && section.classList.contains('is-settled') && isCardSurface(event.target)) shine(); }); let historyOffset = 0; let loadingHistory = false; let historyLoaded = false; const historyLogin = String(login || '').trim().toLowerCase(); const loadHistory = async () => { if (loadingHistory || !isActive() || !section.isConnected) return; loadingHistory = true; const note = document.createElement('div'); note.className = 'meta-muted'; note.textContent = t('screens.support_phase2.loading'); historyRows.append(note); try { const result = await authService.getSupportHistory(login, 20, historyOffset); if (!isActive() || !section.isConnected) return; note.remove(); if (!result.ready) { historyRows.textContent = t('screens.support_phase2.loading'); return; } if (!historyOffset && !result.transfers?.length) { historyRows.textContent = t('screens.support_phase2.no_history'); } const more = historyRows.querySelector('[data-stars-more]'); more?.remove(); for (const transfer of result.transfers || []) { const outgoing = transfer.senderLogin?.trim().toLowerCase() === historyLogin; const cents = transfer.kind === 'DAO' || outgoing ? transfer.amountStarCents : transfer.recipientStarCents; const row = document.createElement('div'); row.className = 'profile-support-transfer'; const info = document.createElement('span'); info.className = 'profile-support-transfer__peer'; info.textContent = transfer.kind === 'DAO' ? t('screens.support_phase2.history_dao') : `${outgoing ? '→' : '←'} ${outgoing ? transfer.recipientLogin : transfer.senderLogin}`; const value = renderAmount(cents, outgoing ? '−' : '+'); const detail = document.createElement('small'); detail.className = 'profile-support-transfer__detail meta-muted'; const date = transfer.blockTime ? formatDateTime(Number(transfer.blockTime) * 1000) : ''; const lamports = BigInt(transfer.amountLamports || '0'); const sol = `${lamports / 1_000_000_000n}.${String(lamports % 1_000_000_000n).padStart(9, '0').replace(/0+$/, '') || '0'} SOL`; detail.textContent = date ? `${date} · ${sol}` : sol; const explorer = document.createElement('a'); const sig = String(transfer.signature || ''); if (/^[1-9A-HJ-NP-Za-km-z]{64,90}$/.test(sig)) { const network = getSolanaCluster(); explorer.className = 'profile-support-transfer__link'; explorer.href = `https://explorer.solana.com/tx/${sig}${network && network !== 'mainnet-beta' ? `?cluster=${encodeURIComponent(network)}` : ''}`; explorer.target = '_blank'; explorer.rel = 'noopener noreferrer'; explorer.textContent = t('screens.support_phase2.transaction'); row.append(info, value, detail, explorer); } else row.append(info, value, detail); historyRows.append(row); } historyOffset += (result.transfers || []).length; if (result.hasMore) { const btn = document.createElement('button'); btn.className = 'text-btn'; btn.type = 'button'; btn.dataset.starsMore = '1'; btn.textContent = t('screens.support_phase2.more'); btn.addEventListener('click', () => void loadHistory()); historyRows.append(btn); } historyLoaded = true; } catch { if (isActive() && section.isConnected) note.textContent = t('screens.support_phase2.history_unavailable'); } finally { loadingHistory = false; } }; history.addEventListener('toggle', () => { if (!history.open) return; // Записи истории тоже появляются ниже — подтягиваем их в видимую область, когда они на месте. const reveal = () => { if (!history.open || !isActive() || !section.isConnected) return; history.scrollIntoView({ block: 'nearest', behavior: prefersReducedMotion() ? 'auto' : 'smooth' }); }; if (historyLoaded) reveal(); else void loadHistory().then(reveal); }); let pendingRefresh = null; const scheduleRetry = () => { if (pendingRefresh !== null) return; pendingRefresh = window.setTimeout(() => { pendingRefresh = null; if (isActive() && section.isConnected) void refresh(); }, 10_000); }; const showLineStatus = (text) => { setExpanded(false); summary.disabled = true; summary.removeAttribute('aria-label'); summary.textContent = text; }; const refresh = async () => { try { const stats = await authService.getSupportStats(login); if (!isActive() || !section.isConnected) return; if (!stats.ready) { // Первичная индексация ещё идёт. Повторим запрос к кешу без RPC Solana. showLineStatus(t('screens.support_phase2.loading')); scheduleRetry(); return; } if (!stats.available) { // Free-аккаунты не имеют Paid PDA, поэтому блок статистики не показываем. section.remove(); return; } const values = supportStatsValues({ supportSent: stats.supportSentStarCents, supportReceived: stats.supportReceivedStarCents, daoDirect: stats.daoDirectStarCents, }); stopShine?.(); stopShine = null; summary.replaceChildren(); METRICS.forEach((metric, idx) => { if (idx) { const sep = document.createElement('span'); sep.className = 'profile-support__sep'; sep.textContent = '·'; summary.append(sep); } summary.append(renderChip(metric, values[idx])); }); summary.insertAdjacentHTML('beforeend', iconHtml('chevron-down', false, 'profile-support__chevron')); // Видимые чипы — числа и значки; скринридер получает всю сводку целиком. summary.setAttribute('aria-label', t('screens.support_phase2.summary', { sent: formatStars(values[0]), received: formatStars(values[1]), shine: formatStars(values[2]), })); summary.disabled = false; content.replaceChildren(); METRICS.forEach((metric, idx) => { const row = document.createElement('div'); // Нулевые суммы приглушены и не «дышат»: свечение — только там, где поддержка есть. row.className = values[idx] === 0n ? `profile-support-stat ${metric.tone} is-zero` : `profile-support-stat ${metric.tone}`; const iconSlot = document.createElement('span'); iconSlot.className = 'profile-support-stat__icon'; iconSlot.innerHTML = iconHtml(metric.icon); const name = document.createElement('span'); name.className = 'profile-support-stat__label'; name.textContent = t(`screens.support_phase2.${metric.key}`); row.append(iconSlot, name, renderAmount(values[idx])); content.append(row); }); } catch { if (!isActive() || !section.isConnected) return; // A missing Paid PDA means Free, but network errors must not be displayed as zero. showLineStatus(t('screens.support_phase2.unavailable')); } }; void refresh(); return { element: section, refresh }; }