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; }