Files
SHiNE-server/shine-UI/js/components/dm-voice-card.js
T
PixelandClaude Opus 5.5 1c59b82ff7 Голосовые в личке: волна громкости, жесты записи, пауза и удаление
- Пузырь голосового показывает волну громкости с плавной закраской
  проигранной части; тап по волне перематывает (для webm без duration —
  по полю dur).
- Запись: удержание — запись, отпускание — отправка, влево — отмена с
  эффектом корзины (полоса рассыпается в пыльцу), вверх — замок с паузой,
  удалением и отправкой. Тап показывает подсказку, Enter/пробел сразу
  включают замок, Esc отменяет. Живая волна: столбик раз в 110 мс,
  плавный сдвиг и рост.
- Формат: необязательное поле wf у kind=voice (64 уровня по 5 бит,
  base64url), старые клиенты его игнорируют; получатель проверяет строку.
- Opus 32 кбит/с вместо ~170: файлы в 3–4 раза легче. Тост «Голосовое
  отправлено» убран — подтверждение даёт пузырь в ленте.
- app.js не перемонтирует текущий экран во время записи/отправки
  голосового: повторный рендер того же пути откладывается до конца записи.
- Код вынесен из chat-view.js в components/dm-voice-{recorder,card,waveform}.js,
  стили — в styles/features/dm-voice.css; старые стили записи удалены.
- Возвращены отмена и пауза, потерянные в 780ca539 (18.11).
- Документация: Personal_Messages/README.md, Технические_вставки_DM_v1.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:04:00 +03:00

190 lines
7.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Пузырь голосового в личной переписке: кнопка воспроизведения, волна громкости
// с плавной закраской проигранной части и перемотка тапом по волне.
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;
}