Слить PR #4: голосовые сообщения и карточка поддержки

This commit is contained in:
AidarKC
2026-12-01 22:29:58 +03:00
24 changed files with 2993 additions and 651 deletions
+189 -382
View File
@@ -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);