Улучшить вложения и запись голосовых в личной переписке

This commit is contained in:
AidarKC
2026-11-17 15:34:36 +03:00
parent 1f06629838
commit 2dd0ed6d59
9 changed files with 251 additions and 40 deletions
+154 -24
View File
@@ -1292,6 +1292,21 @@ function renderLog(
);
}
bubble.append(attachmentsWrap);
const expiresAt = dmAttachments
.filter((item) => Number(item?.version || 1) >= 3)
.map((item) => Number(item.uploadedAtMs || msg?.timeMs || 0) + 14 * 24 * 60 * 60 * 1000)
.filter((value) => value > 14 * 24 * 60 * 60 * 1000);
if (expiresAt.length) {
const remaining = Math.min(...expiresAt) - Date.now();
const expiry = document.createElement('div');
expiry.className = 'dm-attachment-expiry';
expiry.textContent = remaining <= 0
? t('screens.dm_attachments.file_expired_short')
: remaining < 24 * 60 * 60 * 1000
? t('screens.dm_attachments.remaining_less_day')
: t('screens.dm_attachments.remaining_days', { value1: Math.ceil(remaining / (24 * 60 * 60 * 1000)) });
bubble.append(expiry);
}
}
const textNode = document.createElement('div');
@@ -1897,9 +1912,11 @@ export function render({ navigate, route, chrome }) {
<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>
<button class="dm-voice-cancel" type="button" id="chat-voice-cancel" aria-label="${th('screens.chat_view.voice_cancel')}">✕</button>
<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>
<button class="dm-voice-pause" type="button" id="chat-voice-pause" hidden></button>
</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>
@@ -1907,6 +1924,7 @@ export function render({ navigate, route, chrome }) {
<button class="dm-bar-icon dm-emoji-btn" type="button" id="chat-emoji-toggle" aria-label="${th('screens.chat_view.text_121')}" title="${th('screens.chat_view.text_122')}">${iconHtml('emoji')}</button>
<button class="dm-send-btn dm-send-icon-btn" type="button" title="${th('screens.chat_view.text_123')}" data-mode="voice" aria-label="${th('screens.chat_view.text_124')}"></button>
</div>
<div class="dm-file-queue" id="chat-file-queue" hidden></div>
<input id="chat-file-input" type="file" multiple hidden />
<input id="chat-media-input" type="file" accept="image/*,video/*" multiple hidden />
<input id="chat-camera-input" type="file" accept="image/*,video/*" capture="environment" hidden />
@@ -1917,6 +1935,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],
@@ -1928,6 +1947,8 @@ export function render({ navigate, route, chrome }) {
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 voicePause = form.querySelector('#chat-voice-pause');
const voiceCancel = form.querySelector('#chat-voice-cancel');
const fileTransferEnabled = isDmFileTransferEnabled();
const editBanner = form.querySelector('#chat-edit-banner');
const editBannerText = form.querySelector('#chat-edit-banner-text');
@@ -1940,6 +1961,8 @@ export function render({ navigate, route, chrome }) {
let emojiLongPressTimer = null;
let emojiLongPressTriggered = false;
let fileActionVisible = false;
let queuedFiles = [];
let fileSending = false;
let voiceRecorder = null;
let voiceStream = null;
let voiceChunks = [];
@@ -1949,6 +1972,11 @@ export function render({ navigate, route, chrome }) {
let voicePointerHeld = false;
let voiceReleaseRequested = false;
let voiceStartY = 0;
let voiceStartX = 0;
let voicePressStartedAt = 0;
let voiceCancelRequested = false;
let voicePausedMs = 0;
let voicePausedAt = 0;
let voicePointerId = null;
let voiceBusy = false;
let suppressVoiceClick = false;
@@ -2024,7 +2052,7 @@ export function render({ navigate, route, chrome }) {
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>';
return iconHtml('send');
}
if (mode === 'busy') {
return '<span class="dm-send-busy-dot">…</span>';
@@ -2032,7 +2060,8 @@ export function render({ navigate, route, chrome }) {
return iconHtml('mic');
};
const currentVoiceDurationMs = () => voiceStartedAt > 0 ? Math.max(0, Date.now() - voiceStartedAt) : 0;
const currentVoiceDurationMs = () => voiceStartedAt > 0
? Math.max(0, (voicePausedAt || Date.now()) - voiceStartedAt - voicePausedMs) : 0;
const syncVoiceTimer = () => {
if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs());
@@ -2058,22 +2087,22 @@ export function render({ navigate, route, chrome }) {
if (!sendBtn) return;
const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive');
let mode = 'voice';
if (voiceBusy) mode = 'busy';
if (voiceBusy || fileSending) mode = 'busy';
else if (recording && voiceLocked) mode = 'stop';
else if (recording) mode = 'voice';
else if (activeEdit || String(input?.value || '').trim()) mode = 'send';
else if (activeEdit || queuedFiles.length || String(input?.value || '').trim()) mode = 'send';
sendBtn.dataset.mode = mode;
sendBtn.innerHTML = sendIconMarkup(mode);
sendBtn.classList.toggle('is-recording', recording);
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
sendBtn.disabled = voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
sendBtn.disabled = voiceBusy || fileSending || (mode === 'voice' && !recording && !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') {
sendBtn.title = t('screens.chat_view.text_030');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030'));
sendBtn.title = t('screens.chat_view.voice_send');
sendBtn.setAttribute('aria-label', t('screens.chat_view.voice_send'));
} else if (mode === 'busy') {
sendBtn.title = t('screens.chat_view.text_031');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_031'));
@@ -2083,6 +2112,13 @@ export function render({ navigate, route, chrome }) {
}
form.classList.toggle('dm-chat-input--recording', recording);
if (voiceStatus) voiceStatus.hidden = !recording;
if (voicePause) {
voicePause.hidden = !recording || !voiceLocked;
voicePause.textContent = voiceRecorder?.state === 'paused' ? '▶' : 'Ⅱ';
voicePause.setAttribute('aria-label', t(voiceRecorder?.state === 'paused' ? 'screens.chat_view.voice_resume' : 'screens.chat_view.voice_pause'));
}
form.classList.toggle('dm-chat-input--voice-locked', recording && voiceLocked);
form.classList.toggle('dm-chat-input--voice-paused', recording && voiceRecorder?.state === 'paused');
if (input) input.hidden = recording;
if (emojiToggle) emojiToggle.hidden = recording;
attachButtons.forEach((button) => { button.hidden = recording || !fileTransferEnabled; });
@@ -2110,7 +2146,10 @@ export function render({ navigate, route, chrome }) {
const stopVoiceRecording = ({ send = true } = {}) => {
voicePointerHeld = false;
voiceReleaseRequested = true;
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
if (!voiceRecorder || voiceRecorder.state === 'inactive') {
if (!send) voiceCancelRequested = true;
return;
}
voiceRecorder.__shineShouldSend = Boolean(send);
try {
voiceRecorder.stop();
@@ -2119,7 +2158,7 @@ export function render({ navigate, route, chrome }) {
}
};
const startVoiceRecording = async ({ pointerY = 0, pointerId = null } = {}) => {
const startVoiceRecording = async ({ pointerY = 0, pointerX = 0, pointerId = null } = {}) => {
if (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
@@ -2138,7 +2177,11 @@ export function render({ navigate, route, chrome }) {
voiceReleaseRequested = false;
voiceLocked = false;
voiceStartY = Number(pointerY || 0);
voiceStartX = Number(pointerX || 0);
voicePointerId = pointerId;
voiceCancelRequested = false;
voicePausedMs = 0;
voicePausedAt = 0;
suppressVoiceClick = false;
try {
@@ -2166,13 +2209,15 @@ export function render({ navigate, route, chrome }) {
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
});
recorder.addEventListener('stop', async () => {
const shouldSend = recorder.__shineShouldSend !== false;
const shouldSend = recorder.__shineShouldSend !== false && !voiceCancelRequested;
const durationMs = currentVoiceDurationMs();
const chunks = voiceChunks.slice();
voiceChunks = [];
voiceRecorder = null;
voiceLocked = false;
voiceStartedAt = 0;
voicePausedAt = 0;
voicePausedMs = 0;
clearVoiceTimer();
stopVoiceStreamTracks();
voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0);
@@ -2211,7 +2256,8 @@ export function render({ navigate, route, chrome }) {
recorder.start(1000);
voiceTimer = window.setInterval(syncVoiceTimer, 250);
updateSendButtonMode();
if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
if (voiceCancelRequested) stopVoiceRecording({ send: false });
else if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
} catch (error) {
voicePointerHeld = false;
voiceReleaseRequested = false;
@@ -2527,7 +2573,7 @@ export function render({ navigate, route, chrome }) {
}
};
const sendFileAttachmentMessage = async (attachmentsInput) => {
const sendFileAttachmentMessage = async (attachmentsInput, caption = '') => {
const attachments = (Array.isArray(attachmentsInput) ? attachmentsInput : [attachmentsInput]).filter(Boolean);
if (!attachments.length) return;
if (attachments.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
@@ -2542,7 +2588,7 @@ export function render({ navigate, route, chrome }) {
: (attachments.length === 1
? `📎 ${String(attachments[0]?.name || 'file')}`
: t('screens.chat_view.text_097', { value1: attachments.length }));
const finalText = `${replyBlock}${fileBlocks}${fallbackText}`;
const finalText = `${replyBlock}${fileBlocks}${String(caption || '').trim() || fallbackText}`;
hideUnreadSeparator({ rerender: false });
const tempId = addOutgoingPendingMessage(chatId, finalText);
@@ -2606,7 +2652,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: {
@@ -2614,17 +2660,40 @@ 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);
}
},
},
});
};
const renderQueuedFiles = () => {
fileQueue.replaceChildren();
fileQueue.hidden = !queuedFiles.length;
queuedFiles.forEach((file, index) => {
const chip = document.createElement('span');
chip.className = 'dm-file-queue__chip';
const name = document.createElement('span');
name.textContent = file.name;
const remove = document.createElement('button');
remove.type = 'button';
remove.textContent = '✕';
remove.setAttribute('aria-label', t('screens.chat_view.file_remove', { value1: file.name }));
remove.addEventListener('click', () => {
queuedFiles.splice(index, 1);
renderQueuedFiles();
});
chip.append(name, remove);
fileQueue.append(chip);
});
updateSendButtonMode();
};
const handleSelectedFiles = async (fileList) => {
if (fileSending) return;
if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
return;
@@ -2634,11 +2703,14 @@ export function render({ navigate, route, chrome }) {
return;
}
const allFiles = Array.from(fileList || []).filter(Boolean);
const caption = String(input?.value || '').trim();
if (!allFiles.length) return;
if (allFiles.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error', timeoutMs: 2200 });
return;
}
fileSending = true;
updateSendButtonMode();
attachButtons.forEach((button) => {
button.disabled = true;
@@ -2666,13 +2738,26 @@ export function render({ navigate, route, chrome }) {
attachments.push(attachment);
}
uploaded = true;
await sendFileAttachmentMessage(attachments);
await sendFileAttachmentMessage(attachments, caption);
queuedFiles = [];
renderQueuedFiles();
if (caption && String(input?.value || '').trim() === caption) {
input.value = '';
autoResizeComposer(input);
updateSendButtonMode();
}
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);
if (uploaded) {
queuedFiles = [];
renderQueuedFiles();
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;
updateSendButtonMode();
attachButtons.forEach((button) => {
button.disabled = false;
button.classList.remove('is-busy');
@@ -2920,7 +3005,14 @@ export function render({ navigate, route, chrome }) {
});
picker?.addEventListener('change', () => {
const files = Array.from(picker.files || []);
if (files.length) void handleSelectedFiles(files);
if (!files.length) return;
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' });
return;
}
queuedFiles.push(...files);
renderQueuedFiles();
picker.value = '';
});
});
screen.addEventListener('pointerdown', (event) => {
@@ -2953,14 +3045,21 @@ export function render({ navigate, route, chrome }) {
voicePointerHeld = true;
voiceReleaseRequested = false;
voiceStartY = Number(event.clientY || 0);
voicePressStartedAt = Date.now();
voicePointerId = event.pointerId;
try { sendBtn.setPointerCapture?.(event.pointerId); } catch { /* optional */ }
void startVoiceRecording({ pointerY: voiceStartY, pointerId: event.pointerId });
void startVoiceRecording({ pointerY: voiceStartY, pointerX: event.clientX, pointerId: event.pointerId });
});
sendBtn?.addEventListener('pointermove', (event) => {
if (!voicePointerHeld || voiceLocked || voicePointerId !== event.pointerId) return;
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
if (Number(event.clientX || 0) <= voiceStartX - 72) {
voiceCancelRequested = true;
suppressVoiceClick = true;
stopVoiceRecording({ send: false });
if (voiceHint) voiceHint.textContent = t('screens.chat_view.voice_cancelled');
return;
}
if (Number(event.clientY || 0) <= voiceStartY - 64) {
voiceLocked = true;
voiceReleaseRequested = false;
@@ -2977,13 +3076,40 @@ export function render({ navigate, route, chrome }) {
voiceReleaseRequested = true;
try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
voicePointerId = null;
if (!voiceLocked) {
if (!voiceLocked && !voiceCancelRequested && Date.now() - voicePressStartedAt < 350) {
voiceLocked = true;
voiceReleaseRequested = false;
if (voiceHint) voiceHint.textContent = t('screens.chat_view.voice_tap_hint');
updateSendButtonMode();
suppressVoiceClick = true;
stopVoiceRecording({ send: true });
} else if (!voiceLocked) {
suppressVoiceClick = true;
stopVoiceRecording({ send: !voiceCancelRequested });
}
};
sendBtn?.addEventListener('pointerup', finishVoicePointerGesture);
sendBtn?.addEventListener('pointercancel', finishVoicePointerGesture);
sendBtn?.addEventListener('pointercancel', (event) => {
if (voicePointerId !== event.pointerId) return;
voiceCancelRequested = true;
finishVoicePointerGesture(event);
stopVoiceRecording({ send: false });
});
voiceCancel?.addEventListener('click', () => {
voiceCancelRequested = true;
stopVoiceRecording({ send: false });
});
voicePause?.addEventListener('click', () => {
if (!voiceRecorder || !voiceLocked) return;
if (voiceRecorder.state === 'recording') {
voiceRecorder.pause();
voicePausedAt = Date.now();
} else if (voiceRecorder.state === 'paused') {
voicePausedMs += Date.now() - voicePausedAt;
voicePausedAt = 0;
voiceRecorder.resume();
}
updateSendButtonMode();
});
sendBtn?.addEventListener('contextmenu', (event) => {
if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault();
});
@@ -3012,6 +3138,10 @@ export function render({ navigate, route, chrome }) {
form.addEventListener('submit', async (event) => {
event.preventDefault();
const text = String(input.value || '').trim();
if (queuedFiles.length) {
await handleSelectedFiles(queuedFiles);
return;
}
if (!text) return;
input.value = '';
autoResizeComposer(input);