Вернуть очередь файлов с подписью и срок хранения вложений в личке

Коммит 780ca539 (18.11) случайно удалил из chat-view.js функции из
2dd0ed6d (17.11). Возвращены поверх текущего main (подпись в
sendFileAttachmentMessage уже была добавлена вместе с «Поделиться»):

- выбранные файлы копятся в очереди над полем ввода, лишний убирается,
  текст поля уходит подписью, всё отправляется одним сообщением;
- если не удалась загрузка — очередь и подпись остаются для повтора;
  если файлы загружены, а DM не ушёл — повтор без новой загрузки;
- у вложений DM v3 строка «Вложение доступно ещё N дн.», пока срок
  не истёк (срок — из DM_FILE_RETENTION_MS);
- ключи file_remove, remaining_less_day, remaining_days (ru/en).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pixel
2026-11-29 19:07:21 +03:00
co-authored by Claude Opus 5.5
parent 1c59b82ff7
commit e7349c7bf4
5 changed files with 117 additions and 22 deletions
+100 -16
View File
@@ -43,7 +43,7 @@ import {
} 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,
@@ -1215,6 +1215,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');
@@ -1815,6 +1832,8 @@ 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">
@@ -1850,6 +1869,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],
@@ -1873,6 +1893,8 @@ export function render({ navigate, route, chrome }) {
// Создаётся ниже, когда готовы обработчики страницы; до этого кнопка — обычный микрофон.
let voice = null;
let suppressVoiceClick = false;
let queuedFiles = [];
let fileSending = false;
let historyLoaderTimer = 0;
const setHistoryLoadingState = (isLoading) => {
@@ -1955,10 +1977,10 @@ export function render({ navigate, route, chrome }) {
const voiceState = voice?.state || 'idle';
const recording = Boolean(voice?.isRecording());
let mode = 'voice';
if (voiceState === 'busy') mode = 'busy';
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 || String(input?.value || '').trim()) mode = 'send';
else if (activeEdit || shared || queuedFiles.length || String(input?.value || '').trim()) mode = 'send';
sendBtn.dataset.mode = mode;
sendBtn.innerHTML = sendIconMarkup(mode);
@@ -2421,7 +2443,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: {
@@ -2429,10 +2451,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);
}
},
},
@@ -2495,7 +2517,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 });
@@ -2505,13 +2553,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');
@@ -2538,13 +2601,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');
@@ -2553,7 +2630,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();
}
};
@@ -2809,7 +2886,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) => {
@@ -2873,7 +2952,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) => {
@@ -2883,6 +2962,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);