SHA256
Голосовые в личке: волна громкости, жесты записи, пауза и удаление
- Пузырь голосового показывает волну громкости с плавной закраской
проигранной части; тап по волне перематывает (для 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>
This commit is contained in:
+83
-350
@@ -38,7 +38,6 @@ 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';
|
||||
@@ -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);
|
||||
@@ -1937,11 +1821,6 @@ export function render({ navigate, route, chrome }) {
|
||||
<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>
|
||||
@@ -1979,9 +1858,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,17 +1870,8 @@ 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 historyLoaderTimer = 0;
|
||||
@@ -2028,8 +1895,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 +1941,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';
|
||||
if (voiceState === 'busy') mode = 'busy';
|
||||
else if (voiceState === 'locked' || voiceState === 'paused') mode = 'voice-send';
|
||||
else if (voiceState !== 'idle') mode = 'voice';
|
||||
else if (activeEdit || shared || 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 +1980,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 поднимает клавиатуру поверх пикера —
|
||||
// поэтому при вставке эмодзи фокусируем поле только там, где есть «точный» указатель.
|
||||
@@ -3075,47 +2832,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 +2860,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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3225,9 +2960,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);
|
||||
|
||||
Reference in New Issue
Block a user