Карточка «Поддержка» в профиле: блок-строка, раскрытие и эффекты

- Под «Сменить профиль» блок-строка с суммами ♡ · ↗ · ✦ в цветах метрик,
  тап раскрывает стеклянную карточку с суммами и историей переводов.
- Раскрытие с подкруткой в видимую область, сияние: кометы «пополнения»,
  блик по рамке со вспышкой, орбита; reduced-motion — статичный вид.
- Стили вынесены в styles/features/profile-support.css, эффекты —
  в js/components/support-shine-effects.js.
- formatStarAmount() — число без символа звезды для вёрстки с SVG-иконкой.
- Ключ screens.support_phase2.summary (ru/en), подписи без emoji.
- DESIGN.md §11.3 и WALLET_SHINE_SUPPORT.md обновлены.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pixel
2026-11-29 18:14:59 +03:00
co-authored by Claude Opus 5.5
parent d3a84dd451
commit 55f2d11721
11 changed files with 939 additions and 41 deletions
+260 -31
View File
@@ -1,7 +1,20 @@
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 { formatStars } from '../services/shine-support-amount.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);
@@ -10,27 +23,211 @@ export function supportStatsValues(stats = {}) {
return [sent, received, daoDirect];
}
/** Adds an independent asynchronous block; failure/Free accounts do not get fictitious statistics. */
// Фильтр «жидкого света» один на документ (тот же приём, что 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 = `<defs><filter id="${GOO_FILTER_ID}" x="-20%" y="-60%" width="140%" height="220%" color-interpolation-filters="sRGB">`
+ '<feGaussianBlur in="SourceGraphic" stdDeviation="5" result="blur"/>'
+ '<feColorMatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 18 -7" result="goo"/>'
+ '<feComposite in="SourceGraphic" in2="goo" operator="atop"/>'
+ '</filter></defs>';
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 = `${sign}${formatStarAmount(cents)}`;
const spoken = document.createElement('span');
spoken.className = 'sr-only';
spoken.textContent = `${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 = 'card stack profile-support-stats';
section.style.cssText = 'margin-top:12px;gap:8px;';
const title = document.createElement('strong');
title.textContent = t('screens.support_phase2.statistics');
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 = 'meta-muted';
content.textContent = t('screens.support_phase2.loading');
section.append(title, content);
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.textContent = t('screens.support_phase2.history');
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 = 'stack';
historyRows.style.cssText = 'gap:8px;margin-top:10px;';
historyRows.className = 'profile-support-history__rows';
history.append(historySummary, historyRows);
section.append(history);
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;
@@ -60,24 +257,24 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
const cents = transfer.kind === 'DAO' || outgoing
? transfer.amountStarCents : transfer.recipientStarCents;
const row = document.createElement('div');
row.className = 'row';
row.style.cssText = 'display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px;';
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 = document.createElement('strong');
value.textContent = `${outgoing ? '−' : '+'}${formatStars(cents)}`;
const value = renderAmount(cents, outgoing ? '−' : '+');
const detail = document.createElement('small');
detail.className = 'meta-muted';
const date = transfer.blockTime ? new Date(Number(transfer.blockTime) * 1000).toLocaleString() : '';
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} · ${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');
@@ -100,7 +297,14 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
} finally { loadingHistory = false; }
};
history.addEventListener('toggle', () => {
if (history.open && !historyLoaded) void loadHistory();
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 = () => {
@@ -110,13 +314,19 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
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.
content.textContent = t('screens.support_phase2.loading');
showLineStatus(t('screens.support_phase2.loading'));
scheduleRetry();
return;
}
@@ -130,23 +340,42 @@ export function attachSupportStats(parent, { login, isActive = () => true }) {
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();
content.className = 'stack';
[t('screens.support_phase2.sent'), t('screens.support_phase2.received'), t('screens.support_phase2.shine')].forEach((label, idx) => {
METRICS.forEach((metric, idx) => {
const row = document.createElement('div');
row.className = 'row';
row.style.cssText = 'display:flex;justify-content:space-between;gap:8px;';
// Нулевые суммы приглушены и не «дышат»: свечение — только там, где поддержка есть.
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');
const amount = document.createElement('strong');
name.textContent = label;
amount.textContent = formatStars(values[idx]);
row.append(name, amount);
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.
content.textContent = t('screens.support_phase2.unavailable');
showLineStatus(t('screens.support_phase2.unavailable'));
}
};
void refresh();