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

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
+1 -1
View File
@@ -1,2 +1,2 @@
client.version=1.20.56 client.version=1.20.57
server.version=1.16.29 server.version=1.16.29
+7
View File
@@ -25,6 +25,13 @@
- Solana WS: `wss://devnet.helius-rpc.com/?api-key=YOUR_HELIUS_API_KEY` - Solana WS: `wss://devnet.helius-rpc.com/?api-key=YOUR_HELIUS_API_KEY`
- Приведённые Helius URLs предназначены **только для приватных серверных конфигов**. `YOUR_HELIUS_API_KEY` — плейсхолдер. Не передавайте такой URL напрямую в публичный UI: посетители увидят ключ. - Приведённые Helius URLs предназначены **только для приватных серверных конфигов**. `YOUR_HELIUS_API_KEY` — плейсхолдер. Не передавайте такой URL напрямую в публичный UI: посетители увидят ключ.
- Caddy config: `/etc/caddy/Caddyfile` - Caddy config: `/etc/caddy/Caddyfile`
- На t2 маршрут `GET /api/files/user-server` направлен в Jetty `127.0.0.1:7102`
перед SPA fallback; `/dm-files/*` также направлен в Jetty для legacy DM.
Проверка: HTTP-ответ на неизвестный login — JSON с кодом 404, не HTML с кодом 200.
- Для новых R2-вложений отдельно требуются публичные DNS/Cloudflare custom domains
`files.t2.shineup.me` и `dm-files.t2.shineup.me`. На 17.11.2026 они не
разрешаются в DNS, поэтому скачивание новых вложений остаётся недоступным
до настройки этих доменов у владельца зоны и корзин R2.
- Общий PostgreSQL container: `shine-test-postgres` - Общий PostgreSQL container: `shine-test-postgres`
- PostgreSQL image: `postgres:18` - PostgreSQL image: `postgres:18`
- PostgreSQL engine version на `2026-07-28`: `18.4` - PostgreSQL engine version на `2026-07-28`: `18.4`
+16
View File
@@ -57,3 +57,19 @@
показывать окончание 14-дневного срока без скачивания; старые v1/v2 сохраняют показывать окончание 14-дневного срока без скачивания; старые v1/v2 сохраняют
прежний протокол и правила хранения. Подробнее в `Файлы_DM_v3_R2.md` и прежний протокол и правила хранения. Подробнее в `Файлы_DM_v3_R2.md` и
`docs/API/18_DM_File_Storage_API.md`. `docs/API/18_DM_File_Storage_API.md`.
### Вложения и запись голосового в UI (17.11.2026)
В личной переписке выбранные файлы остаются в очереди у поля ввода: можно
дописать подпись, убрать файл и отправить всё одним сообщением. Текст
показывается под вложением. У вложений DM v3
показывается оставшийся срок хранения на основе `at` (14 дней). Запись
голосового начинается при нажатии микрофона: короткое нажатие закрепляет запись,
удержание с отпусканием отправляет, движение вверх закрепляет, влево отменяет.
В закреплённом режиме доступны пауза/продолжение, отправка и отмена. Текст в
поле ввода переключает кнопку микрофона в кнопку отправки текста.
HTTP resolver `/api/files/user-server` обязан возвращать JSON через Jetty,
поэтому Caddy должен направлять этот путь до SPA fallback. Если маршрута нет,
клиент показывает ошибку каталога серверов без вывода HTML в интерфейс.
Бинарный контейнер `SHiNE_DM` и серверный API этим изменением не меняются.
+11 -1
View File
@@ -977,7 +977,10 @@
"text_005": "File downloaded", "text_005": "File downloaded",
"text_006": "file", "text_006": "file",
"text_007": "Download {value1}", "text_007": "Download {value1}",
"file_expired": "File no longer available: encrypted attachments are kept for up to 14 days." "file_expired": "File no longer available: encrypted attachments are kept for up to 14 days.",
"file_expired_short": "Attachment has expired",
"remaining_less_day": "Attachment available for less than a day",
"remaining_days": "Attachment available for {value1} more days"
}, },
"palette_editor": { "palette_editor": {
"text_001": "Failed to read palette, please make sure the whole text is copied.", "text_001": "Failed to read palette, please make sure the whole text is copied.",
@@ -2216,6 +2219,13 @@
"text_039": "Who to show" "text_039": "Who to show"
}, },
"chat_view": { "chat_view": {
"voice_cancel": "Discard recording",
"voice_pause": "Pause recording",
"voice_resume": "Resume recording",
"voice_cancelled": "Recording discarded",
"voice_tap_hint": "Tap send or discard the recording",
"voice_send": "Send voice message",
"file_remove": "Remove file {value1}",
"security_notice": { "security_notice": {
"title": "Private chat security", "title": "Private chat security",
"encryption": "Messages in this chat are encrypted on the participants' devices.", "encryption": "Messages in this chat are encrypted on the participants' devices.",
+11 -1
View File
@@ -977,7 +977,10 @@
"text_005": "Файл скачан", "text_005": "Файл скачан",
"text_006": "файл", "text_006": "файл",
"text_007": "Скачать {value1}", "text_007": "Скачать {value1}",
"file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней." "file_expired": "Файл больше недоступен: зашифрованные вложения хранятся не более 14 дней.",
"file_expired_short": "Срок хранения вложения истёк",
"remaining_less_day": "Вложение доступно ещё менее дня",
"remaining_days": "Вложение доступно ещё {value1} дн."
}, },
"palette_editor": { "palette_editor": {
"text_001": "Не удалось прочитать палитру: проверьте, что текст скопирован целиком.", "text_001": "Не удалось прочитать палитру: проверьте, что текст скопирован целиком.",
@@ -2349,6 +2352,13 @@
"text_039": "Кого показать" "text_039": "Кого показать"
}, },
"chat_view": { "chat_view": {
"voice_cancel": "Отменить запись",
"voice_pause": "Приостановить запись",
"voice_resume": "Продолжить запись",
"voice_cancelled": "Запись отменена",
"voice_tap_hint": "Нажмите кнопку отправки или отмените запись",
"voice_send": "Отправить голосовое",
"file_remove": "Убрать файл {value1}",
"security_notice": { "security_notice": {
"title": "Безопасность личной переписки", "title": "Безопасность личной переписки",
"encryption": "Сообщения в этом чате шифруются на устройствах участников.", "encryption": "Сообщения в этом чате шифруются на устройствах участников.",
+154 -24
View File
@@ -1292,6 +1292,21 @@ function renderLog(
); );
} }
bubble.append(attachmentsWrap); 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'); 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-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> <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> <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-dot" aria-hidden="true"></span>
<span class="dm-voice-recording-time" id="chat-voice-recording-time">0:00</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> <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>
<div class="dm-field"> <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> <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-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> <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>
<div class="dm-file-queue" id="chat-file-queue" hidden></div>
<input id="chat-file-input" type="file" multiple hidden /> <input id="chat-file-input" type="file" multiple hidden />
<input id="chat-media-input" type="file" accept="image/*,video/*" 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 /> <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 emojiToggle = form.querySelector('#chat-emoji-toggle');
const fileToggle = form.querySelector('#chat-file-toggle'); const fileToggle = form.querySelector('#chat-file-toggle');
const fileInput = form.querySelector('#chat-file-input'); const fileInput = form.querySelector('#chat-file-input');
const fileQueue = form.querySelector('#chat-file-queue');
// Три входа для вложений: галерея (фото/видео), камера и любой файл – дальше путь один. // Три входа для вложений: галерея (фото/видео), камера и любой файл – дальше путь один.
const attachSources = [ const attachSources = [
[fileToggle, fileInput], [fileToggle, fileInput],
@@ -1928,6 +1947,8 @@ export function render({ navigate, route, chrome }) {
const voiceStatus = form.querySelector('#chat-voice-recording-status'); const voiceStatus = form.querySelector('#chat-voice-recording-status');
const voiceTime = form.querySelector('#chat-voice-recording-time'); const voiceTime = form.querySelector('#chat-voice-recording-time');
const voiceHint = form.querySelector('#chat-voice-recording-hint'); 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 fileTransferEnabled = isDmFileTransferEnabled();
const editBanner = form.querySelector('#chat-edit-banner'); const editBanner = form.querySelector('#chat-edit-banner');
const editBannerText = form.querySelector('#chat-edit-banner-text'); const editBannerText = form.querySelector('#chat-edit-banner-text');
@@ -1940,6 +1961,8 @@ export function render({ navigate, route, chrome }) {
let emojiLongPressTimer = null; let emojiLongPressTimer = null;
let emojiLongPressTriggered = false; let emojiLongPressTriggered = false;
let fileActionVisible = false; let fileActionVisible = false;
let queuedFiles = [];
let fileSending = false;
let voiceRecorder = null; let voiceRecorder = null;
let voiceStream = null; let voiceStream = null;
let voiceChunks = []; let voiceChunks = [];
@@ -1949,6 +1972,11 @@ export function render({ navigate, route, chrome }) {
let voicePointerHeld = false; let voicePointerHeld = false;
let voiceReleaseRequested = false; let voiceReleaseRequested = false;
let voiceStartY = 0; let voiceStartY = 0;
let voiceStartX = 0;
let voicePressStartedAt = 0;
let voiceCancelRequested = false;
let voicePausedMs = 0;
let voicePausedAt = 0;
let voicePointerId = null; let voicePointerId = null;
let voiceBusy = false; let voiceBusy = false;
let suppressVoiceClick = false; let suppressVoiceClick = false;
@@ -2024,7 +2052,7 @@ export function render({ navigate, route, chrome }) {
return iconHtml('send'); return iconHtml('send');
} }
if (mode === 'stop') { 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') { if (mode === 'busy') {
return '<span class="dm-send-busy-dot">…</span>'; return '<span class="dm-send-busy-dot">…</span>';
@@ -2032,7 +2060,8 @@ export function render({ navigate, route, chrome }) {
return iconHtml('mic'); 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 = () => { const syncVoiceTimer = () => {
if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs()); if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs());
@@ -2058,22 +2087,22 @@ export function render({ navigate, route, chrome }) {
if (!sendBtn) return; if (!sendBtn) return;
const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive'); const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive');
let mode = 'voice'; let mode = 'voice';
if (voiceBusy) mode = 'busy'; if (voiceBusy || fileSending) mode = 'busy';
else if (recording && voiceLocked) mode = 'stop'; else if (recording && voiceLocked) mode = 'stop';
else if (recording) mode = 'voice'; 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.dataset.mode = mode;
sendBtn.innerHTML = sendIconMarkup(mode); sendBtn.innerHTML = sendIconMarkup(mode);
sendBtn.classList.toggle('is-recording', recording); sendBtn.classList.toggle('is-recording', recording);
sendBtn.classList.toggle('is-locked', recording && voiceLocked); 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') { if (mode === 'send') {
sendBtn.title = t('screens.chat_view.text_029'); sendBtn.title = t('screens.chat_view.text_029');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029')); sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029'));
} else if (mode === 'stop') { } else if (mode === 'stop') {
sendBtn.title = t('screens.chat_view.text_030'); sendBtn.title = t('screens.chat_view.voice_send');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030')); sendBtn.setAttribute('aria-label', t('screens.chat_view.voice_send'));
} else if (mode === 'busy') { } else if (mode === 'busy') {
sendBtn.title = t('screens.chat_view.text_031'); sendBtn.title = t('screens.chat_view.text_031');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_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); form.classList.toggle('dm-chat-input--recording', recording);
if (voiceStatus) voiceStatus.hidden = !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 (input) input.hidden = recording;
if (emojiToggle) emojiToggle.hidden = recording; if (emojiToggle) emojiToggle.hidden = recording;
attachButtons.forEach((button) => { button.hidden = recording || !fileTransferEnabled; }); attachButtons.forEach((button) => { button.hidden = recording || !fileTransferEnabled; });
@@ -2110,7 +2146,10 @@ export function render({ navigate, route, chrome }) {
const stopVoiceRecording = ({ send = true } = {}) => { const stopVoiceRecording = ({ send = true } = {}) => {
voicePointerHeld = false; voicePointerHeld = false;
voiceReleaseRequested = true; voiceReleaseRequested = true;
if (!voiceRecorder || voiceRecorder.state === 'inactive') return; if (!voiceRecorder || voiceRecorder.state === 'inactive') {
if (!send) voiceCancelRequested = true;
return;
}
voiceRecorder.__shineShouldSend = Boolean(send); voiceRecorder.__shineShouldSend = Boolean(send);
try { try {
voiceRecorder.stop(); 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 (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
if (!fileTransferEnabled) { if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 }); showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
@@ -2138,7 +2177,11 @@ export function render({ navigate, route, chrome }) {
voiceReleaseRequested = false; voiceReleaseRequested = false;
voiceLocked = false; voiceLocked = false;
voiceStartY = Number(pointerY || 0); voiceStartY = Number(pointerY || 0);
voiceStartX = Number(pointerX || 0);
voicePointerId = pointerId; voicePointerId = pointerId;
voiceCancelRequested = false;
voicePausedMs = 0;
voicePausedAt = 0;
suppressVoiceClick = false; suppressVoiceClick = false;
try { try {
@@ -2166,13 +2209,15 @@ export function render({ navigate, route, chrome }) {
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' }); showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
}); });
recorder.addEventListener('stop', async () => { recorder.addEventListener('stop', async () => {
const shouldSend = recorder.__shineShouldSend !== false; const shouldSend = recorder.__shineShouldSend !== false && !voiceCancelRequested;
const durationMs = currentVoiceDurationMs(); const durationMs = currentVoiceDurationMs();
const chunks = voiceChunks.slice(); const chunks = voiceChunks.slice();
voiceChunks = []; voiceChunks = [];
voiceRecorder = null; voiceRecorder = null;
voiceLocked = false; voiceLocked = false;
voiceStartedAt = 0; voiceStartedAt = 0;
voicePausedAt = 0;
voicePausedMs = 0;
clearVoiceTimer(); clearVoiceTimer();
stopVoiceStreamTracks(); stopVoiceStreamTracks();
voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0); voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0);
@@ -2211,7 +2256,8 @@ export function render({ navigate, route, chrome }) {
recorder.start(1000); recorder.start(1000);
voiceTimer = window.setInterval(syncVoiceTimer, 250); voiceTimer = window.setInterval(syncVoiceTimer, 250);
updateSendButtonMode(); updateSendButtonMode();
if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true }); if (voiceCancelRequested) stopVoiceRecording({ send: false });
else if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
} catch (error) { } catch (error) {
voicePointerHeld = false; voicePointerHeld = false;
voiceReleaseRequested = 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); const attachments = (Array.isArray(attachmentsInput) ? attachmentsInput : [attachmentsInput]).filter(Boolean);
if (!attachments.length) return; if (!attachments.length) return;
if (attachments.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) { if (attachments.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
@@ -2542,7 +2588,7 @@ export function render({ navigate, route, chrome }) {
: (attachments.length === 1 : (attachments.length === 1
? `📎 ${String(attachments[0]?.name || 'file')}` ? `📎 ${String(attachments[0]?.name || 'file')}`
: t('screens.chat_view.text_097', { value1: attachments.length })); : 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 }); hideUnreadSeparator({ rerender: false });
const tempId = addOutgoingPendingMessage(chatId, finalText); 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), { showToast(actionErrorText(attachments.length === 1 ? t('screens.chat_view.text_075') : t('screens.chat_view.text_076'), error), {
kind: 'error', kind: 'error',
action: { action: {
@@ -2614,17 +2660,40 @@ export function render({ navigate, route, chrome }) {
onClick: async () => { onClick: async () => {
if (disposed) return; if (disposed) return;
try { 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 }); 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) { } 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) => { const handleSelectedFiles = async (fileList) => {
if (fileSending) return;
if (!fileTransferEnabled) { if (!fileTransferEnabled) {
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 }); showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
return; return;
@@ -2634,11 +2703,14 @@ export function render({ navigate, route, chrome }) {
return; return;
} }
const allFiles = Array.from(fileList || []).filter(Boolean); const allFiles = Array.from(fileList || []).filter(Boolean);
const caption = String(input?.value || '').trim();
if (!allFiles.length) return; if (!allFiles.length) return;
if (allFiles.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) { 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 }); showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error', timeoutMs: 2200 });
return; return;
} }
fileSending = true;
updateSendButtonMode();
attachButtons.forEach((button) => { attachButtons.forEach((button) => {
button.disabled = true; button.disabled = true;
@@ -2666,13 +2738,26 @@ export function render({ navigate, route, chrome }) {
attachments.push(attachment); attachments.push(attachment);
} }
uploaded = true; 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); setFileActionVisible(false);
showToast(attachments.length === 1 ? t('screens.chat_view.text_078') : t('screens.chat_view.text_103', { value1: attachments.length }), { timeoutMs: 1300 }); showToast(attachments.length === 1 ? t('screens.chat_view.text_078') : t('screens.chat_view.text_103', { value1: attachments.length }), { timeoutMs: 1300 });
} catch (error) { } 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' }); else showToast(actionErrorText(allFiles.length === 1 ? t('screens.chat_view.text_079') : t('screens.chat_view.text_080'), error), { kind: 'error' });
} finally { } finally {
fileSending = false;
updateSendButtonMode();
attachButtons.forEach((button) => { attachButtons.forEach((button) => {
button.disabled = false; button.disabled = false;
button.classList.remove('is-busy'); button.classList.remove('is-busy');
@@ -2920,7 +3005,14 @@ export function render({ navigate, route, chrome }) {
}); });
picker?.addEventListener('change', () => { picker?.addEventListener('change', () => {
const files = Array.from(picker.files || []); 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) => { screen.addEventListener('pointerdown', (event) => {
@@ -2953,14 +3045,21 @@ export function render({ navigate, route, chrome }) {
voicePointerHeld = true; voicePointerHeld = true;
voiceReleaseRequested = false; voiceReleaseRequested = false;
voiceStartY = Number(event.clientY || 0); voiceStartY = Number(event.clientY || 0);
voicePressStartedAt = Date.now();
voicePointerId = event.pointerId; voicePointerId = event.pointerId;
try { sendBtn.setPointerCapture?.(event.pointerId); } catch { /* optional */ } 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) => { sendBtn?.addEventListener('pointermove', (event) => {
if (!voicePointerHeld || voiceLocked || voicePointerId !== event.pointerId) return; 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) { if (Number(event.clientY || 0) <= voiceStartY - 64) {
voiceLocked = true; voiceLocked = true;
voiceReleaseRequested = false; voiceReleaseRequested = false;
@@ -2977,13 +3076,40 @@ export function render({ navigate, route, chrome }) {
voiceReleaseRequested = true; voiceReleaseRequested = true;
try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ } try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
voicePointerId = null; 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; suppressVoiceClick = true;
stopVoiceRecording({ send: true }); } else if (!voiceLocked) {
suppressVoiceClick = true;
stopVoiceRecording({ send: !voiceCancelRequested });
} }
}; };
sendBtn?.addEventListener('pointerup', finishVoicePointerGesture); 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) => { sendBtn?.addEventListener('contextmenu', (event) => {
if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault(); if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault();
}); });
@@ -3012,6 +3138,10 @@ export function render({ navigate, route, chrome }) {
form.addEventListener('submit', async (event) => { form.addEventListener('submit', async (event) => {
event.preventDefault(); event.preventDefault();
const text = String(input.value || '').trim(); const text = String(input.value || '').trim();
if (queuedFiles.length) {
await handleSelectedFiles(queuedFiles);
return;
}
if (!text) return; if (!text) return;
input.value = ''; input.value = '';
autoResizeComposer(input); autoResizeComposer(input);
-12
View File
@@ -232,18 +232,6 @@ function createUnavailableBlock(messageTimestampMs, storage = 'arweave', detail
? t('remaining.attachments.the_file_may_not_have_propagated_to_arweave_yet_please_try') ? t('remaining.attachments.the_file_may_not_have_propagated_to_arweave_yet_please_try')
: t('remaining.attachments.file_unavailable'); : t('remaining.attachments.file_unavailable');
} }
if (detail) {
const debug = document.createElement('pre');
debug.className = 'message-attachment-debug';
debug.textContent = [
'DEBUG server attachment',
detail.name ? `name: ${detail.name}` : '',
detail.sha256 ? `sha256: ${detail.sha256}` : '',
detail.url ? `url: ${detail.url}` : '',
detail.error ? `error: ${detail.error}` : '',
].filter(Boolean).join('\n');
block.append(debug);
}
return block; return block;
} }
@@ -39,6 +39,10 @@ async function lookup(login, base) {
method: 'GET', cache: 'no-store', credentials: 'omit', referrerPolicy: 'no-referrer', method: 'GET', cache: 'no-store', credentials: 'omit', referrerPolicy: 'no-referrer',
}); });
if (!response.ok) throw new Error(`Access-server lookup HTTP ${response.status}`); if (!response.ok) throw new Error(`Access-server lookup HTTP ${response.status}`);
const contentType = String(response.headers?.get?.('Content-Type') || '').toLowerCase();
if (contentType && !contentType.includes('application/json')) {
throw new Error('Access-server file directory returned a non-JSON response');
}
return normalizeServerResponse(await response.json()); return normalizeServerResponse(await response.json());
} }
+47 -1
View File
@@ -1066,7 +1066,7 @@
grid-column: 1; grid-column: 1;
min-height: 42px; min-height: 42px;
display: grid; display: grid;
grid-template-columns: auto auto minmax(0, 1fr); grid-template-columns: auto auto auto minmax(0, 1fr) auto;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
padding: 0 12px; padding: 0 12px;
@@ -1110,6 +1110,46 @@
font-size: 11px; font-size: 11px;
color: var(--text-secondary); color: var(--text-secondary);
} }
.dm-voice-cancel, .dm-voice-pause {
width: 32px;
height: 32px;
border: 0;
border-radius: 50%;
background: var(--surface-selected);
color: var(--text-primary);
cursor: pointer;
font-size: 18px;
touch-action: manipulation;
}
.dm-voice-cancel { color: var(--danger); }
.dm-voice-pause[hidden] { display: none; }
.dm-chat-input--voice-paused .dm-voice-recording-dot { animation-play-state: paused; opacity: .35; }
.dm-attachment-expiry {
margin-top: 6px;
color: var(--text-secondary);
font-size: 11px;
line-height: 1.3;
}
.dm-file-queue {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 8px 10px 2px;
}
.dm-file-queue[hidden] { display: none; }
.dm-file-queue__chip {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 100%;
border: 1px solid var(--border-subtle);
border-radius: 12px;
padding: 5px 8px;
background: var(--surface-selected);
font-size: 12px;
}
.dm-file-queue__chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dm-file-queue__chip button { border: 0; background: none; color: var(--text-secondary); cursor: pointer; }
.dm-chat-input--recording .dm-actions-col { .dm-chat-input--recording .dm-actions-col {
align-self: center; align-self: center;
@@ -1519,6 +1559,12 @@
border: 0; border: 0;
background: transparent; background: transparent;
} }
.dm-chat-input--recording .dm-composer-bar {
border-color: color-mix(in srgb, var(--danger) 45%, var(--border-control));
}
.dm-chat-input--recording .dm-send-btn {
touch-action: none;
}
/* ===== Нижняя панель ввода – одна для чатов, обсуждений и каналов ===== /* ===== Нижняя панель ввода – одна для чатов, обсуждений и каналов =====