SHA256
Карточка «Поддержка» в профиле: блок-строка, раскрытие и эффекты
- Под «Сменить профиль» блок-строка с суммами ♡ · ↗ · ✦ в цветах метрик, тап раскрывает стеклянную карточку с суммами и историей переводов. - Раскрытие с подкруткой в видимую область, сияние: кометы «пополнения», блик по рамке со вспышкой, орбита; 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:
@@ -0,0 +1,335 @@
|
||||
import { formatStarAmount } from '../services/shine-support-amount.js';
|
||||
|
||||
// Одноразовое «сияние» карточки «Поддержка» (после раскрытия и при тапе по ней):
|
||||
// — «пополнение»: в каждой ненулевой строке комета цвета метрики летит дугой от иконки к сумме, оставляя
|
||||
// светящийся хвост и пылинки; при попадании сумма вспыхивает искрами и досчитывается от нуля;
|
||||
// — золотой блик обходит рамку по контуру и гаснет вспышкой-звёздочкой в правом верхнем углу;
|
||||
// — пунктирная орбита с золотыми точками вокруг карточки.
|
||||
// Всё декоративное (aria-hidden), каждый слой удаляет себя по окончании своей анимации, а единый цикл rAF
|
||||
// останавливается, как только страница закрыта, — таймеров, переживающих страницу, нет.
|
||||
|
||||
const COMET_START_MS = 150;
|
||||
const COMET_STAGGER_MS = 260;
|
||||
const COMET_FLIGHT_MS = 650;
|
||||
// Доля пути, которую занимает хвост кометы; после попадания хвост «втягивается» в сумму.
|
||||
const COMET_TRAIL = 0.5;
|
||||
const MOTE_EVERY_MS = 30;
|
||||
const COUNT_MS = 700;
|
||||
const ORBIT_MS = 2400;
|
||||
const ORBIT_GAP = 6;
|
||||
// Поле SVG орбиты вокруг карточки: эффекты не выходят за край дальше 10px (иначе на 320px появится горизонтальная прокрутка).
|
||||
const ORBIT_PAD = 10;
|
||||
const ORBIT_DOTS = 7;
|
||||
const SPARKS = 8;
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
const runs = new WeakMap();
|
||||
let fxSeq = 0;
|
||||
|
||||
export function prefersReducedMotion() {
|
||||
return Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches);
|
||||
}
|
||||
|
||||
const easeOutCubic = (p) => 1 - (1 - p) ** 3;
|
||||
const easeInOutCubic = (p) => (p < 0.5 ? 4 * p ** 3 : 1 - (-2 * p + 2) ** 3 / 2);
|
||||
|
||||
function removeAfterOwnAnimation(el) {
|
||||
// animationend всплывает от дочерних слоёв — удаляем только по окончании анимации самого элемента.
|
||||
const done = (event) => { if (event.target === el) el.remove(); };
|
||||
el.addEventListener('animationend', done);
|
||||
el.addEventListener('animationcancel', done);
|
||||
}
|
||||
|
||||
// offsetLeft/offsetTop не зависят от transform: замеры верны, даже когда карточка вдавлена (scale .97).
|
||||
function offsetWithin(el, ancestor) {
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
for (let node = el; node && node !== ancestor; node = node.offsetParent) {
|
||||
x += node.offsetLeft;
|
||||
y += node.offsetTop;
|
||||
}
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
function svgEl(name, attrs = {}) {
|
||||
const el = document.createElementNS(SVG_NS, name);
|
||||
for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, String(value));
|
||||
return el;
|
||||
}
|
||||
|
||||
function overlaySvg(card, className, width = card.offsetWidth, height = card.offsetHeight) {
|
||||
const svg = svgEl('svg', { width, height, viewBox: `0 0 ${width} ${height}`, 'aria-hidden': 'true', focusable: 'false' });
|
||||
svg.setAttribute('class', `profile-support-fx ${className}`);
|
||||
const defs = svgEl('defs');
|
||||
svg.append(defs);
|
||||
return { svg, defs, width, height };
|
||||
}
|
||||
|
||||
// Свечение — SVG-фильтр, а не CSS filter: на вложенных элементах SVG CSS-фильтры поддерживаются не везде.
|
||||
// Область фильтра задана в координатах холста: у тонкой линии рамка объекта почти нулевой высоты.
|
||||
// layers — сколько раз наложить ореол: два слоя дают яркий «неоновый» росчерк.
|
||||
function glowFilter(defs, width, height, deviation, layers = 1) {
|
||||
const id = `profile-support-glow-${fxSeq += 1}`;
|
||||
const filter = svgEl('filter', { id, filterUnits: 'userSpaceOnUse', x: 0, y: 0, width, height });
|
||||
filter.append(svgEl('feGaussianBlur', { in: 'SourceGraphic', stdDeviation: deviation, result: 'blur' }));
|
||||
const merge = svgEl('feMerge');
|
||||
for (let i = 0; i < layers; i += 1) merge.append(svgEl('feMergeNode', { in: 'blur' }));
|
||||
merge.append(svgEl('feMergeNode', { in: 'SourceGraphic' }));
|
||||
filter.append(merge);
|
||||
defs.append(filter);
|
||||
return `url(#${id})`;
|
||||
}
|
||||
|
||||
// Скруглённый прямоугольник по часовой стрелке от правого верхнего угла: блик, пройдя круг, гаснет в этом углу.
|
||||
function roundedRectPath(x, y, w, h, r) {
|
||||
const rr = Math.max(0, Math.min(r, w / 2, h / 2));
|
||||
return `M ${x + w - rr} ${y} A ${rr} ${rr} 0 0 1 ${x + w} ${y + rr} V ${y + h - rr}`
|
||||
+ ` A ${rr} ${rr} 0 0 1 ${x + w - rr} ${y + h} H ${x + rr} A ${rr} ${rr} 0 0 1 ${x} ${y + h - rr}`
|
||||
+ ` V ${y + rr} A ${rr} ${rr} 0 0 1 ${x + rr} ${y} Z`;
|
||||
}
|
||||
|
||||
// Четырёхлучевая звёздочка-вспышка с вогнутыми гранями.
|
||||
function sparklePath(cx, cy, s) {
|
||||
return `M ${cx} ${cy - s} Q ${cx} ${cy} ${cx + s} ${cy} Q ${cx} ${cy} ${cx} ${cy + s}`
|
||||
+ ` Q ${cx} ${cy} ${cx - s} ${cy} Q ${cx} ${cy} ${cx} ${cy - s} Z`;
|
||||
}
|
||||
|
||||
function cardRadius(card) {
|
||||
return parseFloat(getComputedStyle(card).borderTopLeftRadius) || 20;
|
||||
}
|
||||
|
||||
function rimGlint(card) {
|
||||
const { svg, defs, width, height } = overlaySvg(card, 'profile-support-fx__rim');
|
||||
const glow = glowFilter(defs, width, height, 2);
|
||||
const r = cardRadius(card);
|
||||
// Линия ложится ровно на грань: середина штриха — в 0.75px от края.
|
||||
const d = roundedRectPath(0.75, 0.75, width - 1.5, height - 1.5, r - 0.75);
|
||||
const tint = svgEl('path', { d });
|
||||
tint.setAttribute('class', 'profile-support-fx__rim-tint');
|
||||
const glint = svgEl('path', { d, pathLength: 1, filter: glow });
|
||||
glint.setAttribute('class', 'profile-support-fx__rim-glint');
|
||||
// Середина дуги правого верхнего угла: r·(1 − cos 45°) от каждого края. Вспышке — своё, более яркое свечение.
|
||||
const corner = r * 0.29;
|
||||
const flare = svgEl('path', { d: sparklePath(width - corner, corner, 11), filter: glowFilter(defs, width, height, 2.5, 2) });
|
||||
flare.setAttribute('class', 'profile-support-fx__flare');
|
||||
svg.append(tint, glint, flare);
|
||||
removeAfterOwnAnimation(svg);
|
||||
card.append(svg);
|
||||
}
|
||||
|
||||
function orbit(card) {
|
||||
const { svg, width, height } = overlaySvg(card, 'profile-support-fx__orbit', card.offsetWidth + ORBIT_PAD * 2, card.offsetHeight + ORBIT_PAD * 2);
|
||||
svg.style.left = `${-ORBIT_PAD}px`;
|
||||
svg.style.top = `${-ORBIT_PAD}px`;
|
||||
const inset = ORBIT_PAD - ORBIT_GAP;
|
||||
const ring = svgEl('path', { d: roundedRectPath(inset, inset, width - inset * 2, height - inset * 2, cardRadius(card) + ORBIT_GAP) });
|
||||
ring.setAttribute('class', 'profile-support-fx__ring');
|
||||
svg.append(ring);
|
||||
const dots = [];
|
||||
for (let i = 0; i < ORBIT_DOTS; i += 1) {
|
||||
const el = svgEl('circle', { r: (1.2 + (i % 3) * 0.5).toFixed(1), opacity: 0 });
|
||||
el.setAttribute('class', 'profile-support-fx__dot');
|
||||
svg.append(el);
|
||||
dots.push({ el, start: (i + Math.random() * 0.6) / ORBIT_DOTS, travel: 0.2 + Math.random() * 0.12, peak: 0.55 + Math.random() * 0.45 });
|
||||
}
|
||||
removeAfterOwnAnimation(svg);
|
||||
card.append(svg);
|
||||
// Длина пути доступна только у вставленного в документ SVG.
|
||||
return { svg, ring, dots, length: ring.getTotalLength() };
|
||||
}
|
||||
|
||||
function moveOrbitDots(fx, elapsed) {
|
||||
const p = Math.min(1, elapsed / ORBIT_MS);
|
||||
const envelope = Math.sin(Math.PI * p);
|
||||
for (const dot of fx.dots) {
|
||||
const point = fx.ring.getPointAtLength(((dot.start + dot.travel * easeOutCubic(p)) % 1) * fx.length);
|
||||
dot.el.setAttribute('cx', point.x.toFixed(1));
|
||||
dot.el.setAttribute('cy', point.y.toFixed(1));
|
||||
dot.el.setAttribute('opacity', (envelope * dot.peak).toFixed(2));
|
||||
}
|
||||
return p < 1;
|
||||
}
|
||||
|
||||
function sparkBurst(amount) {
|
||||
const burst = document.createElement('span');
|
||||
burst.className = 'profile-support-sparks';
|
||||
burst.setAttribute('aria-hidden', 'true');
|
||||
for (let i = 0; i < SPARKS; i += 1) {
|
||||
const spark = document.createElement('span');
|
||||
spark.className = 'profile-support-spark';
|
||||
spark.style.setProperty('--a', `${Math.round(i * (360 / SPARKS) + Math.random() * 24 - 12)}deg`);
|
||||
spark.style.setProperty('--d', `${14 + Math.round(Math.random() * 8)}px`);
|
||||
burst.append(spark);
|
||||
}
|
||||
// Все искры одной длительности — достаточно дождаться первой.
|
||||
const removeBurst = () => burst.remove();
|
||||
burst.firstChild.addEventListener('animationend', removeBurst, { once: true });
|
||||
burst.firstChild.addEventListener('animationcancel', removeBurst, { once: true });
|
||||
amount.append(burst);
|
||||
}
|
||||
|
||||
function spawnMote(card, point, tone) {
|
||||
const mote = document.createElement('span');
|
||||
mote.className = 'profile-support-fx profile-support-fx__mote';
|
||||
mote.setAttribute('aria-hidden', 'true');
|
||||
mote.style.left = `${(point.x + Math.random() * 8 - 4).toFixed(1)}px`;
|
||||
mote.style.top = `${(point.y + Math.random() * 8 - 4).toFixed(1)}px`;
|
||||
mote.style.setProperty('--ps-tone', tone);
|
||||
mote.style.setProperty('--mx', `${Math.round(Math.random() * 10 - 5)}px`);
|
||||
mote.style.setProperty('--my', `${Math.round(Math.random() * 10 - 8)}px`);
|
||||
removeAfterOwnAnimation(mote);
|
||||
card.append(mote);
|
||||
}
|
||||
|
||||
// Хвост — штрих длиной COMET_TRAIL на пути длины 1, голова — светящаяся точка в HTML (у неё мягкая box-shadow).
|
||||
// Градиент вдоль полёта гасит хвост к началу, поэтому свет «стекает» к сумме.
|
||||
function prepareComets(card, counters) {
|
||||
const { svg, defs, width, height } = overlaySvg(card, 'profile-support-fx__comets');
|
||||
const glow = glowFilter(defs, width, height, 2.4, 2);
|
||||
const comets = [];
|
||||
for (const counter of counters) {
|
||||
if (counter.cents === 0n) continue;
|
||||
const icon = counter.row.querySelector('.profile-support-stat__icon');
|
||||
if (!icon) continue;
|
||||
const a = offsetWithin(icon, card);
|
||||
const b = offsetWithin(counter.amount, card);
|
||||
const x0 = a.x + icon.offsetWidth + 4;
|
||||
const y0 = a.y + icon.offsetHeight / 2;
|
||||
const x1 = b.x - 4;
|
||||
const y1 = b.y + counter.amount.offsetHeight / 2;
|
||||
const dx = x1 - x0;
|
||||
const tone = getComputedStyle(icon).color;
|
||||
const id = `profile-support-comet-${fxSeq += 1}`;
|
||||
const gradient = svgEl('linearGradient', { id, gradientUnits: 'userSpaceOnUse', x1: x0, y1: y0, x2: x1, y2: y1 });
|
||||
[[0, 0], [0.4, 0.55], [1, 1]].forEach(([offset, opacity]) => {
|
||||
const stop = svgEl('stop', { offset });
|
||||
stop.style.stopColor = tone;
|
||||
stop.style.stopOpacity = String(opacity);
|
||||
gradient.append(stop);
|
||||
});
|
||||
defs.append(gradient);
|
||||
// Дуга ныряет под строку и поднимается в сумму — как росчерк на референсе.
|
||||
const trail = svgEl('path', {
|
||||
d: `M ${x0} ${y0} C ${x0 + dx * 0.35} ${y0 + 24}, ${x1 - dx * 0.3} ${y1 + 20}, ${x1} ${y1}`,
|
||||
pathLength: 1,
|
||||
stroke: `url(#${id})`,
|
||||
filter: glow,
|
||||
});
|
||||
trail.setAttribute('class', 'profile-support-fx__trail');
|
||||
trail.style.strokeDasharray = `${COMET_TRAIL} 3`;
|
||||
trail.style.strokeDashoffset = String(COMET_TRAIL);
|
||||
svg.append(trail);
|
||||
const head = document.createElement('span');
|
||||
head.className = 'profile-support-fx profile-support-fx__comet';
|
||||
head.setAttribute('aria-hidden', 'true');
|
||||
head.style.setProperty('--ps-tone', tone);
|
||||
head.style.opacity = '0';
|
||||
card.append(head);
|
||||
comets.push({ counter, trail, head, tone, start: COMET_START_MS + comets.length * COMET_STAGGER_MS, length: 0, lastMote: -Infinity, done: false });
|
||||
}
|
||||
// Срок жизни слоя задаёт его CSS-анимация (дольше полёта последней кометы).
|
||||
removeAfterOwnAnimation(svg);
|
||||
card.append(svg);
|
||||
for (const comet of comets) comet.length = comet.trail.getTotalLength();
|
||||
return { svg, comets };
|
||||
}
|
||||
|
||||
function moveComet(card, comet, elapsed, startCount) {
|
||||
const p = (elapsed - comet.start) / COMET_FLIGHT_MS;
|
||||
if (p < 0) return true;
|
||||
const reach = easeInOutCubic(Math.min(1, p)) * (1 + COMET_TRAIL);
|
||||
comet.trail.style.strokeDashoffset = (COMET_TRAIL - reach).toFixed(4);
|
||||
if (reach < 1) {
|
||||
const point = comet.trail.getPointAtLength(reach * comet.length);
|
||||
comet.head.style.opacity = '1';
|
||||
comet.head.style.transform = `translate(${point.x.toFixed(1)}px, ${point.y.toFixed(1)}px)`;
|
||||
if (elapsed - comet.lastMote >= MOTE_EVERY_MS) {
|
||||
comet.lastMote = elapsed;
|
||||
spawnMote(card, comet.trail.getPointAtLength(Math.max(0, reach - 0.06) * comet.length), comet.tone);
|
||||
}
|
||||
} else if (comet.head.isConnected) {
|
||||
// Попадание: голова растворяется в сумме, сумма вспыхивает и начинает досчитываться.
|
||||
comet.head.remove();
|
||||
startCount(comet.counter, elapsed);
|
||||
}
|
||||
if (p >= 1) comet.done = true;
|
||||
return !comet.done;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проигрывает сияние на карточке; повторный вызов прерывает предыдущий. Возвращает stop():
|
||||
* суммы сразу становятся итоговыми, декоративные слои убираются. При reduced-motion ничего не делает.
|
||||
*/
|
||||
export function playSupportShine(card, { isActive = () => true } = {}) {
|
||||
runs.get(card)?.();
|
||||
if (prefersReducedMotion() || !card.isConnected) return () => {};
|
||||
const alive = () => isActive() && card.isConnected;
|
||||
const counters = [...card.querySelectorAll('.profile-support-stat')].map((row) => {
|
||||
const value = row.querySelector('.profile-support-amount__value[data-cents]');
|
||||
return value && { row, value, amount: value.parentElement, cents: BigInt(value.dataset.cents), countFrom: null, done: false };
|
||||
}).filter(Boolean);
|
||||
rimGlint(card);
|
||||
const orbitFx = orbit(card);
|
||||
const { comets } = prepareComets(card, counters);
|
||||
for (const counter of counters) {
|
||||
if (counter.cents === 0n) counter.done = true;
|
||||
else counter.value.textContent = formatStarAmount(0n);
|
||||
}
|
||||
const startCount = (counter, elapsed) => {
|
||||
counter.countFrom = elapsed;
|
||||
counter.amount.classList.add('is-filling');
|
||||
sparkBurst(counter.amount);
|
||||
};
|
||||
// Сумма без кометы (не нашлась иконка строки) досчитывается сразу — иначе зависла бы на нуле.
|
||||
const withComet = new Set(comets.map((comet) => comet.counter));
|
||||
for (const counter of counters) {
|
||||
if (!counter.done && !withComet.has(counter)) startCount(counter, 0);
|
||||
}
|
||||
|
||||
let frame = 0;
|
||||
let finished = false;
|
||||
// Видимое число — aria-hidden; итог всегда восстанавливается точным BigInt, без потерь округления.
|
||||
const finish = () => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
cancelAnimationFrame(frame);
|
||||
for (const counter of counters) {
|
||||
counter.value.textContent = formatStarAmount(counter.cents);
|
||||
counter.amount.classList.remove('is-filling');
|
||||
}
|
||||
if (runs.get(card) === stop) runs.delete(card);
|
||||
};
|
||||
function stop() {
|
||||
finish();
|
||||
card.querySelectorAll('.profile-support-fx, .profile-support-sparks').forEach((el) => el.remove());
|
||||
}
|
||||
const startedAt = performance.now();
|
||||
const tick = (now) => {
|
||||
if (!alive()) { finish(); return; }
|
||||
const elapsed = now - startedAt;
|
||||
let pending = false;
|
||||
for (const comet of comets) {
|
||||
if (!comet.done && moveComet(card, comet, elapsed, startCount)) pending = true;
|
||||
}
|
||||
for (const counter of counters) {
|
||||
if (counter.done) continue;
|
||||
pending = true;
|
||||
if (counter.countFrom === null) continue;
|
||||
const q = Math.min(1, (elapsed - counter.countFrom) / COUNT_MS);
|
||||
if (q < 1) {
|
||||
counter.value.textContent = formatStarAmount(BigInt(Math.round(Number(counter.cents) * easeOutCubic(q))));
|
||||
} else {
|
||||
counter.done = true;
|
||||
counter.value.textContent = formatStarAmount(counter.cents);
|
||||
// Цвет и свечение суммы плавно гаснут (переход в CSS).
|
||||
counter.amount.classList.remove('is-filling');
|
||||
}
|
||||
}
|
||||
if (orbitFx.svg.isConnected && moveOrbitDots(orbitFx, elapsed)) pending = true;
|
||||
if (pending) frame = requestAnimationFrame(tick);
|
||||
else finish();
|
||||
};
|
||||
frame = requestAnimationFrame(tick);
|
||||
runs.set(card, stop);
|
||||
return stop;
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -48,6 +48,8 @@ const paths = {
|
||||
'user-plus': '<circle cx="10" cy="8" r="3.5"/><path d="M3.5 20a6.5 6.5 0 0 1 13 0M19 8v6M16 11h6"/>',
|
||||
refresh: '<path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v4.4h-4.4"/>',
|
||||
sparkle: '<path d="M11 4c.6 4.4 2.6 6.4 7 7-4.4.6-6.4 2.6-7 7-.6-4.4-2.6-6.4-7-7 4.4-.6 6.4-2.6 7-7Z"/><path d="M19 2.5v3M17.5 4h3"/>',
|
||||
'trend-up': '<path d="m3 17 6.5-6.5 4 4L21 7"/><path d="M15 7h6v6"/>',
|
||||
star: '<path d="m12 2.8 2.85 5.78 6.38.93-4.62 4.5 1.09 6.35L12 17.36l-5.7 3 1.09-6.35-4.62-4.5 6.38-.93Z"/>',
|
||||
rings: '<circle cx="12" cy="12" r="2"/><circle cx="12" cy="12" r="5.5"/><circle cx="12" cy="12" r="9"/>',
|
||||
place: '<path d="M12 21s-6.5-5.6-6.5-11a6.5 6.5 0 0 1 13 0c0 5.4-6.5 11-6.5 11Z"/><circle cx="12" cy="10" r="2.4"/>',
|
||||
groups: '<circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0"/><circle cx="17" cy="9.5" r="2.5"/><path d="M15.6 14.1A4.6 4.6 0 0 1 21 18.5"/>',
|
||||
|
||||
Reference in New Issue
Block a user