SHA256
Слить PR #4: голосовые сообщения и карточка поддержки
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { restoreShare, activateShare, allowShareNavigation, restoreSharePath, checkShareOwner, getPendingShare, finishShare, isShareSending } from './services/share-flow.js';
|
||||
import { isDmPreviewHidden } from './services/dm-preview-settings.js';
|
||||
import { dmPreviewTarget, dmPreviewText, fetchDmPreview } from './services/dm-preview.js';
|
||||
import { isVoiceRecordingActive, onVoiceRecordingIdle } from './components/dm-voice-recorder.js';
|
||||
import { initI18n, onLanguageChange, t } from './i18n/index.js';
|
||||
import { preventPagePinchZoom } from './services/pwa-viewport-gestures.js';
|
||||
preventPagePinchZoom();
|
||||
@@ -238,6 +239,9 @@ const CURRENT_BUILD_HASH = String(window.__SHINE_BUILD_HASH__ || '').trim();
|
||||
const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
||||
|
||||
let currentCleanup = null;
|
||||
// Путь смонтированного экрана: повторный рендер того же экрана во время записи голосового откладывается.
|
||||
let mountedPath = '';
|
||||
let renderDeferredByVoice = false;
|
||||
let pingIntervalId = null;
|
||||
let reconnectIntervalId = null;
|
||||
let channelsPrefetchTimerId = null;
|
||||
@@ -1440,6 +1444,14 @@ async function redirectToActiveKeyRotationIfNeeded() {
|
||||
function renderApp() {
|
||||
// Avoid remounting the composer while an encrypted share upload is in progress.
|
||||
if (state.session.isAuthorized && isShareSending()) return;
|
||||
// Перемонтирование того же экрана оборвало бы запись или отправку голосового (например,
|
||||
// обновление после старта сессии при плохой сети). Ждём конца записи; переход на другой
|
||||
// маршрут не откладывается — уход со страницы прерывает запись штатно.
|
||||
if (isVoiceRecordingActive() && window.location.pathname === mountedPath) {
|
||||
renderDeferredByVoice = true;
|
||||
return;
|
||||
}
|
||||
renderDeferredByVoice = false;
|
||||
if (state.session.isAuthorized && !keyRotationRouteLock) {
|
||||
checkShareOwner(state.session.login);
|
||||
if (activateShare(state.session.login) && window.location.pathname !== '/contacts') { navigate('contacts'); return; }
|
||||
@@ -1509,6 +1521,7 @@ function renderApp() {
|
||||
}
|
||||
|
||||
screenEl.append(screen);
|
||||
mountedPath = window.location.pathname;
|
||||
const pageCleanup = typeof screen.cleanup === 'function' ? screen.cleanup : null;
|
||||
const scrollToBottomControl = attachPageScrollToBottom(pageId, screen);
|
||||
currentCleanup = () => {
|
||||
@@ -2100,6 +2113,9 @@ async function init() {
|
||||
if (!allowShareNavigation(window.location.pathname)) { restoreSharePath(); return; }
|
||||
renderApp();
|
||||
});
|
||||
onVoiceRecordingIdle(() => {
|
||||
if (renderDeferredByVoice) renderApp();
|
||||
});
|
||||
document.addEventListener('pointerdown', () => {
|
||||
void unlockDmAudio();
|
||||
}, { passive: true });
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
// Пузырь голосового в личной переписке: кнопка воспроизведения, волна громкости
|
||||
// с плавной закраской проигранной части и перемотка тапом по волне.
|
||||
import { t } from '../i18n/index.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { decryptDmFileToBlob } from '../services/dm-file-service.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
computeWaveformFromBlob,
|
||||
computedWaveformFor,
|
||||
decodeWaveform,
|
||||
fillWaveformBars,
|
||||
rememberComputedWaveform,
|
||||
resampleWaveform,
|
||||
} from './dm-voice-waveform.js';
|
||||
|
||||
const CARD_BARS = 40;
|
||||
// Голосовые, отправленные до появления `wf`: ровная низкая полоса, пока файл не загружен.
|
||||
const PLACEHOLDER_LEVEL = 0.16;
|
||||
|
||||
export function formatVoiceDuration(durationMs = 0) {
|
||||
const total = Math.max(0, Math.round(Number(durationMs || 0) / 1000));
|
||||
const minutes = Math.floor(total / 60);
|
||||
const seconds = total % 60;
|
||||
return `${minutes}:${String(seconds).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function createDmVoiceAttachmentCard(attachment) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'dm-voice-card';
|
||||
|
||||
const playBtn = document.createElement('button');
|
||||
playBtn.type = 'button';
|
||||
playBtn.className = 'ui-button dm-voice-card__play';
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'dm-voice-card__body';
|
||||
const track = document.createElement('button');
|
||||
track.type = 'button';
|
||||
track.className = 'ui-button dm-voice-card__track';
|
||||
track.setAttribute('aria-label', t('dialogs.modals.chat_view.label_025'));
|
||||
const wave = document.createElement('span');
|
||||
wave.className = 'dm-voice-wave dm-voice-card__wave';
|
||||
wave.setAttribute('aria-hidden', 'true');
|
||||
const played = document.createElement('span');
|
||||
played.className = 'dm-voice-wave dm-voice-card__wave dm-voice-card__wave--played';
|
||||
played.setAttribute('aria-hidden', 'true');
|
||||
track.append(wave, played);
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'dm-voice-card__meta';
|
||||
const duration = document.createElement('span');
|
||||
duration.textContent = formatVoiceDuration(attachment?.durationMs || 0);
|
||||
const label = document.createElement('span');
|
||||
label.textContent = t('dialogs.modals.chat_view.label_026');
|
||||
meta.append(duration, label);
|
||||
body.append(track, meta);
|
||||
card.append(playBtn, body);
|
||||
|
||||
let values = decodeWaveform(attachment?.waveform) || computedWaveformFor(attachment?.id);
|
||||
const paintWave = () => {
|
||||
const levels = values ? resampleWaveform(values, CARD_BARS) : new Array(CARD_BARS).fill(PLACEHOLDER_LEVEL);
|
||||
fillWaveformBars(wave, levels);
|
||||
fillWaveformBars(played, levels);
|
||||
card.classList.toggle('is-placeholder', !values);
|
||||
};
|
||||
paintWave();
|
||||
|
||||
let shownPlaying = null;
|
||||
const setPlaying = (playing) => {
|
||||
if (shownPlaying === playing) return;
|
||||
shownPlaying = playing;
|
||||
playBtn.innerHTML = iconHtml(playing ? 'pause' : 'play', !playing);
|
||||
playBtn.setAttribute('aria-label', t(playing ? 'screens.chat_view.voice.pause_playback' : 'dialogs.modals.chat_view.label_024'));
|
||||
};
|
||||
setPlaying(false);
|
||||
|
||||
let audio = null;
|
||||
let objectUrl = '';
|
||||
let loading = false;
|
||||
let frame = 0;
|
||||
|
||||
const release = () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
try { audio?.pause(); } catch { /* уже остановлен */ }
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
objectUrl = '';
|
||||
}
|
||||
};
|
||||
|
||||
const totalSeconds = () => (Number.isFinite(audio?.duration) && audio.duration > 0
|
||||
? audio.duration
|
||||
: Math.max(0, Number(attachment?.durationMs || 0) / 1000));
|
||||
|
||||
const syncProgress = () => {
|
||||
if (!audio) return;
|
||||
if (!card.isConnected) {
|
||||
release();
|
||||
return;
|
||||
}
|
||||
const total = totalSeconds();
|
||||
const current = Math.max(0, Number(audio.currentTime || 0));
|
||||
track.style.setProperty('--progress', total > 0 ? Math.min(1, current / total).toFixed(4) : '0');
|
||||
const text = `${formatVoiceDuration(current * 1000)} / ${formatVoiceDuration(total * 1000)}`;
|
||||
if (duration.textContent !== text) duration.textContent = text;
|
||||
setPlaying(!audio.paused);
|
||||
};
|
||||
|
||||
// timeupdate приходит ~4 раза в секунду: закраска волны рывками. Пока играет — ведём её по кадрам.
|
||||
const followPlayback = () => {
|
||||
frame = 0;
|
||||
syncProgress();
|
||||
if (audio && !audio.paused && card.isConnected) frame = window.requestAnimationFrame(followPlayback);
|
||||
};
|
||||
|
||||
const ensureAudio = async () => {
|
||||
if (audio) return audio;
|
||||
if (loading) return null;
|
||||
loading = true;
|
||||
playBtn.disabled = true;
|
||||
try {
|
||||
const blob = await decryptDmFileToBlob(attachment);
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
audio = new Audio(objectUrl);
|
||||
audio.preload = 'metadata';
|
||||
audio.addEventListener('timeupdate', syncProgress);
|
||||
audio.addEventListener('loadedmetadata', syncProgress);
|
||||
audio.addEventListener('pause', syncProgress);
|
||||
audio.addEventListener('play', () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
followPlayback();
|
||||
});
|
||||
audio.addEventListener('ended', () => {
|
||||
audio.currentTime = 0;
|
||||
syncProgress();
|
||||
});
|
||||
audio.addEventListener('error', () => {
|
||||
showToast(t('screens.chat_view.text_041'), { kind: 'error', timeoutMs: 2200 });
|
||||
});
|
||||
if (!values) {
|
||||
// Волна старого голосового — украшение: если браузер не декодирует формат,
|
||||
// остаётся заглушка, а воспроизведение работает как обычно.
|
||||
computeWaveformFromBlob(blob).then((computed) => {
|
||||
if (!computed) return;
|
||||
rememberComputedWaveform(attachment?.id, computed);
|
||||
values = computed;
|
||||
if (card.isConnected) paintWave();
|
||||
}).catch(() => {});
|
||||
}
|
||||
return audio;
|
||||
} finally {
|
||||
loading = false;
|
||||
playBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
playBtn.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
try {
|
||||
const player = await ensureAudio();
|
||||
if (!player) return;
|
||||
if (player.paused) await player.play();
|
||||
else player.pause();
|
||||
syncProgress();
|
||||
} catch (error) {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_042'), error), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
track.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
try {
|
||||
const player = await ensureAudio();
|
||||
// У webm из MediaRecorder duration = Infinity до полной прокрутки: берём длительность из `dur`.
|
||||
const total = player ? totalSeconds() : 0;
|
||||
if (!player || total <= 0) return;
|
||||
const rect = track.getBoundingClientRect();
|
||||
const ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / Math.max(1, rect.width)));
|
||||
player.currentTime = total * ratio;
|
||||
syncProgress();
|
||||
} catch (error) {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_043'), error), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
return card;
|
||||
}
|
||||
@@ -0,0 +1,686 @@
|
||||
// Запись голосового в личной переписке.
|
||||
// Удержание микрофона — запись; отпустил — отправка; влево — отмена с эффектом корзины;
|
||||
// вверх — замок, в котором есть пауза, удаление и отправка. Короткий тап только подсказывает.
|
||||
// Модуль — единственный владелец микрофона, MediaRecorder, анализатора громкости и панели
|
||||
// записи. Кнопкой и загрузкой файла владеет страница чата: она передаёт сюда события
|
||||
// указателя и получает готовый файл через onRecorded.
|
||||
import { th } from '../i18n/index.js';
|
||||
import { compressLevels, encodeWaveform, rmsLevel } from './dm-voice-waveform.js';
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
const TAP_MS = 400;
|
||||
const LOCK_DISTANCE = 64;
|
||||
const CANCEL_MIN = 90;
|
||||
const CANCEL_MAX = 150;
|
||||
const CANCEL_RATIO = 0.4;
|
||||
// Отсчёты громкости для поля wf: часто, чтобы волна в сообщении была точной.
|
||||
const SAMPLE_MS = 50;
|
||||
// Живая волна на экране идёт вдвое медленнее отсчётов: новый столбик раз в 110 мс,
|
||||
// а между ними полоса едет плавно — без ряби от 20 скачков в секунду.
|
||||
const LIVE_STEP_MS = 110;
|
||||
const LIVE_BARS = 40;
|
||||
const BAR_GROW_MS = 180;
|
||||
const HALO_SMOOTHING = 0.2;
|
||||
const TIP_MS = 2400;
|
||||
const SNAP_MS = 380;
|
||||
const RETURN_MS = 320;
|
||||
const TRASH_MS = 1300;
|
||||
const DISSOLVE_DELAY_MS = 120;
|
||||
const DISSOLVE_MS = 480;
|
||||
const DUST_COUNT = 64;
|
||||
// Доля пылинок, которые втягиваются в корзину; остальные разлетаются облаком.
|
||||
const DUST_TO_TRASH = 0.3;
|
||||
const MIME_CANDIDATES = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4', 'audio/webm'];
|
||||
// Голосу хватает 32 кбит/с (opus): по умолчанию браузер пишет ~128–170 кбит/с,
|
||||
// и файлы выходят в 4–5 раз тяжелее без слышимой разницы для речи.
|
||||
const VOICE_BITRATE = 32_000;
|
||||
const IDLE_EVENT = 'shine-voice-recording-idle';
|
||||
const AUDIO_CONSTRAINTS = {
|
||||
audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
|
||||
video: false,
|
||||
};
|
||||
const LIVE_STATES = new Set(['holding', 'locked', 'paused']);
|
||||
const PANEL_STATES = new Set(['holding', 'locked', 'paused', 'cancelling']);
|
||||
|
||||
const svg = (body, className = '') => `<svg${className ? ` class="${className}"` : ''} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
|
||||
// Крышка корзины — отдельная группа: при удалении записи она откидывается и захлопывается.
|
||||
const TRASH_SVG = svg('<g class="dm-voice-trash__lid"><path d="M4 7h16M9.5 7V4.8h5V7"/></g><path d="M6.5 7l.9 12.2a1.9 1.9 0 0 0 1.9 1.8h5.4a1.9 1.9 0 0 0 1.9-1.8L17.5 7M10 11v6M14 11v6"/>', 'dm-voice-trash');
|
||||
// Дужка замка поднята, пока запись не закреплена.
|
||||
const LOCK_SVG = svg('<path class="dm-voice-lock-icon__shackle" d="M8.5 11V8a3.5 3.5 0 0 1 7 0v3"/><rect x="5.5" y="11" width="13" height="9.5" rx="2.5"/>', 'dm-voice-lock-icon');
|
||||
const CHEVRON_UP = svg('<path d="m7 14 5-5 5 5"/>', 'dm-voice-lock__arrow');
|
||||
const CHEVRON_LEFT = svg('<path d="m14.5 6-6 6 6 6"/>');
|
||||
|
||||
const now = () => performance.now();
|
||||
const vibrate = (pattern) => {
|
||||
try { navigator.vibrate?.(pattern); } catch { /* вибрация есть не везде */ }
|
||||
};
|
||||
const prefersReducedMotion = () => Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches);
|
||||
// RMS речи обычно 0.02–0.3: корень растягивает тихие звуки, чтобы живая волна не лежала плоско.
|
||||
const displayLevel = (level) => Math.min(1, Math.sqrt(Math.max(0, level)) * 1.7);
|
||||
|
||||
function clock(ms) {
|
||||
const total = Math.max(0, Math.floor(ms / 1000));
|
||||
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
// Активные записи всех экземпляров. App не перерисовывает текущий экран, пока идёт запись
|
||||
// или отправка голосового: иначе перемонтирование страницы оборвало бы её.
|
||||
const activeRecorders = new Set();
|
||||
|
||||
export function isVoiceRecordingActive() {
|
||||
return activeRecorders.size > 0;
|
||||
}
|
||||
|
||||
/** Колбэк вызывается, когда не осталось ни одной активной записи. Возвращает отписку. */
|
||||
export function onVoiceRecordingIdle(callback) {
|
||||
window.addEventListener(IDLE_EVENT, callback);
|
||||
return () => window.removeEventListener(IDLE_EVENT, callback);
|
||||
}
|
||||
|
||||
function markRecorderActive(owner, active) {
|
||||
const had = activeRecorders.has(owner);
|
||||
if (active) activeRecorders.add(owner);
|
||||
else activeRecorders.delete(owner);
|
||||
if (!had || active || activeRecorders.size) return;
|
||||
// Асинхронно: отложенная перерисовка не должна начаться посреди смены состояния записи.
|
||||
window.setTimeout(() => {
|
||||
if (!activeRecorders.size) window.dispatchEvent(new CustomEvent(IDLE_EVENT));
|
||||
}, 0);
|
||||
}
|
||||
|
||||
function pickMimeType() {
|
||||
return MIME_CANDIDATES.find((mime) => globalThis.MediaRecorder?.isTypeSupported?.(mime)) || '';
|
||||
}
|
||||
|
||||
function extensionFor(mime = '') {
|
||||
const value = String(mime).toLowerCase();
|
||||
if (value.includes('ogg')) return 'ogg';
|
||||
if (value.includes('mp4') || value.includes('m4a')) return 'm4a';
|
||||
return 'webm';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {HTMLFormElement} options.form — панель ввода (здесь живут замок и подсказка)
|
||||
* @param {HTMLElement} options.bar — капсула ввода (здесь живёт панель записи)
|
||||
* @param {() => boolean} options.canStart — страница проверяет свои запреты и сама объясняет отказ
|
||||
* @param {(state: string) => void} options.onStateChange
|
||||
* @param {(result: {file: File, durationMs: number, waveform: string}) => Promise<void>} options.onRecorded
|
||||
* @param {(problem: {kind: 'unsupported'|'media'|'recorder'|'send', error?: unknown}) => void} options.onError
|
||||
*/
|
||||
export function createDmVoiceRecorder({ form, bar, canStart, onStateChange, onRecorded, onError }) {
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'dm-voice-panel';
|
||||
panel.hidden = true;
|
||||
// Точка записи и корзина делят одну ячейку: при удалении корзина появляется на месте точки
|
||||
// и ничего в панели не сдвигается.
|
||||
panel.innerHTML = `
|
||||
<span class="dm-voice-panel__lead">
|
||||
<span class="dm-voice-panel__dot" aria-hidden="true"></span>
|
||||
<button type="button" class="dm-voice-panel__btn dm-voice-panel__delete" aria-label="${th('screens.chat_view.voice.delete')}">${TRASH_SVG}</button>
|
||||
</span>
|
||||
<span class="dm-voice-panel__time">0:00</span>
|
||||
<span class="dm-voice-panel__wave" aria-hidden="true"><span class="dm-voice-panel__strip"></span></span>
|
||||
<span class="dm-voice-panel__slide" aria-hidden="true">${CHEVRON_LEFT}<span>${th('screens.chat_view.voice.slide_cancel')}</span></span>
|
||||
<button type="button" class="dm-voice-panel__btn dm-voice-panel__pause"></button>
|
||||
`;
|
||||
const deleteBtn = panel.querySelector('.dm-voice-panel__delete');
|
||||
const dotEl = panel.querySelector('.dm-voice-panel__dot');
|
||||
const timeEl = panel.querySelector('.dm-voice-panel__time');
|
||||
const waveEl = panel.querySelector('.dm-voice-panel__wave');
|
||||
const stripEl = panel.querySelector('.dm-voice-panel__strip');
|
||||
const pauseBtn = panel.querySelector('.dm-voice-panel__pause');
|
||||
|
||||
const lock = document.createElement('div');
|
||||
lock.className = 'dm-voice-lock';
|
||||
lock.hidden = true;
|
||||
lock.setAttribute('aria-hidden', 'true');
|
||||
lock.innerHTML = `${LOCK_SVG}${CHEVRON_UP}`;
|
||||
|
||||
const tip = document.createElement('div');
|
||||
tip.className = 'dm-voice-tip';
|
||||
tip.setAttribute('role', 'status');
|
||||
|
||||
bar.insertBefore(panel, bar.querySelector('.dm-field'));
|
||||
form.append(lock, tip);
|
||||
|
||||
let state = 'idle';
|
||||
let rec = null;
|
||||
let session = 0;
|
||||
let destroyed = false;
|
||||
let audioCtx = null;
|
||||
let frame = 0;
|
||||
let pointerId = null;
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
let pressedAt = 0;
|
||||
let released = false;
|
||||
let lastClock = '';
|
||||
let tipTimer = 0;
|
||||
let snapTimer = 0;
|
||||
let returnTimer = 0;
|
||||
let escBound = false;
|
||||
let effect = null;
|
||||
let barStep = 0;
|
||||
const owner = {};
|
||||
|
||||
const canPause = () => typeof rec?.recorder?.pause === 'function' && typeof rec?.recorder?.resume === 'function';
|
||||
|
||||
function syncPauseButton() {
|
||||
const paused = state === 'paused';
|
||||
pauseBtn.hidden = !canPause();
|
||||
pauseBtn.innerHTML = iconHtml(paused ? 'mic' : 'pause');
|
||||
pauseBtn.setAttribute('aria-label', th(paused ? 'screens.chat_view.voice.resume' : 'screens.chat_view.voice.pause'));
|
||||
}
|
||||
|
||||
const onKeydown = (event) => {
|
||||
if (event.key !== 'Escape' || !LIVE_STATES.has(state)) return;
|
||||
event.preventDefault();
|
||||
void cancel();
|
||||
};
|
||||
|
||||
function syncEscListener() {
|
||||
const wanted = LIVE_STATES.has(state) && !destroyed;
|
||||
if (wanted === escBound) return;
|
||||
escBound = wanted;
|
||||
if (wanted) document.addEventListener('keydown', onKeydown);
|
||||
else document.removeEventListener('keydown', onKeydown);
|
||||
}
|
||||
|
||||
function setState(next) {
|
||||
const previous = state;
|
||||
state = next;
|
||||
markRecorderActive(owner, next !== 'idle' && !destroyed);
|
||||
panel.hidden = !PANEL_STATES.has(next);
|
||||
panel.dataset.state = next;
|
||||
if (next !== 'holding') panel.style.removeProperty('--slide');
|
||||
window.clearTimeout(snapTimer);
|
||||
if (next === 'holding') {
|
||||
lock.hidden = false;
|
||||
lock.classList.remove('is-snapped');
|
||||
lock.style.removeProperty('--lift');
|
||||
} else if (previous === 'holding' && next === 'locked') {
|
||||
// Замок защёлкивается на глазах и только потом исчезает.
|
||||
lock.classList.add('is-snapped');
|
||||
snapTimer = window.setTimeout(() => { lock.hidden = true; }, SNAP_MS);
|
||||
} else {
|
||||
lock.hidden = true;
|
||||
}
|
||||
if (PANEL_STATES.has(previous) && !PANEL_STATES.has(next)) playReturn();
|
||||
syncPauseButton();
|
||||
syncEscListener();
|
||||
if (!destroyed) onStateChange(next);
|
||||
}
|
||||
|
||||
// Панель записи ушла — поле ввода и кнопки проявляются, а не возникают рывком.
|
||||
function playReturn() {
|
||||
if (prefersReducedMotion()) return;
|
||||
window.clearTimeout(returnTimer);
|
||||
form.classList.remove('dm-voice-return');
|
||||
void form.offsetWidth;
|
||||
form.classList.add('dm-voice-return');
|
||||
returnTimer = window.setTimeout(() => form.classList.remove('dm-voice-return'), RETURN_MS);
|
||||
}
|
||||
|
||||
function ensureAudioContext() {
|
||||
// iOS разрешает запуск звука только внутри жеста: контекст создаётся до запроса микрофона.
|
||||
const Context = globalThis.AudioContext || globalThis.webkitAudioContext;
|
||||
if (!Context) return;
|
||||
try {
|
||||
if (!audioCtx || audioCtx.state === 'closed') audioCtx = new Context();
|
||||
void audioCtx.resume?.()?.catch?.(() => {});
|
||||
} catch {
|
||||
audioCtx = null;
|
||||
}
|
||||
}
|
||||
|
||||
function connectAnalyser(current) {
|
||||
if (!audioCtx) return;
|
||||
try {
|
||||
current.source = audioCtx.createMediaStreamSource(current.stream);
|
||||
current.analyser = audioCtx.createAnalyser();
|
||||
current.analyser.fftSize = 1024;
|
||||
current.samples = new Float32Array(current.analyser.fftSize);
|
||||
current.source.connect(current.analyser);
|
||||
} catch {
|
||||
// Без анализатора запись работает, просто без живой волны и без поля wf.
|
||||
current.analyser = null;
|
||||
}
|
||||
}
|
||||
|
||||
function readLevel() {
|
||||
const analyser = rec?.analyser;
|
||||
if (!analyser?.getFloatTimeDomainData) return 0;
|
||||
analyser.getFloatTimeDomainData(rec.samples);
|
||||
return rmsLevel(rec.samples);
|
||||
}
|
||||
|
||||
function elapsedMs() {
|
||||
if (!rec) return 0;
|
||||
return rec.activeMs + (rec.segmentStartedAt ? now() - rec.segmentStartedAt : 0);
|
||||
}
|
||||
|
||||
function paintClock(ms) {
|
||||
const text = clock(ms);
|
||||
if (text === lastClock) return;
|
||||
lastClock = text;
|
||||
timeEl.textContent = text;
|
||||
}
|
||||
|
||||
function makeBar(level) {
|
||||
const bar = document.createElement('span');
|
||||
bar.className = 'dm-voice-wave__bar';
|
||||
bar.style.setProperty('--level', level.toFixed(3));
|
||||
return bar;
|
||||
}
|
||||
|
||||
/** Полоса из LIVE_BARS + 1 столбика: лишний — тот, что сейчас въезжает справа. */
|
||||
function resetStrip() {
|
||||
stripEl.replaceChildren(...Array.from({ length: LIVE_BARS + 1 }, () => makeBar(0)));
|
||||
stripEl.style.transform = '';
|
||||
barStep = 0;
|
||||
}
|
||||
|
||||
/** Новый столбик встаёт в конец полосы, самый старый уходит; высоты остальных не трогаем. */
|
||||
function pushLiveBar(level) {
|
||||
const bar = makeBar(level);
|
||||
stripEl.append(bar);
|
||||
while (stripEl.children.length > LIVE_BARS + 1) stripEl.firstElementChild.remove();
|
||||
if (!prefersReducedMotion() && typeof bar.animate === 'function') {
|
||||
// Столбик вырастает, а не появляется скачком: волна «дышит» мягко.
|
||||
bar.animate(
|
||||
[{ transform: 'scaleY(0.12)' }, { transform: `scaleY(${Math.max(0.12, level).toFixed(3)})` }],
|
||||
{ duration: BAR_GROW_MS, easing: 'ease-out' },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function tick() {
|
||||
frame = 0;
|
||||
if (destroyed || !rec || (state !== 'holding' && state !== 'locked')) return;
|
||||
const level = readLevel();
|
||||
const ms = elapsedMs();
|
||||
// Отсчёты по времени записи, а не по кадрам: в фоне кадров нет, а волна не должна сжиматься.
|
||||
while (rec.nextSampleAt <= ms) {
|
||||
rec.levels.push(level);
|
||||
rec.nextSampleAt += SAMPLE_MS;
|
||||
}
|
||||
rec.windowSum += level;
|
||||
rec.windowPeak = Math.max(rec.windowPeak, level);
|
||||
rec.windowCount += 1;
|
||||
while (rec.nextBarAt <= ms) {
|
||||
// Высота столбика — среднее с пиком за его 110 мс, а не один случайный замер.
|
||||
const mean = rec.windowCount ? rec.windowSum / rec.windowCount : level;
|
||||
pushLiveBar(displayLevel((mean + rec.windowPeak) / 2));
|
||||
rec.windowSum = 0;
|
||||
rec.windowPeak = 0;
|
||||
rec.windowCount = 0;
|
||||
rec.nextBarAt += LIVE_STEP_MS;
|
||||
}
|
||||
if (!barStep && stripEl.children.length > 1) {
|
||||
barStep = stripEl.children[1].offsetLeft - stripEl.children[0].offsetLeft;
|
||||
}
|
||||
// Между столбиками полоса едет плавно: новый въезжает справа ровно за LIVE_STEP_MS.
|
||||
const shift = Math.max(0, Math.min(1, (rec.nextBarAt - ms) / LIVE_STEP_MS)) * barStep;
|
||||
stripEl.style.transform = `translateX(${shift.toFixed(2)}px)`;
|
||||
paintClock(ms);
|
||||
rec.halo += (displayLevel(level) - rec.halo) * HALO_SMOOTHING;
|
||||
form.style.setProperty('--voice-level', rec.halo.toFixed(3));
|
||||
frame = window.requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
function startLoop() {
|
||||
if (!frame) frame = window.requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
function stopLoop() {
|
||||
window.cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
form.style.removeProperty('--voice-level');
|
||||
}
|
||||
|
||||
function releaseMedia(current) {
|
||||
try { current.stream?.getTracks?.().forEach((track) => track.stop()); } catch { /* микрофон уже освобождён */ }
|
||||
try { current.source?.disconnect(); } catch { /* граф уже разобран */ }
|
||||
current.source = null;
|
||||
current.analyser = null;
|
||||
void audioCtx?.suspend?.()?.catch?.(() => {});
|
||||
}
|
||||
|
||||
/** Бросить текущую запись: звук и уровни стираются, микрофон освобождается. */
|
||||
function discardRecording() {
|
||||
const current = rec;
|
||||
rec = null;
|
||||
stopLoop();
|
||||
if (!current) return;
|
||||
current.chunks.length = 0;
|
||||
current.levels.length = 0;
|
||||
try {
|
||||
if (current.recorder.state !== 'inactive') current.recorder.stop();
|
||||
} catch { /* уже остановлен */ }
|
||||
releaseMedia(current);
|
||||
}
|
||||
|
||||
async function openMicrophone(id) {
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia(AUDIO_CONSTRAINTS);
|
||||
if (destroyed || id !== session) {
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
return false;
|
||||
}
|
||||
const mimeType = pickMimeType();
|
||||
const options = mimeType ? { mimeType, audioBitsPerSecond: VOICE_BITRATE } : { audioBitsPerSecond: VOICE_BITRATE };
|
||||
const recorder = new MediaRecorder(stream, options);
|
||||
const current = {
|
||||
stream, recorder, mimeType, chunks: [], levels: [],
|
||||
activeMs: 0, segmentStartedAt: 0, nextSampleAt: 0,
|
||||
nextBarAt: LIVE_STEP_MS, windowSum: 0, windowPeak: 0, windowCount: 0, halo: 0,
|
||||
source: null, analyser: null, samples: null,
|
||||
};
|
||||
recorder.addEventListener('dataavailable', (event) => {
|
||||
if (event.data?.size > 0) current.chunks.push(event.data);
|
||||
});
|
||||
recorder.addEventListener('error', (event) => {
|
||||
if (rec === current) onError({ kind: 'recorder', error: event?.error });
|
||||
});
|
||||
rec = current;
|
||||
connectAnalyser(current);
|
||||
recorder.start(1000);
|
||||
current.segmentStartedAt = now();
|
||||
lastClock = '';
|
||||
paintClock(0);
|
||||
resetStrip();
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (destroyed || id !== session) return false;
|
||||
discardRecording();
|
||||
setState('idle');
|
||||
onError({ kind: 'media', error });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function begin({ locked }) {
|
||||
if (destroyed || state !== 'idle') return;
|
||||
hideTip();
|
||||
if (!globalThis.MediaRecorder || !navigator.mediaDevices?.getUserMedia) {
|
||||
onError({ kind: 'unsupported' });
|
||||
return;
|
||||
}
|
||||
if (!canStart()) return;
|
||||
released = false;
|
||||
pressedAt = now();
|
||||
const id = ++session;
|
||||
ensureAudioContext();
|
||||
setState('starting');
|
||||
if (!(await openMicrophone(id))) return;
|
||||
if (!locked && released) {
|
||||
// Палец отпустили раньше, чем открылся микрофон (быстрый тап или окно разрешения).
|
||||
discardRecording();
|
||||
setState('idle');
|
||||
showTip();
|
||||
return;
|
||||
}
|
||||
setState(locked ? 'locked' : 'holding');
|
||||
vibrate(10);
|
||||
startLoop();
|
||||
}
|
||||
|
||||
function stopRecorder(current) {
|
||||
return new Promise((resolve) => {
|
||||
const { recorder, chunks } = current;
|
||||
const done = () => resolve(new Blob(chunks, { type: recorder.mimeType || current.mimeType || chunks[0]?.type || 'audio/webm' }));
|
||||
if (recorder.state === 'inactive') {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
recorder.addEventListener('stop', done, { once: true });
|
||||
try {
|
||||
recorder.stop();
|
||||
} catch {
|
||||
done();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function finish() {
|
||||
if (!rec || !LIVE_STATES.has(state)) return;
|
||||
const current = rec;
|
||||
const durationMs = Math.round(elapsedMs());
|
||||
const waveform = current.levels.length ? encodeWaveform(compressLevels(current.levels)) : '';
|
||||
stopLoop();
|
||||
setState('busy');
|
||||
const blob = await stopRecorder(current);
|
||||
releaseMedia(current);
|
||||
if (rec === current) rec = null;
|
||||
if (destroyed) return;
|
||||
if (!blob.size) {
|
||||
setState('idle');
|
||||
return;
|
||||
}
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const file = new File([blob], `voice-${stamp}.${extensionFor(blob.type)}`, { type: blob.type, lastModified: Date.now() });
|
||||
try {
|
||||
await onRecorded({ file, durationMs, waveform });
|
||||
} catch (error) {
|
||||
if (!destroyed) onError({ kind: 'send', error });
|
||||
} finally {
|
||||
if (!destroyed) setState('idle');
|
||||
}
|
||||
}
|
||||
|
||||
function lockRecording() {
|
||||
if (state !== 'holding') return;
|
||||
setState('locked');
|
||||
vibrate(15);
|
||||
}
|
||||
|
||||
function togglePause() {
|
||||
if (!rec || !canPause()) return;
|
||||
if (state === 'locked' && rec.recorder.state === 'recording') {
|
||||
rec.recorder.pause();
|
||||
rec.activeMs += now() - rec.segmentStartedAt;
|
||||
rec.segmentStartedAt = 0;
|
||||
stopLoop();
|
||||
setState('paused');
|
||||
} else if (state === 'paused' && rec.recorder.state === 'paused') {
|
||||
rec.recorder.resume();
|
||||
rec.segmentStartedAt = now();
|
||||
setState('locked');
|
||||
startLoop();
|
||||
}
|
||||
}
|
||||
|
||||
function stopEffect() {
|
||||
if (!effect) return;
|
||||
effect.animations.forEach((animation) => animation.cancel());
|
||||
effect.dust.forEach((node) => node.remove());
|
||||
effect = null;
|
||||
}
|
||||
|
||||
// Удаление записи: крышка корзины откидывается, полоса волны растворяется справа налево
|
||||
// в облако пыльцы — большая часть пылинок разлетается вверх и вбок и гаснет, часть
|
||||
// втягивается в корзину; крышка захлопывается, корзина вздрагивает и исчезает.
|
||||
function playTrashEffect() {
|
||||
if (prefersReducedMotion() || typeof panel.animate !== 'function') return Promise.resolve();
|
||||
const lid = deleteBtn.querySelector('.dm-voice-trash__lid');
|
||||
const panelRect = panel.getBoundingClientRect();
|
||||
const waveRect = waveEl.getBoundingClientRect();
|
||||
const trashRect = deleteBtn.getBoundingClientRect();
|
||||
const targetX = trashRect.left + trashRect.width / 2 - panelRect.left;
|
||||
const targetY = trashRect.top + trashRect.height / 2 - panelRect.top;
|
||||
// Пыльца рождается только из видимых столбиков: у громких мест облако гуще.
|
||||
const bars = [...stripEl.children]
|
||||
.map((bar) => bar.getBoundingClientRect())
|
||||
.filter((rect) => rect.right > waveRect.left && rect.left < waveRect.right);
|
||||
const current = { animations: [], dust: [] };
|
||||
effect = current;
|
||||
const run = (node, keyframes, options) => {
|
||||
if (!node) return;
|
||||
current.animations.push(node.animate(keyframes, { fill: 'forwards', ...options }));
|
||||
};
|
||||
|
||||
run(deleteBtn, [
|
||||
{ transform: 'scale(.6)', opacity: 0 },
|
||||
{ transform: 'scale(1)', opacity: 1, offset: 0.14 },
|
||||
{ transform: 'scale(1) rotate(0deg)', offset: 0.8 },
|
||||
{ transform: 'scale(1) rotate(-10deg)', offset: 0.85 },
|
||||
{ transform: 'scale(1) rotate(8deg)', offset: 0.9 },
|
||||
{ transform: 'scale(1) rotate(0deg)', opacity: 1, offset: 0.94 },
|
||||
{ transform: 'scale(.7) translateY(6px)', opacity: 0 },
|
||||
], { duration: TRASH_MS, easing: 'ease-out' });
|
||||
run(lid, [
|
||||
{ transform: 'rotate(0deg)' },
|
||||
{ transform: 'rotate(-38deg)', offset: 0.16 },
|
||||
{ transform: 'rotate(-38deg)', offset: 0.74 },
|
||||
{ transform: 'rotate(0deg)', offset: 0.82 },
|
||||
{ transform: 'rotate(0deg)' },
|
||||
], { duration: TRASH_MS, easing: 'ease-in-out' });
|
||||
run(dotEl, [{ opacity: 1 }, { opacity: 0 }], { duration: 160 });
|
||||
run(timeEl, [{ opacity: 1 }, { opacity: 0 }], { duration: 240 });
|
||||
// Фронт растворения идёт справа налево с постоянной скоростью — пылинки рождаются ровно на нём.
|
||||
run(waveEl, [{ clipPath: 'inset(0 0 0 0)' }, { clipPath: 'inset(0 100% 0 0)' }], {
|
||||
duration: DISSOLVE_MS, delay: DISSOLVE_DELAY_MS, easing: 'linear',
|
||||
});
|
||||
|
||||
for (let i = 0; i < DUST_COUNT && bars.length; i += 1) {
|
||||
const rect = bars[Math.floor(Math.random() * bars.length)];
|
||||
const x = rect.left + rect.width * Math.random() - panelRect.left;
|
||||
const y = rect.top + rect.height * Math.random() - panelRect.top;
|
||||
const front = (x + panelRect.left - waveRect.left) / Math.max(1, waveRect.width);
|
||||
const delay = DISSOLVE_DELAY_MS + (1 - Math.min(1, Math.max(0, front))) * DISSOLVE_MS;
|
||||
const dust = document.createElement('span');
|
||||
dust.className = Math.random() < 0.35 ? 'dm-voice-dust is-light' : 'dm-voice-dust';
|
||||
dust.style.left = `${x}px`;
|
||||
dust.style.top = `${y}px`;
|
||||
const size = 1.4 + Math.random() * 1.8;
|
||||
dust.style.width = `${size}px`;
|
||||
dust.style.height = `${size}px`;
|
||||
panel.append(dust);
|
||||
current.dust.push(dust);
|
||||
if (Math.random() < DUST_TO_TRASH) {
|
||||
run(dust, [
|
||||
{ transform: 'translate(0, 0) scale(1)', opacity: 0 },
|
||||
{ opacity: 1, offset: 0.12 },
|
||||
{ transform: `translate(${targetX - x}px, ${targetY - y}px) scale(.3)`, opacity: 0.2 },
|
||||
], { duration: 420 + Math.random() * 160, delay, easing: 'cubic-bezier(.55, .05, .7, .2)' });
|
||||
} else {
|
||||
// Облако: небольшой разброс, дрейф вверх и слегка в сторону корзины, плавное затухание.
|
||||
const dx = -16 + Math.random() * 24;
|
||||
const dy = -(6 + Math.random() * 18);
|
||||
run(dust, [
|
||||
{ transform: 'translate(0, 0) scale(1)', opacity: 0 },
|
||||
{ transform: `translate(${(dx * 0.3).toFixed(1)}px, ${(dy * 0.3).toFixed(1)}px) scale(1)`, opacity: 1, offset: 0.2 },
|
||||
{ transform: `translate(${dx.toFixed(1)}px, ${dy.toFixed(1)}px) scale(.4)`, opacity: 0 },
|
||||
], { duration: 450 + Math.random() * 150, delay, easing: 'cubic-bezier(.2, .6, .4, 1)' });
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.allSettled(current.animations.map((animation) => animation.finished)).then(() => {
|
||||
if (effect === current) stopEffect();
|
||||
});
|
||||
}
|
||||
|
||||
async function cancel() {
|
||||
if (!LIVE_STATES.has(state)) return;
|
||||
session += 1;
|
||||
pointerId = null;
|
||||
discardRecording();
|
||||
setState('cancelling');
|
||||
vibrate([12, 40, 12]);
|
||||
await playTrashEffect();
|
||||
if (!destroyed && state === 'cancelling') setState('idle');
|
||||
}
|
||||
|
||||
function showTip() {
|
||||
window.clearTimeout(tipTimer);
|
||||
// Содержимое ставится заново на каждый показ, чтобы экранный диктор озвучил подсказку.
|
||||
tip.innerHTML = `${LOCK_SVG}<span class="dm-voice-tip__text"><strong>${th('screens.chat_view.voice.hold_tip')}</strong><span>${th('screens.chat_view.voice.lock_tip')}</span></span>`;
|
||||
tip.classList.add('is-visible');
|
||||
tipTimer = window.setTimeout(hideTip, TIP_MS);
|
||||
}
|
||||
|
||||
function hideTip() {
|
||||
window.clearTimeout(tipTimer);
|
||||
tip.classList.remove('is-visible');
|
||||
}
|
||||
|
||||
function cancelDistance() {
|
||||
return Math.min(CANCEL_MAX, Math.max(CANCEL_MIN, bar.clientWidth * CANCEL_RATIO));
|
||||
}
|
||||
|
||||
deleteBtn.addEventListener('click', () => { void cancel(); });
|
||||
pauseBtn.addEventListener('click', togglePause);
|
||||
|
||||
return {
|
||||
get state() { return state; },
|
||||
isRecording: () => PANEL_STATES.has(state),
|
||||
|
||||
/** Нажатие на микрофон указателем (палец, мышь, перо). */
|
||||
press(event) {
|
||||
pointerId = event.pointerId ?? null;
|
||||
startX = Number(event.clientX || 0);
|
||||
startY = Number(event.clientY || 0);
|
||||
void begin({ locked: false });
|
||||
},
|
||||
|
||||
move(event) {
|
||||
if (state !== 'holding' || event.pointerId !== pointerId) return;
|
||||
const dx = Math.max(0, startX - Number(event.clientX || 0));
|
||||
const dy = Math.max(0, startY - Number(event.clientY || 0));
|
||||
const cancelAt = cancelDistance();
|
||||
panel.style.setProperty('--slide', Math.min(1, dx / cancelAt).toFixed(3));
|
||||
lock.style.setProperty('--lift', Math.min(1, dy / LOCK_DISTANCE).toFixed(3));
|
||||
if (dx >= cancelAt) void cancel();
|
||||
else if (dy >= LOCK_DISTANCE) lockRecording();
|
||||
},
|
||||
|
||||
release(event) {
|
||||
if (pointerId == null || event.pointerId !== pointerId) return;
|
||||
pointerId = null;
|
||||
released = true;
|
||||
if (state !== 'holding') return;
|
||||
if (now() - pressedAt < TAP_MS) {
|
||||
discardRecording();
|
||||
setState('idle');
|
||||
showTip();
|
||||
return;
|
||||
}
|
||||
void finish();
|
||||
},
|
||||
|
||||
/** Система забрала жест (звонок, системная панель): запись не теряем и не отправляем сами. */
|
||||
interrupt(event) {
|
||||
if (pointerId == null || event.pointerId !== pointerId) return;
|
||||
pointerId = null;
|
||||
released = true;
|
||||
if (state === 'holding') lockRecording();
|
||||
},
|
||||
|
||||
/** С клавиатуры удерживать нечего: запись сразу начинается в режиме замка. */
|
||||
startLocked() {
|
||||
pointerId = null;
|
||||
void begin({ locked: true });
|
||||
},
|
||||
|
||||
send() {
|
||||
void finish();
|
||||
},
|
||||
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
session += 1;
|
||||
discardRecording();
|
||||
stopEffect();
|
||||
window.clearTimeout(tipTimer);
|
||||
window.clearTimeout(snapTimer);
|
||||
window.clearTimeout(returnTimer);
|
||||
syncEscListener();
|
||||
try { void audioCtx?.close?.(); } catch { /* уже закрыт */ }
|
||||
audioCtx = null;
|
||||
state = 'idle';
|
||||
markRecorderActive(owner, false);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// Волна голосового сообщения: 64 уровня громкости 0..31.
|
||||
// В тех-блоке `<S:file;...;kind=voice;wf=...>` уровни упакованы по 5 бит в base64url,
|
||||
// поэтому получатель рисует волну сразу, не скачивая и не расшифровывая файл.
|
||||
// Поле приходит от собеседника внутри расшифрованного текста — это недоверенный ввод:
|
||||
// decodeWaveform() принимает только короткую base64url-строку и иначе возвращает null.
|
||||
|
||||
export const WAVEFORM_POINTS = 64;
|
||||
export const WAVEFORM_MAX_LEVEL = 31;
|
||||
|
||||
const BITS = 5;
|
||||
const ENCODED_BYTES = Math.ceil((WAVEFORM_POINTS * BITS) / 8);
|
||||
const WF_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
||||
// Ниже этого RMS запись считается тишиной: шум микрофона не растягиваем до полной высоты.
|
||||
const SILENCE_LEVEL = 0.002;
|
||||
// Сжатие динамики: тихие слоги остаются видимыми рядом с громкими.
|
||||
const CURVE = 0.75;
|
||||
const FALLBACK_CACHE_LIMIT = 200;
|
||||
|
||||
function cleanLevel(value) {
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
/** Максимум по отрезку [from, to) — пики громкости при сжатии не теряются. */
|
||||
function peakInRange(values, from, to, read) {
|
||||
let peak = 0;
|
||||
for (let i = from; i < to; i += 1) peak = Math.max(peak, read(values[i]));
|
||||
return peak;
|
||||
}
|
||||
|
||||
function spread(length, count, index) {
|
||||
const from = Math.floor((index * length) / count);
|
||||
const to = Math.max(from + 1, Math.floor(((index + 1) * length) / count));
|
||||
return [Math.min(from, length - 1), Math.min(to, length)];
|
||||
}
|
||||
|
||||
/** Уровни громкости (RMS 0..1, любой длины) → `points` значений 0..31. */
|
||||
export function compressLevels(levels, points = WAVEFORM_POINTS) {
|
||||
const clean = Array.from(levels ?? [], cleanLevel);
|
||||
const out = new Uint8Array(points);
|
||||
if (!clean.length) return out;
|
||||
|
||||
const buckets = Array.from({ length: points }, (_, i) => {
|
||||
const [from, to] = spread(clean.length, points, i);
|
||||
return peakInRange(clean, from, to, (v) => v);
|
||||
});
|
||||
const peak = Math.max(...buckets);
|
||||
if (peak < SILENCE_LEVEL) return out;
|
||||
buckets.forEach((value, i) => {
|
||||
out[i] = Math.round(WAVEFORM_MAX_LEVEL * (value / peak) ** CURVE);
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function toBase64Url(bytes) {
|
||||
let binary = '';
|
||||
bytes.forEach((byte) => { binary += String.fromCharCode(byte); });
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
function fromBase64Url(text) {
|
||||
const base64 = text.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, '='));
|
||||
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
||||
}
|
||||
|
||||
/** Ровно 64 значения (лишнее отбрасывается, недостающее = 0) → 54 символа base64url. */
|
||||
export function encodeWaveform(values) {
|
||||
const bytes = new Uint8Array(ENCODED_BYTES);
|
||||
for (let i = 0; i < WAVEFORM_POINTS; i += 1) {
|
||||
const raw = Number(values?.[i]);
|
||||
const value = Number.isFinite(raw) ? Math.min(WAVEFORM_MAX_LEVEL, Math.max(0, Math.round(raw))) : 0;
|
||||
for (let bit = BITS - 1; bit >= 0; bit -= 1) {
|
||||
const position = i * BITS + (BITS - 1 - bit);
|
||||
if ((value >> bit) & 1) bytes[position >> 3] |= 0x80 >> (position & 7);
|
||||
}
|
||||
}
|
||||
return toBase64Url(bytes);
|
||||
}
|
||||
|
||||
/** Строка из поля `wf` → значения 0..31 или null, если это не наша упаковка. */
|
||||
export function decodeWaveform(text) {
|
||||
if (typeof text !== 'string' || !WF_PATTERN.test(text)) return null;
|
||||
let bytes;
|
||||
try {
|
||||
bytes = fromBase64Url(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const count = Math.floor((bytes.length * 8) / BITS);
|
||||
if (!count) return null;
|
||||
const out = new Uint8Array(count);
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
let value = 0;
|
||||
for (let bit = 0; bit < BITS; bit += 1) {
|
||||
const position = i * BITS + bit;
|
||||
value = (value << 1) | ((bytes[position >> 3] >> (7 - (position & 7))) & 1);
|
||||
}
|
||||
out[i] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Значения 0..31 → `count` высот столбиков 0..1 (сжатие по максимуму, растяжение по ближайшему). */
|
||||
export function resampleWaveform(values, count) {
|
||||
const length = values?.length || 0;
|
||||
if (!length) return new Array(count).fill(0);
|
||||
const read = (v) => Math.min(1, cleanLevel(v) / WAVEFORM_MAX_LEVEL);
|
||||
return Array.from({ length: count }, (_, i) => {
|
||||
const [from, to] = spread(length, count, i);
|
||||
return peakInRange(values, from, to, read);
|
||||
});
|
||||
}
|
||||
|
||||
/** Среднеквадратичная громкость отрезка сигнала (-1..1). */
|
||||
export function rmsLevel(samples) {
|
||||
const length = samples?.length || 0;
|
||||
if (!length) return 0;
|
||||
let sum = 0;
|
||||
for (let i = 0; i < length; i += 1) sum += samples[i] * samples[i];
|
||||
return Math.sqrt(sum / length);
|
||||
}
|
||||
|
||||
/** Волна по готовому звуку — для старых голосовых, отправленных без `wf`. */
|
||||
export function waveformFromChannelData(data, points = WAVEFORM_POINTS) {
|
||||
const length = data?.length || 0;
|
||||
if (!length) return new Uint8Array(points);
|
||||
const blocks = Math.min(length, points * 4);
|
||||
const levels = Array.from({ length: blocks }, (_, i) => {
|
||||
const [from, to] = spread(length, blocks, i);
|
||||
return rmsLevel(data.subarray(from, to));
|
||||
});
|
||||
return compressLevels(levels, points);
|
||||
}
|
||||
|
||||
export async function computeWaveformFromBlob(blob) {
|
||||
const Offline = globalThis.OfflineAudioContext || globalThis.webkitOfflineAudioContext;
|
||||
if (!Offline || !blob) return null;
|
||||
const context = new Offline(1, 1, 44_100);
|
||||
const buffer = await context.decodeAudioData(await blob.arrayBuffer());
|
||||
return waveformFromChannelData(buffer.getChannelData(0));
|
||||
}
|
||||
|
||||
// Волны старых голосовых живут до перезагрузки страницы: при перерисовке ленты
|
||||
// столбики не возвращаются к заглушке и файл не декодируется повторно.
|
||||
const computedWaveforms = new Map();
|
||||
|
||||
export function computedWaveformFor(id) {
|
||||
return computedWaveforms.get(String(id || '')) || null;
|
||||
}
|
||||
|
||||
export function rememberComputedWaveform(id, values) {
|
||||
const key = String(id || '');
|
||||
if (!key || !values) return;
|
||||
computedWaveforms.delete(key);
|
||||
computedWaveforms.set(key, values);
|
||||
if (computedWaveforms.size > FALLBACK_CACHE_LIMIT) {
|
||||
computedWaveforms.delete(computedWaveforms.keys().next().value);
|
||||
}
|
||||
}
|
||||
|
||||
/** Столбики в контейнере: `--level` 0..1 задаёт высоту, геометрия — в dm-voice.css. */
|
||||
export function fillWaveformBars(container, levels) {
|
||||
if (!container) return;
|
||||
while (container.children.length < levels.length) {
|
||||
const bar = document.createElement('span');
|
||||
bar.className = 'dm-voice-wave__bar';
|
||||
container.append(bar);
|
||||
}
|
||||
while (container.children.length > levels.length) container.lastElementChild.remove();
|
||||
levels.forEach((level, i) => {
|
||||
container.children[i].style.setProperty('--level', level.toFixed(3));
|
||||
});
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -15,6 +15,8 @@ const paths = {
|
||||
emoji: '<circle cx="12" cy="12" r="9"/><path d="M8.3 14.2a4.6 4.6 0 0 0 7.4 0"/><circle cx="9" cy="9.8" r=".9" fill="currentColor" stroke="none"/><circle cx="15" cy="9.8" r=".9" fill="currentColor" stroke="none"/>',
|
||||
send: '<path d="M12 19V5M5.5 11.5 12 5l6.5 6.5"/>',
|
||||
mic: '<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/>',
|
||||
play: '<path d="M8.2 5.6v12.8a1 1 0 0 0 1.5.86l10.4-6.4a1 1 0 0 0 0-1.72L9.7 4.74a1 1 0 0 0-1.5.86Z"/>',
|
||||
pause: '<path d="M8.5 5.5v13M15.5 5.5v13"/>',
|
||||
camera: '<path d="M4.5 7.5h2.8l1.7-2.5h6l1.7 2.5h2.8A1.5 1.5 0 0 1 21 9v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18V9a1.5 1.5 0 0 1 1.5-1.5Z"/><circle cx="12" cy="13" r="3.5"/>',
|
||||
image: '<rect x="3" y="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="9.5" r="1.6"/><path d="m21 16-4.7-4.7-8.2 8.2"/>',
|
||||
list: '<path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4.5" cy="6" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r=".9" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r=".9" fill="currentColor" stroke="none"/>',
|
||||
@@ -50,6 +52,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"/>',
|
||||
|
||||
@@ -375,10 +375,8 @@
|
||||
"label_030": "Stop and send voice",
|
||||
"label_031": "Encrypting and sending voice",
|
||||
"label_032": "Record Voice Message",
|
||||
"label_033": "↑ swipe up to secure",
|
||||
"label_034": "Encrypting and Uploading Files",
|
||||
"label_035": "File",
|
||||
"label_036": "Record pinned · click ■to submit",
|
||||
"add_user_prefix": "Add User",
|
||||
"add_user_suffix": "to contacts?"
|
||||
},
|
||||
@@ -1023,7 +1021,9 @@
|
||||
"text_005": "File downloaded",
|
||||
"text_006": "file",
|
||||
"text_007": "Download {value1}",
|
||||
"file_expired": "File no longer available: encrypted attachments are kept for up to 14 days."
|
||||
"file_expired": "File no longer available: encrypted attachments are kept for up to 14 days.",
|
||||
"remaining_less_day": "Attachment available for less than a day",
|
||||
"remaining_days": "Attachment available for {value1} more days"
|
||||
},
|
||||
"palette_editor": {
|
||||
"text_001": "Failed to read palette, please make sure the whole text is copied.",
|
||||
@@ -2289,15 +2289,23 @@
|
||||
"chat_view": {
|
||||
"security_notice": {
|
||||
"title": "Private chat security",
|
||||
"encryption": "Messages in this chat are encrypted on the participants' devices.",
|
||||
"servers": "The server delivers encrypted data but should not be able to read the conversation.",
|
||||
"derivation": "Chat keys are derived from account keys and stored on the devices.",
|
||||
"rotation": "After key rotation, some messages may require the keys to be received again.",
|
||||
"source": "Before sending, make sure you are communicating with the intended user and server.",
|
||||
"warning_label": "Important:",
|
||||
"warning": "never share private keys or your account password with anyone.",
|
||||
"recovery": "Access recovery depends on your saved keys and password. Keep them secure."
|
||||
"zero_knowledge_label": "Zero-Knowledge Architecture:",
|
||||
"zero_knowledge": "We don't trust servers. SHiNE does not store your private keys and has no technical access to chat content.",
|
||||
"self_custody_label": "Self-Custody & Open Source:",
|
||||
"self_custody": "Your key is generated locally from your login and password. No hidden algorithms — the code is fully open.",
|
||||
"control_label": "Absolute Control:",
|
||||
"control": "Forget your password and you lose access to your messages forever."
|
||||
},
|
||||
"voice": {
|
||||
"hold_tip": "Hold to record",
|
||||
"lock_tip": "Swipe up to keep recording hands-free",
|
||||
"slide_cancel": "Slide to cancel",
|
||||
"delete": "Delete recording",
|
||||
"pause": "Pause recording",
|
||||
"resume": "Resume recording",
|
||||
"pause_playback": "Pause voice message"
|
||||
},
|
||||
"file_remove": "Remove file {value1}",
|
||||
"text_002": "Muted",
|
||||
"text_015": "Search",
|
||||
"text_020": "Clear history",
|
||||
@@ -2337,7 +2345,6 @@
|
||||
"text_041": "Could not play voice message",
|
||||
"text_034": "Encrypted data uploaded, but the key-sharing direct message was not sent.",
|
||||
"text_037": "Could not load direct-message history",
|
||||
"text_051": "Voicemailed",
|
||||
"text_052": "No voice mail",
|
||||
"text_045": "Added to contacts",
|
||||
"text_046": "Could not add to contacts",
|
||||
@@ -2408,7 +2415,6 @@
|
||||
"text_110": "Delete",
|
||||
"text_117": "File",
|
||||
"text_118": "File",
|
||||
"text_119": "↑ swipe up to secure",
|
||||
"text_120": "Message",
|
||||
"text_123": "Record Voice Message",
|
||||
"text_124": "Record Voice Message",
|
||||
@@ -4348,9 +4354,10 @@
|
||||
"support_phase2": {
|
||||
"statistics": "Support",
|
||||
"loading": "Loading support totals…",
|
||||
"sent": "❤️ Supported others",
|
||||
"received": "💚 Support received",
|
||||
"shine": "✨ Supported SHiNE",
|
||||
"sent": "Supported others",
|
||||
"received": "Support received",
|
||||
"shine": "Supported SHiNE",
|
||||
"summary": "Support: supported others {sent}, received {received}, supported SHiNE {shine}",
|
||||
"unavailable": "Totals unavailable (Free account or Solana error)",
|
||||
"donate_shine": "✨ Support SHiNE",
|
||||
"donate": "Donate",
|
||||
|
||||
@@ -472,10 +472,8 @@
|
||||
"label_030": "Остановить и отправить голосовое",
|
||||
"label_031": "Шифрование и отправка голосового",
|
||||
"label_032": "Записать голосовое сообщение",
|
||||
"label_033": "↑ проведите вверх, чтобы закрепить",
|
||||
"label_034": "Шифрование и загрузка файлов",
|
||||
"label_035": "Файл",
|
||||
"label_036": "Запись закреплена · нажмите ■, чтобы отправить",
|
||||
"add_user_prefix": "Добавить пользователя ",
|
||||
"add_user_suffix": " в контакты?"
|
||||
},
|
||||
@@ -1023,7 +1021,9 @@
|
||||
"text_005": "Файл скачан",
|
||||
"text_006": "файл",
|
||||
"text_007": "Скачать {value1}",
|
||||
"file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней."
|
||||
"file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней.",
|
||||
"remaining_less_day": "Вложение доступно ещё менее дня",
|
||||
"remaining_days": "Вложение доступно ещё {value1} дн."
|
||||
},
|
||||
"palette_editor": {
|
||||
"text_001": "Не удалось прочитать палитру: проверьте, что текст скопирован целиком.",
|
||||
@@ -2424,15 +2424,23 @@
|
||||
"chat_view": {
|
||||
"security_notice": {
|
||||
"title": "Ваша переписка защищена сквозным шифрованием",
|
||||
"encryption": "Все личные сообщения шифруются с использованием современных криптографических алгоритмов. Ключи шифрования хранятся ТОЛЬКО на устройствах участников переписки.",
|
||||
"servers": "Сервера SHiNE не имеют ваших приватных ключей и даже технически никак не могут прочитать ваши сообщения.",
|
||||
"derivation": "Ваш ключ шифрования высчитывается из вашего логина и пароля",
|
||||
"rotation": "При смене пароля перекодирование всех ваших сообщений со старого пароля на новый происходит на устройстве пользователя.",
|
||||
"source": "Код наших приложений полностью открыт и вы легко можете проверить всё это сами.",
|
||||
"warning_label": "Важно:",
|
||||
"warning": "если вы забудете свой пароль, восстановить доступ к вашей зашифрованной переписке будет невозможно.",
|
||||
"recovery": "SHiNE не хранит ваши секретные ключи и никак не сможет помочь вам восстановить вашу переписку"
|
||||
"zero_knowledge_label": "Zero-Knowledge Architecture:",
|
||||
"zero_knowledge": "Мы не доверяем серверам. SHiNE не хранит ваши приватные ключи и технически не имеет доступа к содержимому чатов.",
|
||||
"self_custody_label": "Self-Custody & Open Source:",
|
||||
"self_custody": "Ваш ключ генерируется локально из вашего логина и пароля. Никаких скрытых алгоритмов — код полностью открыт.",
|
||||
"control_label": "Absolute Control:",
|
||||
"control": "Забудете пароль — навсегда потеряете доступ к переписке."
|
||||
},
|
||||
"voice": {
|
||||
"hold_tip": "Удерживайте, чтобы записать",
|
||||
"lock_tip": "Проведите вверх — запись закрепится",
|
||||
"slide_cancel": "Влево — отмена",
|
||||
"delete": "Удалить запись",
|
||||
"pause": "Приостановить запись",
|
||||
"resume": "Продолжить запись",
|
||||
"pause_playback": "Приостановить голосовое сообщение"
|
||||
},
|
||||
"file_remove": "Убрать файл {value1}",
|
||||
"text_001": "Чат",
|
||||
"text_002": "Без звука",
|
||||
"text_003": "Показать связи",
|
||||
@@ -2483,7 +2491,6 @@
|
||||
"text_048": "Сначала завершите редактирование сообщения.",
|
||||
"text_049": "Этот браузер не поддерживает запись голосовых сообщений.",
|
||||
"text_050": "Запись с микрофона прервалась",
|
||||
"text_051": "Голосовое отправлено",
|
||||
"text_052": "Голосовое не отправлено",
|
||||
"text_053": "Не удалось начать запись",
|
||||
"text_054": "Передача файлов отключена в дополнительных настройках.",
|
||||
@@ -2551,7 +2558,6 @@
|
||||
"text_116": "Камера",
|
||||
"text_117": "Файл",
|
||||
"text_118": "Файл",
|
||||
"text_119": "↑ проведите вверх, чтобы закрепить",
|
||||
"text_120": "Сообщение",
|
||||
"text_121": "Эмодзи",
|
||||
"text_122": "Эмодзи",
|
||||
@@ -4348,9 +4354,10 @@
|
||||
"support_phase2": {
|
||||
"statistics": "Поддержка",
|
||||
"loading": "Загрузка статистики…",
|
||||
"sent": "❤️ Поддержал других",
|
||||
"received": "💚 Получил поддержку",
|
||||
"shine": "✨ Поддержал SHiNE",
|
||||
"sent": "Поддержал других",
|
||||
"received": "Получил поддержку",
|
||||
"shine": "Поддержал SHiNE",
|
||||
"summary": "Поддержка: поддержал других {sent}, получил поддержку {received}, поддержал SHiNE {shine}",
|
||||
"unavailable": "Статистика недоступна (Free или ошибка Solana)",
|
||||
"donate_shine": "✨ Поддержать SHiNE",
|
||||
"donate": "Пожертвовать",
|
||||
|
||||
+189
-382
@@ -38,13 +38,12 @@ import { dayKey, formatClockTime, formatDayLabel, showToast } from '../services/
|
||||
import { buildDmFileTechBlock, buildDmReplyTechBlock, parseDmTechBlocks, sanitizeUserDmTextForSend } from '../services/dm-tech-blocks.js';
|
||||
import { isDmFileTransferEnabled } from '../services/feature-settings.js';
|
||||
import {
|
||||
decryptDmFileToBlob,
|
||||
encryptAndUploadDmFile,
|
||||
DM_MAX_ATTACHMENTS_PER_MESSAGE,
|
||||
} from '../services/dm-file-service.js';
|
||||
import { createAttachmentCarouselElement } from '../services/attachment-format.js';
|
||||
import { createDmFileAttachmentCard, createDmExpiredAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js';
|
||||
import { isDmFileExpired } from '../services/dm-file-service.js';
|
||||
import { DM_FILE_RETENTION_MS, isDmFileExpired } from '../services/dm-file-service.js';
|
||||
import {
|
||||
DM_HISTORY_PAGE_SIZE,
|
||||
isDmHistoryFullyLoaded,
|
||||
@@ -57,6 +56,8 @@ import {
|
||||
import { DM_CHAT_PREFS_EVENT, isDmChatMuted, isDmChatPinned, setDmChatPinned } from '../services/dm-chat-prefs.js';
|
||||
import { createDmMuteMenuItem } from '../components/dm-mute-menu.js';
|
||||
import { actionErrorText, mediaAccessErrorText } from '../services/ui-error-texts.js';
|
||||
import { createDmVoiceAttachmentCard } from '../components/dm-voice-card.js';
|
||||
import { createDmVoiceRecorder } from '../components/dm-voice-recorder.js';
|
||||
import { scrollNodeIntoContainer } from '../services/scroll-utils.js';
|
||||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||||
import { makeProfileLinksRoute, makeProfileRoute } from '../services/shine-routes.js';
|
||||
@@ -1020,123 +1021,6 @@ function isTwemojiOnlyMessage(messageText) {
|
||||
}
|
||||
|
||||
|
||||
function formatVoiceDuration(durationMs = 0) {
|
||||
const total = Math.max(0, Math.round(Number(durationMs || 0) / 1000));
|
||||
const minutes = Math.floor(total / 60);
|
||||
const seconds = total % 60;
|
||||
return `${minutes}:${String(seconds).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function createDmVoiceAttachmentCard(attachment) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'dm-voice-card';
|
||||
|
||||
const playBtn = document.createElement('button');
|
||||
playBtn.type = 'button';
|
||||
playBtn.className = 'ui-button dm-voice-card__play';
|
||||
playBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_024'));
|
||||
playBtn.textContent = '▶';
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'dm-voice-card__body';
|
||||
const track = document.createElement('button');
|
||||
track.type = 'button';
|
||||
track.className = 'ui-button dm-voice-card__track';
|
||||
track.setAttribute('aria-label', t('dialogs.modals.chat_view.label_025'));
|
||||
const fill = document.createElement('span');
|
||||
fill.className = 'dm-voice-card__fill';
|
||||
track.append(fill);
|
||||
|
||||
const meta = document.createElement('div');
|
||||
meta.className = 'dm-voice-card__meta';
|
||||
const duration = document.createElement('span');
|
||||
duration.textContent = formatVoiceDuration(attachment?.durationMs || 0);
|
||||
const label = document.createElement('span');
|
||||
label.textContent = t('dialogs.modals.chat_view.label_026');
|
||||
meta.append(duration, label);
|
||||
body.append(track, meta);
|
||||
card.append(playBtn, body);
|
||||
|
||||
let audio = null;
|
||||
let objectUrl = '';
|
||||
let loading = false;
|
||||
|
||||
const syncProgress = () => {
|
||||
if (!audio) return;
|
||||
if (!card.isConnected) {
|
||||
try { audio.pause(); } catch { /* ignore */ }
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
objectUrl = '';
|
||||
}
|
||||
return;
|
||||
}
|
||||
const total = Number.isFinite(audio.duration) && audio.duration > 0
|
||||
? audio.duration
|
||||
: Math.max(0, Number(attachment?.durationMs || 0) / 1000);
|
||||
const current = Math.max(0, Number(audio.currentTime || 0));
|
||||
fill.style.width = `${total > 0 ? Math.min(100, (current / total) * 100) : 0}%`;
|
||||
duration.textContent = `${formatVoiceDuration(current * 1000)} / ${formatVoiceDuration(total * 1000)}`;
|
||||
playBtn.textContent = audio.paused ? '▶' : 'Ⅱ';
|
||||
};
|
||||
|
||||
const ensureAudio = async () => {
|
||||
if (audio) return audio;
|
||||
if (loading) return null;
|
||||
loading = true;
|
||||
playBtn.disabled = true;
|
||||
playBtn.textContent = '…';
|
||||
try {
|
||||
const blob = await decryptDmFileToBlob(attachment);
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
audio = new Audio(objectUrl);
|
||||
audio.preload = 'metadata';
|
||||
audio.addEventListener('timeupdate', syncProgress);
|
||||
audio.addEventListener('loadedmetadata', syncProgress);
|
||||
audio.addEventListener('play', syncProgress);
|
||||
audio.addEventListener('pause', syncProgress);
|
||||
audio.addEventListener('ended', syncProgress);
|
||||
audio.addEventListener('error', () => {
|
||||
showToast(t('screens.chat_view.text_041'), { kind: 'error', timeoutMs: 2200 });
|
||||
});
|
||||
return audio;
|
||||
} finally {
|
||||
loading = false;
|
||||
playBtn.disabled = false;
|
||||
if (!audio) playBtn.textContent = '▶';
|
||||
}
|
||||
};
|
||||
|
||||
playBtn.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
try {
|
||||
const player = await ensureAudio();
|
||||
if (!player) return;
|
||||
if (player.paused) await player.play();
|
||||
else player.pause();
|
||||
syncProgress();
|
||||
} catch (error) {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_042'), error), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
track.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
try {
|
||||
const player = await ensureAudio();
|
||||
if (!player || !Number.isFinite(player.duration) || player.duration <= 0) return;
|
||||
const rect = track.getBoundingClientRect();
|
||||
const ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / Math.max(1, rect.width)));
|
||||
player.currentTime = player.duration * ratio;
|
||||
syncProgress();
|
||||
} catch (error) {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_043'), error), { kind: 'error' });
|
||||
}
|
||||
});
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
function scrollToLatestMessageSmart(list, { smoothIfNearBottom = false } = {}) {
|
||||
if (!list) return;
|
||||
const scrollContainer = findChatScrollContainer(list);
|
||||
@@ -1186,27 +1070,17 @@ function createDmEncryptionNotice() {
|
||||
heading.textContent = `🔒 ${t('screens.chat_view.security_notice.title')}`;
|
||||
notice.append(heading);
|
||||
|
||||
for (const text of [
|
||||
t('screens.chat_view.security_notice.encryption'),
|
||||
t('screens.chat_view.security_notice.servers'),
|
||||
t('screens.chat_view.security_notice.derivation'),
|
||||
t('screens.chat_view.security_notice.rotation'),
|
||||
t('screens.chat_view.security_notice.source'),
|
||||
for (const [label, text] of [
|
||||
[t('screens.chat_view.security_notice.zero_knowledge_label'), t('screens.chat_view.security_notice.zero_knowledge')],
|
||||
[t('screens.chat_view.security_notice.self_custody_label'), t('screens.chat_view.security_notice.self_custody')],
|
||||
[t('screens.chat_view.security_notice.control_label'), t('screens.chat_view.security_notice.control')],
|
||||
]) {
|
||||
const paragraph = document.createElement('p');
|
||||
paragraph.textContent = text;
|
||||
const strong = document.createElement('strong');
|
||||
strong.textContent = `${label} `;
|
||||
paragraph.append(strong, document.createTextNode(text));
|
||||
notice.append(paragraph);
|
||||
}
|
||||
|
||||
const warning = document.createElement('p');
|
||||
const warningLabel = document.createElement('strong');
|
||||
warningLabel.textContent = `${t('screens.chat_view.security_notice.warning_label')} `;
|
||||
warning.append(warningLabel, document.createTextNode(t('screens.chat_view.security_notice.warning')));
|
||||
notice.append(warning);
|
||||
|
||||
const recovery = document.createElement('p');
|
||||
recovery.textContent = t('screens.chat_view.security_notice.recovery');
|
||||
notice.append(recovery);
|
||||
return notice;
|
||||
}
|
||||
|
||||
@@ -1331,6 +1205,23 @@ function renderLog(
|
||||
);
|
||||
}
|
||||
bubble.append(attachmentsWrap);
|
||||
// Вложения DM v3 живут 14 дней: показываем остаток, пока срок не вышел.
|
||||
// Истёкшие и так отрисованы карточкой «файл больше недоступен».
|
||||
const expiresAt = dmAttachments
|
||||
.filter((item) => Number(item?.version || 1) >= 3)
|
||||
.map((item) => Number(item.uploadedAtMs || item.messageTimestampMs || 0))
|
||||
.filter((uploadedAt) => uploadedAt > 0)
|
||||
.map((uploadedAt) => uploadedAt + DM_FILE_RETENTION_MS);
|
||||
const remaining = expiresAt.length ? Math.min(...expiresAt) - Date.now() : 0;
|
||||
if (remaining > 0) {
|
||||
const dayMs = 24 * 60 * 60 * 1000;
|
||||
const expiry = document.createElement('div');
|
||||
expiry.className = 'dm-attachment-expiry';
|
||||
expiry.textContent = remaining < dayMs
|
||||
? t('screens.dm_attachments.remaining_less_day')
|
||||
: t('screens.dm_attachments.remaining_days', { value1: Math.ceil(remaining / dayMs) });
|
||||
bubble.append(expiry);
|
||||
}
|
||||
}
|
||||
|
||||
const textNode = document.createElement('div');
|
||||
@@ -1931,17 +1822,14 @@ export function render({ navigate, route, chrome }) {
|
||||
<button class="ghost-btn dm-edit-banner__close" type="button" id="chat-edit-cancel" title="${th('screens.chat_view.text_112')}">✕</button>
|
||||
</div>
|
||||
<div class="emoji-picker-slot" id="chat-emoji-picker-slot" hidden></div>
|
||||
<!-- Выбранные файлы ждут здесь: можно убрать лишний и дописать подпись, отправка – одним сообщением. -->
|
||||
<div class="dm-file-queue" id="chat-file-queue" hidden></div>
|
||||
<!-- Капсула как строка ответа в обсуждениях. В покое – один ряд: фото · текст · смайлик · отправка.
|
||||
При вводе текст занимает весь верхний ряд, а все кнопки – нижний (как в терминале Claude). -->
|
||||
<div class="dm-composer-bar">
|
||||
<button class="dm-bar-icon dm-media-btn" type="button" id="chat-media-toggle" aria-label="${th('screens.chat_view.text_113')}" title="${th('screens.chat_view.text_114')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('image')}</button>
|
||||
<button class="dm-bar-icon dm-camera-btn" type="button" id="chat-camera-toggle" aria-label="${th('screens.chat_view.text_115')}" title="${th('screens.chat_view.text_116')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('camera')}</button>
|
||||
<button class="dm-bar-icon dm-file-btn" type="button" id="chat-file-toggle" aria-label="${th('screens.chat_view.text_117')}" title="${th('screens.chat_view.text_118')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('clip')}</button>
|
||||
<div class="dm-voice-recording-status" id="chat-voice-recording-status" hidden>
|
||||
<span class="dm-voice-recording-dot" aria-hidden="true"></span>
|
||||
<span class="dm-voice-recording-time" id="chat-voice-recording-time">0:00</span>
|
||||
<span class="dm-voice-recording-hint" id="chat-voice-recording-hint">${th('screens.chat_view.text_119')}</span>
|
||||
</div>
|
||||
<div class="dm-field">
|
||||
<textarea class="input dm-input" name="message" rows="1" placeholder="${th('screens.chat_view.text_120')}" maxlength="12000" enterkeyhint="enter"></textarea>
|
||||
</div>
|
||||
@@ -1971,6 +1859,7 @@ export function render({ navigate, route, chrome }) {
|
||||
const emojiToggle = form.querySelector('#chat-emoji-toggle');
|
||||
const fileToggle = form.querySelector('#chat-file-toggle');
|
||||
const fileInput = form.querySelector('#chat-file-input');
|
||||
const fileQueue = form.querySelector('#chat-file-queue');
|
||||
// Три входа для вложений: галерея (фото/видео), камера и любой файл – дальше путь один.
|
||||
const attachSources = [
|
||||
[fileToggle, fileInput],
|
||||
@@ -1979,9 +1868,6 @@ export function render({ navigate, route, chrome }) {
|
||||
];
|
||||
const attachButtons = attachSources.map(([button]) => button).filter(Boolean);
|
||||
const sendBtn = form.querySelector('.dm-send-btn');
|
||||
const voiceStatus = form.querySelector('#chat-voice-recording-status');
|
||||
const voiceTime = form.querySelector('#chat-voice-recording-time');
|
||||
const voiceHint = form.querySelector('#chat-voice-recording-hint');
|
||||
const fileTransferEnabled = isDmFileTransferEnabled();
|
||||
const editBanner = form.querySelector('#chat-edit-banner');
|
||||
const editBannerText = form.querySelector('#chat-edit-banner-text');
|
||||
@@ -1994,18 +1880,11 @@ export function render({ navigate, route, chrome }) {
|
||||
let emojiLongPressTimer = null;
|
||||
let emojiLongPressTriggered = false;
|
||||
let fileActionVisible = false;
|
||||
let voiceRecorder = null;
|
||||
let voiceStream = null;
|
||||
let voiceChunks = [];
|
||||
let voiceStartedAt = 0;
|
||||
let voiceTimer = null;
|
||||
let voiceLocked = false;
|
||||
let voicePointerHeld = false;
|
||||
let voiceReleaseRequested = false;
|
||||
let voiceStartY = 0;
|
||||
let voicePointerId = null;
|
||||
let voiceBusy = false;
|
||||
// Создаётся ниже, когда готовы обработчики страницы; до этого кнопка — обычный микрофон.
|
||||
let voice = null;
|
||||
let suppressVoiceClick = false;
|
||||
let queuedFiles = [];
|
||||
let fileSending = false;
|
||||
|
||||
let historyLoaderTimer = 0;
|
||||
const setHistoryLoadingState = (isLoading) => {
|
||||
@@ -2028,8 +1907,8 @@ export function render({ navigate, route, chrome }) {
|
||||
let composerPressing = false;
|
||||
const syncComposerLayout = () => {
|
||||
if (!input) return;
|
||||
const expanded = inputFocused || composerPressing || emojiPickerOpen || Boolean(activeEdit)
|
||||
|| Boolean(String(input.value || '').trim());
|
||||
const expanded = !voice?.isRecording() && (inputFocused || composerPressing || emojiPickerOpen
|
||||
|| Boolean(activeEdit) || Boolean(String(input.value || '').trim()));
|
||||
if (expanded === form.classList.contains('dm-chat-input--expanded')) return;
|
||||
form.classList.toggle('dm-chat-input--expanded', expanded);
|
||||
autoResizeComposer(input);
|
||||
@@ -2074,58 +1953,35 @@ export function render({ navigate, route, chrome }) {
|
||||
|
||||
|
||||
const sendIconMarkup = (mode) => {
|
||||
if (mode === 'send') {
|
||||
if (mode === 'send' || mode === 'voice-send') {
|
||||
return iconHtml('send');
|
||||
}
|
||||
if (mode === 'stop') {
|
||||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor"/></svg>';
|
||||
}
|
||||
if (mode === 'busy') {
|
||||
return '<span class="dm-send-busy-dot">…</span>';
|
||||
}
|
||||
return iconHtml('mic');
|
||||
};
|
||||
|
||||
const currentVoiceDurationMs = () => voiceStartedAt > 0 ? Math.max(0, Date.now() - voiceStartedAt) : 0;
|
||||
|
||||
const syncVoiceTimer = () => {
|
||||
if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs());
|
||||
};
|
||||
|
||||
const clearVoiceTimer = () => {
|
||||
if (voiceTimer != null) {
|
||||
window.clearInterval(voiceTimer);
|
||||
voiceTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const stopVoiceStreamTracks = () => {
|
||||
try {
|
||||
voiceStream?.getTracks?.().forEach((track) => track.stop());
|
||||
} catch {
|
||||
// ignore microphone cleanup failures
|
||||
}
|
||||
voiceStream = null;
|
||||
};
|
||||
|
||||
const updateSendButtonMode = () => {
|
||||
if (!sendBtn) return;
|
||||
const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive');
|
||||
const voiceState = voice?.state || 'idle';
|
||||
const recording = Boolean(voice?.isRecording());
|
||||
let mode = 'voice';
|
||||
if (voiceBusy) mode = 'busy';
|
||||
else if (recording && voiceLocked) mode = 'stop';
|
||||
else if (recording) mode = 'voice';
|
||||
else if (activeEdit || shared || String(input?.value || '').trim()) mode = 'send';
|
||||
if (voiceState === 'busy' || fileSending) mode = 'busy';
|
||||
else if (voiceState === 'locked' || voiceState === 'paused') mode = 'voice-send';
|
||||
else if (voiceState !== 'idle') mode = 'voice';
|
||||
else if (activeEdit || shared || queuedFiles.length || String(input?.value || '').trim()) mode = 'send';
|
||||
|
||||
sendBtn.dataset.mode = mode;
|
||||
sendBtn.innerHTML = sendIconMarkup(mode);
|
||||
sendBtn.classList.toggle('is-holding', voiceState === 'starting' || voiceState === 'holding');
|
||||
sendBtn.classList.toggle('is-recording', recording);
|
||||
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
|
||||
sendBtn.disabled = isShareSending() || voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
|
||||
sendBtn.disabled = isShareSending() || mode === 'busy' || voiceState === 'cancelling'
|
||||
|| (mode === 'voice' && voiceState === 'idle' && !fileTransferEnabled);
|
||||
if (mode === 'send') {
|
||||
sendBtn.title = t('screens.chat_view.text_029');
|
||||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029'));
|
||||
} else if (mode === 'stop') {
|
||||
} else if (mode === 'voice-send') {
|
||||
sendBtn.title = t('screens.chat_view.text_030');
|
||||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030'));
|
||||
} else if (mode === 'busy') {
|
||||
@@ -2136,149 +1992,62 @@ export function render({ navigate, route, chrome }) {
|
||||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_032'));
|
||||
}
|
||||
form.classList.toggle('dm-chat-input--recording', recording);
|
||||
if (voiceStatus) voiceStatus.hidden = !recording;
|
||||
if (input) input.hidden = recording;
|
||||
if (emojiToggle) emojiToggle.hidden = recording;
|
||||
attachButtons.forEach((button) => { button.hidden = recording || !fileTransferEnabled; });
|
||||
if (!recording && voiceHint) voiceHint.textContent = t('dialogs.modals.chat_view.label_033');
|
||||
syncVoiceTimer();
|
||||
};
|
||||
|
||||
const selectVoiceMimeType = () => {
|
||||
const candidates = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/ogg;codecs=opus',
|
||||
'audio/mp4',
|
||||
'audio/webm',
|
||||
];
|
||||
return candidates.find((mime) => globalThis.MediaRecorder?.isTypeSupported?.(mime)) || '';
|
||||
};
|
||||
|
||||
const voiceExtension = (mime = '') => {
|
||||
const value = String(mime || '').toLowerCase();
|
||||
if (value.includes('ogg')) return 'ogg';
|
||||
if (value.includes('mp4') || value.includes('m4a')) return 'm4a';
|
||||
return 'webm';
|
||||
};
|
||||
|
||||
const stopVoiceRecording = ({ send = true } = {}) => {
|
||||
voicePointerHeld = false;
|
||||
voiceReleaseRequested = true;
|
||||
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
|
||||
voiceRecorder.__shineShouldSend = Boolean(send);
|
||||
try {
|
||||
voiceRecorder.stop();
|
||||
} catch {
|
||||
stopVoiceStreamTracks();
|
||||
}
|
||||
};
|
||||
|
||||
const startVoiceRecording = async ({ pointerY = 0, pointerId = null } = {}) => {
|
||||
if (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
|
||||
if (!fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
|
||||
return;
|
||||
}
|
||||
if (activeEdit) {
|
||||
showToast(t('screens.chat_view.text_048'), { kind: 'error', timeoutMs: 1600 });
|
||||
return;
|
||||
}
|
||||
if (!globalThis.MediaRecorder || !navigator.mediaDevices?.getUserMedia) {
|
||||
showToast(t('screens.chat_view.text_049'), { kind: 'error', timeoutMs: 2400 });
|
||||
return;
|
||||
}
|
||||
|
||||
voicePointerHeld = true;
|
||||
voiceReleaseRequested = false;
|
||||
voiceLocked = false;
|
||||
voiceStartY = Number(pointerY || 0);
|
||||
voicePointerId = pointerId;
|
||||
suppressVoiceClick = false;
|
||||
|
||||
try {
|
||||
closeEmojiPicker();
|
||||
setFileActionVisible(false);
|
||||
voiceStream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
},
|
||||
video: false,
|
||||
});
|
||||
const mimeType = selectVoiceMimeType();
|
||||
const recorder = mimeType
|
||||
? new MediaRecorder(voiceStream, { mimeType })
|
||||
: new MediaRecorder(voiceStream);
|
||||
voiceRecorder = recorder;
|
||||
voiceChunks = [];
|
||||
recorder.__shineShouldSend = true;
|
||||
recorder.addEventListener('dataavailable', (event) => {
|
||||
if (event.data?.size > 0) voiceChunks.push(event.data);
|
||||
});
|
||||
recorder.addEventListener('error', (event) => {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
|
||||
});
|
||||
recorder.addEventListener('stop', async () => {
|
||||
const shouldSend = recorder.__shineShouldSend !== false;
|
||||
const durationMs = currentVoiceDurationMs();
|
||||
const chunks = voiceChunks.slice();
|
||||
voiceChunks = [];
|
||||
voiceRecorder = null;
|
||||
voiceLocked = false;
|
||||
voiceStartedAt = 0;
|
||||
clearVoiceTimer();
|
||||
stopVoiceStreamTracks();
|
||||
voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0);
|
||||
updateSendButtonMode();
|
||||
|
||||
if (!voiceBusy) return;
|
||||
try {
|
||||
const mime = String(recorder.mimeType || mimeType || chunks[0]?.type || 'audio/webm');
|
||||
const blob = new Blob(chunks, { type: mime });
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
const file = new File([blob], `voice-${timestamp}.${voiceExtension(mime)}`, { type: mime, lastModified: Date.now() });
|
||||
const attachment = await encryptAndUploadDmFile({
|
||||
file,
|
||||
login: state.session.login,
|
||||
sessionId: state.session.sessionId,
|
||||
wsUrl: authService.serverUrl,
|
||||
kind: 'voice',
|
||||
durationMs,
|
||||
onProgress: ({ processedBytes, totalBytes }) => {
|
||||
if (!totalBytes) return;
|
||||
const percent = Math.round((processedBytes / totalBytes) * 100);
|
||||
if (voiceHint) voiceHint.textContent = t('screens.chat_view.text_090', { value1: Math.min(100, percent) });
|
||||
},
|
||||
});
|
||||
await sendFileAttachmentMessage([attachment]);
|
||||
showToast(t('screens.chat_view.text_051'), { timeoutMs: 1200 });
|
||||
} catch (error) {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_052'), error), { kind: 'error' });
|
||||
} finally {
|
||||
voiceBusy = false;
|
||||
updateSendButtonMode();
|
||||
}
|
||||
}, { once: true });
|
||||
|
||||
voiceStartedAt = Date.now();
|
||||
recorder.start(1000);
|
||||
voiceTimer = window.setInterval(syncVoiceTimer, 250);
|
||||
// Микрофон, жесты, панель записи и эффект удаления принадлежат dm-voice-recorder.
|
||||
// Страница отвечает за свои запреты, вид кнопки и отправку готового файла.
|
||||
voice = createDmVoiceRecorder({
|
||||
form,
|
||||
bar: form.querySelector('.dm-composer-bar'),
|
||||
canStart: () => {
|
||||
if (!fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
|
||||
return false;
|
||||
}
|
||||
if (activeEdit) {
|
||||
showToast(t('screens.chat_view.text_048'), { kind: 'error', timeoutMs: 1600 });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
onStateChange: (voiceState) => {
|
||||
if (disposed) return;
|
||||
if (voiceState === 'starting') {
|
||||
closeEmojiPicker();
|
||||
setFileActionVisible(false);
|
||||
}
|
||||
updateSendButtonMode();
|
||||
if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
|
||||
} catch (error) {
|
||||
voicePointerHeld = false;
|
||||
voiceReleaseRequested = false;
|
||||
voiceLocked = false;
|
||||
voiceRecorder = null;
|
||||
voiceStartedAt = 0;
|
||||
clearVoiceTimer();
|
||||
stopVoiceStreamTracks();
|
||||
updateSendButtonMode();
|
||||
const mediaReason = mediaAccessErrorText(error);
|
||||
showToast(mediaReason ? t('screens.chat_view.text_091', { value1: mediaReason }) : actionErrorText(t('screens.chat_view.text_053'), error), { kind: 'error' });
|
||||
}
|
||||
};
|
||||
syncComposerLayout();
|
||||
},
|
||||
onRecorded: async ({ file, durationMs, waveform }) => {
|
||||
const attachment = await encryptAndUploadDmFile({
|
||||
file,
|
||||
login: state.session.login,
|
||||
sessionId: state.session.sessionId,
|
||||
wsUrl: authService.serverUrl,
|
||||
kind: 'voice',
|
||||
durationMs,
|
||||
});
|
||||
// Без тоста «отправлено»: появившийся пузырь в ленте и есть подтверждение.
|
||||
await sendFileAttachmentMessage([{ ...attachment, waveform }]);
|
||||
},
|
||||
onError: ({ kind, error }) => {
|
||||
if (disposed) return;
|
||||
if (kind === 'unsupported') {
|
||||
showToast(t('screens.chat_view.text_049'), { kind: 'error', timeoutMs: 2400 });
|
||||
} else if (kind === 'media') {
|
||||
const mediaReason = mediaAccessErrorText(error);
|
||||
showToast(mediaReason ? t('screens.chat_view.text_091', { value1: mediaReason }) : actionErrorText(t('screens.chat_view.text_053'), error), { kind: 'error' });
|
||||
} else if (kind === 'recorder') {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_050'), error), { kind: 'error' });
|
||||
} else {
|
||||
showToast(actionErrorText(t('screens.chat_view.text_052'), error), { kind: 'error' });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// На сенсорных устройствах фокус в textarea поднимает клавиатуру поверх пикера —
|
||||
// поэтому при вставке эмодзи фокусируем поле только там, где есть «точный» указатель.
|
||||
@@ -2664,7 +2433,7 @@ export function render({ navigate, route, chrome }) {
|
||||
};
|
||||
|
||||
// Файлы уже лежат на сервере – повторить можно одно сообщение с ключами, без новой загрузки.
|
||||
const offerAttachmentsRetry = (attachments, error) => {
|
||||
const offerAttachmentsRetry = (attachments, error, caption = '') => {
|
||||
showToast(actionErrorText(attachments.length === 1 ? t('screens.chat_view.text_075') : t('screens.chat_view.text_076'), error), {
|
||||
kind: 'error',
|
||||
action: {
|
||||
@@ -2672,10 +2441,10 @@ export function render({ navigate, route, chrome }) {
|
||||
onClick: async () => {
|
||||
if (disposed) return;
|
||||
try {
|
||||
await sendFileAttachmentMessage(attachments);
|
||||
await sendFileAttachmentMessage(attachments, caption);
|
||||
if (!disposed) showToast(attachments.length === 1 ? t('screens.chat_view.text_077') : t('screens.chat_view.text_100', { value1: attachments.length }), { timeoutMs: 1300 });
|
||||
} catch (again) {
|
||||
if (!disposed) offerAttachmentsRetry(attachments, again);
|
||||
if (!disposed) offerAttachmentsRetry(attachments, again, caption);
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -2738,7 +2507,33 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectedFiles = async (fileList) => {
|
||||
// Очередь вложений у поля ввода: файлы копятся, лишний можно убрать, подпись берётся из поля.
|
||||
const renderQueuedFiles = () => {
|
||||
fileQueue.replaceChildren();
|
||||
fileQueue.hidden = !queuedFiles.length;
|
||||
queuedFiles.forEach((file, index) => {
|
||||
const fileName = String(file?.name || 'file');
|
||||
const chip = document.createElement('span');
|
||||
chip.className = 'dm-file-queue__chip';
|
||||
const name = document.createElement('span');
|
||||
name.textContent = fileName;
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.textContent = '✕';
|
||||
remove.disabled = fileSending;
|
||||
remove.setAttribute('aria-label', t('screens.chat_view.file_remove', { value1: fileName }));
|
||||
remove.addEventListener('click', () => {
|
||||
if (fileSending) return;
|
||||
queuedFiles.splice(index, 1);
|
||||
renderQueuedFiles();
|
||||
});
|
||||
chip.append(name, remove);
|
||||
fileQueue.append(chip);
|
||||
});
|
||||
updateSendButtonMode();
|
||||
};
|
||||
|
||||
const queueSelectedFiles = (files) => {
|
||||
if (shared) return;
|
||||
if (!fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
|
||||
@@ -2748,13 +2543,28 @@ export function render({ navigate, route, chrome }) {
|
||||
showToast(t('screens.chat_view.text_055'), { kind: 'error', timeoutMs: 1600 });
|
||||
return;
|
||||
}
|
||||
const allFiles = Array.from(fileList || []).filter(Boolean);
|
||||
if (!allFiles.length) return;
|
||||
if (allFiles.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
|
||||
if (queuedFiles.length + files.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
|
||||
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error', timeoutMs: 2200 });
|
||||
return;
|
||||
}
|
||||
queuedFiles.push(...files);
|
||||
renderQueuedFiles();
|
||||
};
|
||||
|
||||
const sendQueuedFiles = async () => {
|
||||
if (fileSending || !queuedFiles.length) return;
|
||||
if (!fileTransferEnabled) {
|
||||
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
|
||||
return;
|
||||
}
|
||||
if (activeEdit) {
|
||||
showToast(t('screens.chat_view.text_055'), { kind: 'error', timeoutMs: 1600 });
|
||||
return;
|
||||
}
|
||||
const allFiles = queuedFiles.slice();
|
||||
const caption = String(input?.value || '').trim();
|
||||
fileSending = true;
|
||||
renderQueuedFiles();
|
||||
attachButtons.forEach((button) => {
|
||||
button.disabled = true;
|
||||
button.classList.add('is-busy');
|
||||
@@ -2781,13 +2591,27 @@ export function render({ navigate, route, chrome }) {
|
||||
attachments.push(attachment);
|
||||
}
|
||||
uploaded = true;
|
||||
await sendFileAttachmentMessage(attachments);
|
||||
await sendFileAttachmentMessage(attachments, caption);
|
||||
queuedFiles = [];
|
||||
// Подпись ушла вместе с файлами; если её успели поменять во время загрузки — не трогаем.
|
||||
if (caption && String(input?.value || '').trim() === caption) {
|
||||
input.value = '';
|
||||
autoResizeComposer(input);
|
||||
syncComposerLayout();
|
||||
}
|
||||
setFileActionVisible(false);
|
||||
showToast(attachments.length === 1 ? t('screens.chat_view.text_078') : t('screens.chat_view.text_103', { value1: attachments.length }), { timeoutMs: 1300 });
|
||||
} catch (error) {
|
||||
if (uploaded) offerAttachmentsRetry(attachments, error);
|
||||
else showToast(actionErrorText(allFiles.length === 1 ? t('screens.chat_view.text_079') : t('screens.chat_view.text_080'), error), { kind: 'error' });
|
||||
if (uploaded) {
|
||||
// Файлы уже на сервере: повтор отправит то же сообщение без новой загрузки.
|
||||
queuedFiles = [];
|
||||
offerAttachmentsRetry(attachments, error, caption);
|
||||
} else {
|
||||
// Загрузка не удалась: очередь остаётся, повторить можно той же кнопкой «Отправить».
|
||||
showToast(actionErrorText(allFiles.length === 1 ? t('screens.chat_view.text_079') : t('screens.chat_view.text_080'), error), { kind: 'error' });
|
||||
}
|
||||
} finally {
|
||||
fileSending = false;
|
||||
attachButtons.forEach((button) => {
|
||||
button.disabled = false;
|
||||
button.classList.remove('is-busy');
|
||||
@@ -2796,7 +2620,7 @@ export function render({ navigate, route, chrome }) {
|
||||
fileToggle.title = t('screens.chat_view.text_036');
|
||||
fileToggle.setAttribute('aria-label', t('dialogs.modals.chat_view.label_035'));
|
||||
}
|
||||
attachSources.forEach(([, picker]) => { if (picker) picker.value = ''; });
|
||||
renderQueuedFiles();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3052,7 +2876,9 @@ export function render({ navigate, route, chrome }) {
|
||||
});
|
||||
picker?.addEventListener('change', () => {
|
||||
const files = Array.from(picker.files || []);
|
||||
if (files.length) void handleSelectedFiles(files);
|
||||
// Сброс сразу: тот же файл можно выбрать снова, если его убрали из очереди.
|
||||
picker.value = '';
|
||||
if (files.length) queueSelectedFiles(files);
|
||||
});
|
||||
});
|
||||
screen.addEventListener('pointerdown', (event) => {
|
||||
@@ -3075,47 +2901,22 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (mode === 'stop') {
|
||||
event.preventDefault();
|
||||
suppressVoiceClick = true;
|
||||
stopVoiceRecording({ send: true });
|
||||
event.preventDefault();
|
||||
// Жест указателем обработан здесь; следующий за ним click не должен сработать второй раз.
|
||||
suppressVoiceClick = true;
|
||||
if (mode === 'voice-send') {
|
||||
voice.send();
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
voicePointerHeld = true;
|
||||
voiceReleaseRequested = false;
|
||||
voiceStartY = Number(event.clientY || 0);
|
||||
voicePointerId = event.pointerId;
|
||||
try { sendBtn.setPointerCapture?.(event.pointerId); } catch { /* optional */ }
|
||||
void startVoiceRecording({ pointerY: voiceStartY, pointerId: event.pointerId });
|
||||
voice.press(event);
|
||||
});
|
||||
|
||||
sendBtn?.addEventListener('pointermove', (event) => {
|
||||
if (!voicePointerHeld || voiceLocked || voicePointerId !== event.pointerId) return;
|
||||
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
|
||||
if (Number(event.clientY || 0) <= voiceStartY - 64) {
|
||||
voiceLocked = true;
|
||||
voiceReleaseRequested = false;
|
||||
if (voiceHint) voiceHint.textContent = t('dialogs.modals.chat_view.label_036');
|
||||
updateSendButtonMode();
|
||||
try { navigator.vibrate?.(18); } catch { /* ignore */ }
|
||||
}
|
||||
sendBtn?.addEventListener('pointermove', (event) => voice.move(event));
|
||||
sendBtn?.addEventListener('pointerup', (event) => {
|
||||
try { sendBtn.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
|
||||
voice.release(event);
|
||||
});
|
||||
|
||||
const finishVoicePointerGesture = (event) => {
|
||||
if (!voicePointerHeld && voicePointerId == null) return;
|
||||
if (voicePointerId != null && event.pointerId !== voicePointerId) return;
|
||||
voicePointerHeld = false;
|
||||
voiceReleaseRequested = true;
|
||||
try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
|
||||
voicePointerId = null;
|
||||
if (!voiceLocked) {
|
||||
suppressVoiceClick = true;
|
||||
stopVoiceRecording({ send: true });
|
||||
}
|
||||
};
|
||||
sendBtn?.addEventListener('pointerup', finishVoicePointerGesture);
|
||||
sendBtn?.addEventListener('pointercancel', finishVoicePointerGesture);
|
||||
sendBtn?.addEventListener('pointercancel', (event) => voice.interrupt(event));
|
||||
sendBtn?.addEventListener('contextmenu', (event) => {
|
||||
if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault();
|
||||
});
|
||||
@@ -3128,8 +2929,11 @@ export function render({ navigate, route, chrome }) {
|
||||
const mode = String(sendBtn.dataset.mode || 'voice');
|
||||
if (mode === 'send') {
|
||||
form.requestSubmit();
|
||||
} else if (mode === 'stop') {
|
||||
stopVoiceRecording({ send: true });
|
||||
} else if (mode === 'voice-send') {
|
||||
voice.send();
|
||||
} else if (mode === 'voice') {
|
||||
// Enter/пробел дают click без pointerdown: удерживать нечего, запись сразу в замке.
|
||||
voice.startLocked();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3138,7 +2942,7 @@ export function render({ navigate, route, chrome }) {
|
||||
input.addEventListener('keydown', (event) => {
|
||||
if (!isDmSendEnter(event)) return;
|
||||
event.preventDefault();
|
||||
if (shared?.files.length || String(input.value || '').trim()) form.requestSubmit();
|
||||
if (shared?.files.length || queuedFiles.length || String(input.value || '').trim()) form.requestSubmit();
|
||||
});
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
@@ -3148,6 +2952,11 @@ export function render({ navigate, route, chrome }) {
|
||||
if (text || shared.files.length) await sendSharedDraft(text);
|
||||
return;
|
||||
}
|
||||
if (queuedFiles.length) {
|
||||
closeEmojiPicker();
|
||||
await sendQueuedFiles();
|
||||
return;
|
||||
}
|
||||
if (!text) return;
|
||||
input.value = '';
|
||||
autoResizeComposer(input);
|
||||
@@ -3225,9 +3034,7 @@ export function render({ navigate, route, chrome }) {
|
||||
hideUnreadSeparator({ rerender: false });
|
||||
stopAllTwemojiAnimations();
|
||||
clearEmojiLongPress();
|
||||
try { stopVoiceRecording({ send: false }); } catch { /* ignore */ }
|
||||
clearVoiceTimer();
|
||||
stopVoiceStreamTracks();
|
||||
voice?.destroy();
|
||||
window.removeEventListener('shine-chat-messages-updated', handleIncomingChatRefresh);
|
||||
window.removeEventListener('shine-dm-delivery-updated', handleDeliveryRefresh);
|
||||
window.removeEventListener(DM_CHAT_PREFS_EVENT, handleChatPrefsUpdated);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { t } from '../i18n/index.js';
|
||||
import { decodeWaveform } from '../components/dm-voice-waveform.js';
|
||||
function defaultParsed(rawText = '') {
|
||||
const text = String(rawText || '');
|
||||
return {
|
||||
@@ -134,6 +135,8 @@ function normalizeFileAttachment(fields = {}) {
|
||||
} : {}),
|
||||
kind,
|
||||
durationMs,
|
||||
// Волна голосового (wf) — недоверенный ввод собеседника: берём только валидную упаковку.
|
||||
waveform: kind === 'voice' && decodeWaveform(fields.wf) ? fields.wf : '',
|
||||
uploadedAtMs: Number(fields.at || 0) || 0,
|
||||
};
|
||||
}
|
||||
@@ -176,12 +179,14 @@ export function buildDmFileTechBlock(attachment = {}) {
|
||||
const piecesRoot = String(attachment?.torrentV2PiecesRootB64Url || '').trim();
|
||||
const kind = String(attachment?.kind || 'file') === 'voice' ? 'voice' : 'file';
|
||||
const durationMs = Math.max(0, Math.floor(Number(attachment?.durationMs || 0)));
|
||||
const waveform = String(attachment?.waveform || '');
|
||||
const waveformField = kind === 'voice' && decodeWaveform(waveform) ? `;wf=${waveform}` : '';
|
||||
const torrentFields = version === 2 ? `;th=${torrentHash};pr=${piecesRoot}` : '';
|
||||
// Новые DM v3: в E2EE передаём идентификаторы и ключи, а домен — через senderLogin.
|
||||
// URL ранее созданных v3 и legacy v2/v1 продолжаем читать без изменения.
|
||||
const urlField = version >= 3 ? '' : `;url=${encodedUrl}`;
|
||||
const uploadTime = version >= 3 ? `;at=${Math.max(0, Math.floor(Number(attachment?.uploadedAtMs || 0)))}` : '';
|
||||
return `<S:file;v=${version};id=${id}${urlField};key=${keyB64Url};ivp=${ivPrefix};name=${name};mime=${mime};size=${size};encsize=${encryptedSize};chunk=${chunkSize};chunks=${chunkCount}${torrentFields};kind=${kind};dur=${durationMs}${uploadTime}>`;
|
||||
return `<S:file;v=${version};id=${id}${urlField};key=${keyB64Url};ivp=${ivPrefix};name=${name};mime=${mime};size=${size};encsize=${encryptedSize};chunk=${chunkSize};chunks=${chunkCount}${torrentFields};kind=${kind};dur=${durationMs}${waveformField}${uploadTime}>`;
|
||||
}
|
||||
|
||||
const ivB64Url = String(attachment?.ivB64Url || '').trim();
|
||||
|
||||
@@ -28,9 +28,13 @@ export function parseStarCents(input) {
|
||||
if (cents < 10n || cents > 0xffff_ffff_ffff_ffffn) throw new Error('Минимальная поддержка — 0,10 ⭐');
|
||||
return cents;
|
||||
}
|
||||
export function formatStars(value) {
|
||||
/** Только число («0.10»): для вёрстки, где единица показана отдельной SVG-иконкой. */
|
||||
export function formatStarAmount(value) {
|
||||
const cents = BigInt(value);
|
||||
return `${cents / 100n}.${String(cents % 100n).padStart(2, '0')} ⭐`;
|
||||
return `${cents / 100n}.${String(cents % 100n).padStart(2, '0')}`;
|
||||
}
|
||||
export function formatStars(value) {
|
||||
return `${formatStarAmount(value)} ⭐`;
|
||||
}
|
||||
export function splitStarCents(value) {
|
||||
const cents = BigInt(value);
|
||||
|
||||
Reference in New Issue
Block a user