Локализовать интерфейс SHiNE на русский и английский

This commit is contained in:
AidarKC
2026-11-09 16:45:21 +03:00
parent 526941eb33
commit 405b9a91a7
133 changed files with 12464 additions and 3296 deletions
+178 -171
View File
@@ -1,3 +1,4 @@
import { t, th } from '../i18n/index.js';
import { appendShineMessageLinks } from '../services/shine-message-links.js';
import { iconHtml } from '../components/ui-icon.js';
import { createSearchTopBar, createTopBar } from '../components/topbar.js';
@@ -61,7 +62,7 @@ import { isDmSendEnter } from '../services/dm-composer-keys.js';
export const pageMeta = {
id: 'chat-view',
title: 'Чат',
get title() { return t('screens.chat_view.text_001'); },
shellMode: {
topFade: true,
bottomFade: true,
@@ -96,9 +97,9 @@ function normalizeChatRelationType(value) {
function chatRelationLabel(value) {
switch (normalizeChatRelationType(value)) {
case 'close_friend': return 'Близкий друг';
case 'friend': return 'Друг';
case 'contact': return 'Контакт';
case 'close_friend': return t('screens.chat_view.text_056');
case 'friend': return t('screens.chat_view.text_057');
case 'contact': return t('screens.chat_view.text_058');
default: return '';
}
}
@@ -117,8 +118,8 @@ function createChatHeaderParts(login, navigate) {
const identityButton = document.createElement('button');
identityButton.type = 'button';
identityButton.className = 'topbar-identity chat-header-peer-btn';
identityButton.title = `Меню ${cleanLogin}`;
identityButton.setAttribute('aria-label', `Открыть меню пользователя ${cleanLogin}`);
identityButton.title = t('screens.chat_view.text_083', { value1: cleanLogin });
identityButton.setAttribute('aria-label', t('screens.chat_view.text_084', { value1: cleanLogin }));
const avatarSlot = document.createElement('span');
avatarSlot.className = 'chat-header-avatar-slot';
@@ -139,13 +140,13 @@ function createChatHeaderParts(login, navigate) {
if (muted) {
const mutedIcon = document.createElement('span');
mutedIcon.className = 'chat-header-muted';
mutedIcon.title = 'Без звука';
mutedIcon.title = t('screens.chat_view.text_002');
mutedIcon.innerHTML = iconHtml('bell-off');
nameEl.append(mutedIcon);
}
const relation = chatRelationLabel(currentPeer?.relationType);
// Статус аккаунта, а не «в сети»: присутствие сервер не сообщает, выдумывать его нельзя
const shining = String(currentPeer?.shineStatus || '').toLowerCase() === 'shining' ? '✧ сияющий аккаунт' : '';
const shining = String(currentPeer?.shineStatus || '').toLowerCase() === 'shining' ? t('screens.chat_view.text_059') : '';
metaEl.textContent = [fullName ? cleanLogin : '', shining, relation].filter(Boolean).join(' · ');
metaEl.hidden = !metaEl.textContent;
const avatar = renderUserAvatar({
@@ -184,12 +185,12 @@ function createChatHeaderParts(login, navigate) {
minWidth: 210,
items: [
{
label: 'Показать связи',
label: t('screens.chat_view.text_003'),
iconSrc: '/assets/SHiNE_connections_blue.svg',
action: () => navigate(makeProfileLinksRoute(cleanLogin)),
},
{
label: 'Показать профиль',
label: t('screens.chat_view.text_004'),
iconSrc: '/assets/profile-icon-profile.svg',
action: () => navigate(makeProfileRoute(cleanLogin)),
},
@@ -227,11 +228,11 @@ function openDeleteMessageConfirmModal({ onConfirm }) {
root.innerHTML = `
<div class="modal" id="chat-delete-message-modal">
<div class="modal-card stack">
<h3 class="modal-title">Удалить сообщение?</h3>
<p class="meta-muted">Оно исчезнет и у тебя, и у собеседника.</p>
<h3 class="modal-title">${t('dialogs.modals.chat_view.label_001')}</h3>
<p class="meta-muted">${t('dialogs.modals.chat_view.label_002')}</p>
<div class="form-actions-grid">
<button class="secondary-btn" type="button" id="chat-delete-message-no">Нет</button>
<button class="primary-btn" type="button" id="chat-delete-message-yes">Да</button>
<button class="secondary-btn" type="button" id="chat-delete-message-no">${t('dialogs.modals.chat_view.label_003')}</button>
<button class="primary-btn" type="button" id="chat-delete-message-yes">${t('dialogs.modals.chat_view.label_004')}</button>
</div>
</div>
</div>
@@ -249,9 +250,9 @@ function openDeleteMessageConfirmModal({ onConfirm }) {
}
function openChatConfirmModal({
title = 'Подтвердить действие',
title = t('dialogs.remaining.pages.chat_view.openchatconfirmmodal.podtverdit_deystvie'),
text = '',
confirmLabel = 'Да',
confirmLabel = t('dialogs.remaining.pages.chat_view.openchatconfirmmodal.da'),
confirmKind = 'primary',
onConfirm,
}) {
@@ -264,7 +265,7 @@ function openChatConfirmModal({
<h3 class="modal-title">${title}</h3>
<p class="meta-muted">${text}</p>
<div class="form-actions-grid">
<button class="secondary-btn" type="button" id="chat-confirm-no">Нет</button>
<button class="secondary-btn" type="button" id="chat-confirm-no">${t('dialogs.modals.chat_view.label_003')}</button>
<button class="${confirmClass}" type="button" id="chat-confirm-yes">${confirmLabel}</button>
</div>
</div>
@@ -294,7 +295,7 @@ function openDateJumpModal({ days = new Map(), loading = false, onPick } = {}) {
const root = document.getElementById('modal-root');
if (!root) return null;
const monthTitle = new Intl.DateTimeFormat('ru-RU', { month: 'long', year: 'numeric' });
const weekdays = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];
const weekdays = [t('dialogs.remaining.pages.chat_view.opendatejumpmodal.pn'), t('dialogs.remaining.pages.chat_view.opendatejumpmodal.vt'), t('dialogs.remaining.pages.chat_view.opendatejumpmodal.sr'), t('dialogs.remaining.pages.chat_view.opendatejumpmodal.cht'), t('dialogs.remaining.pages.chat_view.opendatejumpmodal.pt'), t('dialogs.remaining.pages.chat_view.opendatejumpmodal.sb'), t('dialogs.remaining.pages.chat_view.opendatejumpmodal.vs')];
let currentDays = days;
let isLoading = loading;
const latestTime = () => Math.max(0, ...Array.from(currentDays.values(), (d) => d.timeMs));
@@ -305,15 +306,15 @@ function openDateJumpModal({ days = new Map(), loading = false, onPick } = {}) {
root.innerHTML = `
<div class="modal dm-date-jump-modal" id="chat-date-jump-modal">
<div class="modal-card stack dm-date-jump" role="dialog" aria-modal="true" aria-label="Перейти к дате">
<div class="modal-card stack dm-date-jump" role="dialog" aria-modal="true" aria-label="${t('dialogs.modals.chat_view.label_005')}">
<div class="dm-date-jump__head">
<button class="icon-btn dm-date-jump__nav" type="button" data-nav="-1" aria-label="Предыдущий месяц">${iconHtml('back')}</button>
<button class="icon-btn dm-date-jump__nav" type="button" data-nav="-1" aria-label="${t('dialogs.modals.chat_view.label_006')}">${iconHtml('back')}</button>
<h3 class="modal-title dm-date-jump__title"></h3>
<button class="icon-btn dm-date-jump__nav" type="button" data-nav="1" aria-label="Следующий месяц">${iconHtml('open')}</button>
<button class="icon-btn dm-date-jump__nav" type="button" data-nav="1" aria-label="${t('dialogs.modals.chat_view.label_007')}">${iconHtml('open')}</button>
</div>
<div class="dm-date-jump__grid" role="grid"></div>
<p class="meta-muted dm-date-jump__note"></p>
<button class="secondary-btn" type="button" id="chat-date-jump-close">Закрыть</button>
<button class="secondary-btn" type="button" id="chat-date-jump-close">${t('dialogs.modals.chat_view.label_008')}</button>
</div>
</div>
`;
@@ -348,7 +349,7 @@ function openDateJumpModal({ days = new Map(), loading = false, onPick } = {}) {
btn.textContent = String(day);
btn.disabled = !info;
if (info) {
btn.title = `${info.count} ${info.count % 10 === 1 && info.count % 100 !== 11 ? 'сообщение' : (info.count % 10 >= 2 && info.count % 10 <= 4 && (info.count % 100 < 12 || info.count % 100 > 14) ? 'сообщения' : 'сообщений')}`;
btn.title = `${info.count} ${info.count % 10 === 1 && info.count % 100 !== 11 ? t('dialogs.remaining.pages.chat_view.opendatejumpmodal.soobschenie') : (info.count % 10 >= 2 && info.count % 10 <= 4 && (info.count % 100 < 12 || info.count % 100 > 14) ? t('dialogs.remaining.pages.chat_view.opendatejumpmodal.soobscheniya') : t('dialogs.remaining.pages.chat_view.opendatejumpmodal.soobscheniy'))}`;
btn.addEventListener('click', () => {
close();
onPick?.(key);
@@ -356,7 +357,7 @@ function openDateJumpModal({ days = new Map(), loading = false, onPick } = {}) {
}
grid.append(btn);
}
note.textContent = isLoading ? 'Загружаю историю – более ранние дни появятся чуть позже.' : '';
note.textContent = isLoading ? t('dialogs.modals.chat_view.label_016') : '';
note.hidden = !isLoading;
};
@@ -386,6 +387,12 @@ function openDateJumpModal({ days = new Map(), loading = false, onPick } = {}) {
};
}
function escapeDialogHtml(value) {
return String(value ?? '').replace(/[&<>"']/g, (char) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
}[char]));
}
function openDeleteChatConfirmModal({ contactName = '', relationType = 'none', onConfirm }) {
const root = document.getElementById('modal-root');
if (!root) return;
@@ -393,26 +400,26 @@ function openDeleteChatConfirmModal({ contactName = '', relationType = 'none', o
const isCloseFriend = relation === 'close_friend';
const isFriend = relation === 'friend';
const isProtectedRelation = isCloseFriend || isFriend;
const relationName = isCloseFriend ? 'близких друзей' : 'друзей';
const safeName = String(contactName || '').trim() || 'этого пользователя';
const relationName = isCloseFriend ? t('dialogs.remaining.pages.chat_view.opendeletechatconfirmmodal.blizkih_druzey') : t('dialogs.remaining.pages.chat_view.opendeletechatconfirmmodal.druzey');
const safeName = String(contactName || '').trim() || t('dialogs.remaining.pages.chat_view.opendeletechatconfirmmodal.etogo_polzovatelya');
root.innerHTML = `
<div class="modal" id="chat-delete-chat-modal">
<div class="modal-card stack">
<h3 class="modal-title">Удалить чат?</h3>
<h3 class="modal-title">${t('dialogs.modals.chat_view.label_009')}</h3>
${isProtectedRelation ? `
<p class="meta-muted">Можно удалить содержимое переписки, но чат с ${isCloseFriend ? 'близким другом' : 'другом'} останется в списке.</p>
<p class="meta-muted">Удалить ${safeName} из ${relationName} и удалить чат?</p>
<p class="meta-muted">${t('dialogs.final.chat.delete_protected_notice', { relation: isCloseFriend ? t('dialogs.remaining.pages.chat_view.opendeletechatconfirmmodal.blizkim_drugom') : t('dialogs.remaining.pages.chat_view.opendeletechatconfirmmodal.drugom') })}</p>
<p class="meta-muted">${escapeDialogHtml(t('dialogs.final.chat.delete_protected_confirm', { name: safeName, relation: relationName }))}</p>
` : `
<p class="meta-muted">Удалить пользователя ${safeName} из контактов?</p>
<p class="meta-muted">${escapeDialogHtml(t('dialogs.final.chat.delete_contact_confirm', { name: safeName }))}</p>
<label class="dm-confirm-check">
<input type="checkbox" id="chat-delete-chat-history" checked />
<span>Также удалить всю историю переписки</span>
<span>${t('dialogs.remaining.pages.chat_view.markup.takzhe_udalit_vsyu_istoriyu_perepiski')}</span>
</label>
`}
<div class="form-actions-grid">
<button class="secondary-btn" type="button" id="chat-delete-chat-no">Нет</button>
<button class="destructive-btn" type="button" id="chat-delete-chat-yes">Да</button>
<button class="secondary-btn" type="button" id="chat-delete-chat-no">${t('dialogs.remaining.pages.chat_view.markup.net')}</button>
<button class="destructive-btn" type="button" id="chat-delete-chat-yes">${t('dialogs.remaining.pages.chat_view.markup.da')}</button>
</div>
</div>
</div>
@@ -442,7 +449,7 @@ function buildForwardedDmText(message = {}) {
if (attachmentBlocks) {
const fallback = visibleText || (attachments.length === 1
? `📎 ${String(attachments[0]?.name || 'file')}`
: `📎 Файлы: ${attachments.length}`);
: t('screens.chat_view.text_085', { value1: attachments.length }));
return `${attachmentBlocks}${fallback}`;
}
return visibleText;
@@ -459,20 +466,20 @@ async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm
if (!root) return;
const parsed = parseDmTechBlocks(String(message?.text || ''));
const preview = clipForwardPreview(parsed?.displayText || parsed?.visibleText || 'Вложение');
const preview = clipForwardPreview(parsed?.displayText || parsed?.visibleText || t('dialogs.remaining.pages.chat_view.openforwardmessagedialog.vlozhenie'));
root.innerHTML = `
<div class="modal dm-forward-modal" id="chat-forward-modal">
<div class="modal-card stack dm-forward-card">
<div class="dm-forward-head">
<div>
<h3 class="modal-title">Переслать сообщение</h3>
<p class="meta-muted">Выберите чат</p>
<h3 class="modal-title">${t('dialogs.modals.chat_view.label_011')}</h3>
<p class="meta-muted">${t('dialogs.modals.chat_view.label_012')}</p>
</div>
<button class="ui-button dm-forward-close" type="button" id="chat-forward-close" aria-label="Закрыть">×</button>
<button class="ui-button dm-forward-close" type="button" id="chat-forward-close" aria-label="${t('dialogs.modals.chat_view.label_008')}">×</button>
</div>
<div class="dm-forward-preview" id="chat-forward-preview"></div>
<div class="dm-forward-list" id="chat-forward-list">
<div class="dm-forward-loading"><div class="loading-state" style="--loading-delay:250ms"><span class="spinner" role="status" aria-label="Загрузка"></span></div></div>
<div class="dm-forward-loading"><div class="loading-state" style="--loading-delay:250ms"><span class="spinner" role="status" aria-label="${t('dialogs.modals.chat_view.label_010')}"></span></div></div>
</div>
</div>
</div>
@@ -486,7 +493,7 @@ async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm
const previewEl = root.querySelector('#chat-forward-preview');
if (previewEl) {
previewEl.textContent = preview || (parsed?.fileAttachments?.length ? 'Вложение' : 'Сообщение');
previewEl.textContent = preview || (parsed?.fileAttachments?.length ? t('dialogs.modals.chat_view.label_017') : t('dialogs.remaining.pages.chat_view.openforwardmessagedialog.soobschenie'));
}
const list = root.querySelector('#chat-forward-list');
@@ -527,7 +534,7 @@ async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm
if (!rows.length) {
const empty = document.createElement('div');
empty.className = 'meta-muted dm-forward-loading';
empty.textContent = 'Нет доступных чатов';
empty.textContent = t('dialogs.modals.chat_view.label_018');
list.append(empty);
return;
}
@@ -566,7 +573,7 @@ async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm
const confirmTitle = document.createElement('h3');
confirmTitle.className = 'modal-title';
confirmTitle.textContent = 'Переслать сюда?';
confirmTitle.textContent = t('dialogs.modals.chat_view.label_019');
const recipient = document.createElement('div');
recipient.className = 'dm-forward-confirm-peer';
recipient.append(
@@ -583,18 +590,18 @@ async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm
const confirmPreview = document.createElement('div');
confirmPreview.className = 'dm-forward-preview dm-forward-preview--confirm';
confirmPreview.textContent = preview || (parsed?.fileAttachments?.length ? 'Вложение' : 'Сообщение');
confirmPreview.textContent = preview || (parsed?.fileAttachments?.length ? t('dialogs.modals.chat_view.label_017') : t('dialogs.remaining.pages.chat_view.openforwardmessagedialog.soobschenie'));
const actions = document.createElement('div');
actions.className = 'form-actions-grid dm-forward-confirm-actions';
const back = document.createElement('button');
back.type = 'button';
back.className = 'secondary-btn';
back.textContent = 'Назад';
back.textContent = t('dialogs.modals.chat_view.label_020');
const confirm = document.createElement('button');
confirm.type = 'button';
confirm.className = 'primary-btn';
confirm.textContent = 'Переслать';
confirm.textContent = t('dialogs.modals.chat_view.label_021');
actions.append(back, confirm);
card.append(confirmTitle, recipient, confirmPreview, actions);
@@ -606,16 +613,16 @@ async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm
if (confirm.disabled) return;
confirm.disabled = true;
back.disabled = true;
confirm.textContent = 'Отправляем…';
confirm.textContent = t('dialogs.modals.chat_view.label_022');
try {
await onConfirm?.(item.peerLogin);
close();
showToast(`Сообщение переслано в чат ${item.peerLogin}`, { timeoutMs: 1500 });
showToast(t('dialogs.remaining.pages.chat_view.openforwardmessagedialog.soobschenie_pereslano_v_chat_value1', { value1: item.peerLogin }), { timeoutMs: 1500 });
} catch (error) {
confirm.disabled = false;
back.disabled = false;
confirm.textContent = 'Переслать';
showToast(actionErrorText('Не удалось переслать сообщение', error), { kind: 'error' });
confirm.textContent = t('dialogs.modals.chat_view.label_021');
showToast(actionErrorText(t('dialogs.remaining.pages.chat_view.openforwardmessagedialog.ne_udalos_pereslat_soobschenie'), error), { kind: 'error' });
}
});
});
@@ -625,7 +632,7 @@ async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm
list.replaceChildren();
const fail = document.createElement('div');
fail.className = 'meta-muted dm-forward-loading';
fail.textContent = actionErrorText('Не удалось загрузить чаты', error);
fail.textContent = actionErrorText(t('dialogs.modals.chat_view.label_023'), error);
list.append(fail);
}
}
@@ -653,12 +660,12 @@ function openMessageActionsMenu({
root.innerHTML = `
<div class="dm-floating-menu-layer" id="chat-message-actions-layer">
<div class="modal-card stack dm-message-actions-menu dm-message-actions-popover" id="${menuId}">
${canReply ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-reply">${menuIconSvg('reply')}<span>Ответить</span></button>` : ''}
${canForward ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-forward">${menuIconSvg('forward')}<span>Переслать</span></button>` : ''}
<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-copy">${menuIconSvg('copy')}<span>Скопировать как текст</span></button>
${showReadAloud ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-read">${menuIconSvg('read')}<span>Прочесть</span></button>` : ''}
${canEdit ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-edit">${menuIconSvg('edit')}<span>Изменить</span></button>` : ''}
${canDelete ? `<button class="secondary-btn dm-message-action-btn dm-message-action-btn--danger" type="button" id="msg-action-delete">${menuIconSvg('delete')}<span>Удалить</span></button>` : ''}
${canReply ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-reply">${menuIconSvg('reply')}<span>${th('screens.chat_view.text_106')}</span></button>` : ''}
${canForward ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-forward">${menuIconSvg('forward')}<span>${th('screens.chat_view.text_107')}</span></button>` : ''}
<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-copy">${menuIconSvg('copy')}<span>${t('dialogs.remaining.pages.chat_view.markup.skopirovat_kak_tekst')}</span></button>
${showReadAloud ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-read">${menuIconSvg('read')}<span>${th('screens.chat_view.text_108')}</span></button>` : ''}
${canEdit ? `<button class="secondary-btn dm-message-action-btn" type="button" id="msg-action-edit">${menuIconSvg('edit')}<span>${th('screens.chat_view.text_109')}</span></button>` : ''}
${canDelete ? `<button class="secondary-btn dm-message-action-btn dm-message-action-btn--danger" type="button" id="msg-action-delete">${menuIconSvg('delete')}<span>${th('screens.chat_view.text_110')}</span></button>` : ''}
${String(infoText || '').trim() ? `<div class="meta-muted">${String(infoText || '').trim()}</div>` : ''}
</div>
</div>
@@ -706,9 +713,9 @@ function openMessageActionsMenu({
if (navigator?.clipboard?.writeText) {
await navigator.clipboard.writeText(String(messageText || ''));
}
showToast('Сообщение скопировано', { timeoutMs: 1000 });
showToast(t('screens.chat_view.text_039'), { timeoutMs: 1000 });
} catch {
showToast('Не удалось скопировать сообщение', { kind: 'error', timeoutMs: 1200 });
showToast(t('screens.chat_view.text_040'), { kind: 'error', timeoutMs: 1200 });
} finally {
close();
}
@@ -746,8 +753,8 @@ function showTtsMissingConfigDialog() {
root.innerHTML = `
<div class="modal" id="chat-tts-missing-modal">
<div class="modal-card stack">
<h3 class="modal-title">Озвучка не настроена</h3>
<p class="meta-muted">Функция голосовых инструментов сейчас отключена.</p>
<h3 class="modal-title">${t('dialogs.modals.chat_view.label_013')}</h3>
<p class="meta-muted">${t('dialogs.modals.chat_view.label_014')}</p>
<div class="form-actions-grid">
<button class="primary-btn" type="button" id="chat-tts-ok">OK</button>
</div>
@@ -808,11 +815,11 @@ function openConfirmContactModal(targetLogin = '') {
root.innerHTML = `
<div class="modal" id="contact-confirm-modal">
<div class="modal-card stack">
<h3 class="modal-title">Добавить собеседника</h3>
<p class="meta-muted">Добавить пользователя ${targetLogin} в контакты?</p>
<h3 class="modal-title">${t('dialogs.modals.chat_view.label_015')}</h3>
<p class="meta-muted">${t('dialogs.modals.chat_view.add_user_prefix')}${targetLogin}${t('dialogs.modals.chat_view.add_user_suffix')}</p>
<div class="form-actions-grid">
<button class="secondary-btn" type="button" id="contact-confirm-no">Нет</button>
<button class="primary-btn" type="button" id="contact-confirm-yes">Да</button>
<button class="secondary-btn" type="button" id="contact-confirm-no">${t('dialogs.modals.chat_view.label_003')}</button>
<button class="primary-btn" type="button" id="contact-confirm-yes">${t('dialogs.modals.chat_view.label_004')}</button>
</div>
</div>
</div>
@@ -855,15 +862,15 @@ function formatCallDurationCompact(totalSeconds) {
function buildCallStatusText(callSummary) {
if (!callSummary) return '';
if (callSummary.status === 'completed') {
return `Длительность: ${formatCallDurationCompact(callSummary.durationSec)}`;
return t('screens.chat_view.text_086', { value1: formatCallDurationCompact(callSummary.durationSec) });
}
const reason = String(callSummary.reason || '').trim().toLowerCase();
if (reason === 'offline') return 'Абонент не в сети';
if (reason === 'no_answer') return 'Нет ответа';
if (reason === 'connect_failed') return 'Не удалось установить соединение';
if (reason === 'busy') return 'Абонент занят';
if (reason === 'declined') return 'Звонок отклонён';
return 'Звонок не завершён';
if (reason === 'offline') return t('screens.chat_view.text_060');
if (reason === 'no_answer') return t('screens.chat_view.text_061');
if (reason === 'connect_failed') return t('screens.chat_view.text_062');
if (reason === 'busy') return t('screens.chat_view.text_063');
if (reason === 'declined') return t('screens.chat_view.text_064');
return t('screens.chat_view.text_065');
}
function resolveEffectiveReadState(messages, msg) {
@@ -896,10 +903,10 @@ function resolveDeliveryStatus(messages, msg) {
// Статус сообщения — иконкой и словом для экранного чтения (цвет не единственный носитель смысла)
const DELIVERY_STATUS_VIEW = {
'✓✓': { icon: 'check-double', label: 'Прочитано' },
'✓': { icon: 'check', label: 'Отправлено' },
'!': { icon: 'alert', label: 'Не отправлено' },
'…': { icon: 'clock', label: 'Отправляется' },
'✓✓': { icon: 'check-double', get label() { return t('screens.chat_view.text_005'); } },
'✓': { icon: 'check', get label() { return t('screens.chat_view.text_006'); } },
'!': { icon: 'alert', get label() { return t('screens.chat_view.text_007'); } },
'…': { icon: 'clock', get label() { return t('screens.chat_view.text_008'); } },
};
function resolveDeliveryTone(messages, msg) {
@@ -913,7 +920,7 @@ function resolveDeliveryTone(messages, msg) {
function resolveDeliveryNote(msg) {
if (msg?.from !== 'out') return '';
const deliveryState = String(msg?.deliveryState || '').trim().toLowerCase();
if (deliveryState === 'failed') return 'Сообщение не доставлено.';
if (deliveryState === 'failed') return t('screens.chat_view.text_066');
return '';
}
@@ -986,7 +993,7 @@ function createDmVoiceAttachmentCard(attachment) {
const playBtn = document.createElement('button');
playBtn.type = 'button';
playBtn.className = 'ui-button dm-voice-card__play';
playBtn.setAttribute('aria-label', 'Воспроизвести голосовое сообщение');
playBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_024'));
playBtn.textContent = '▶';
const body = document.createElement('div');
@@ -994,7 +1001,7 @@ function createDmVoiceAttachmentCard(attachment) {
const track = document.createElement('button');
track.type = 'button';
track.className = 'ui-button dm-voice-card__track';
track.setAttribute('aria-label', 'Перемотать голосовое сообщение');
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);
@@ -1004,7 +1011,7 @@ function createDmVoiceAttachmentCard(attachment) {
const duration = document.createElement('span');
duration.textContent = formatVoiceDuration(attachment?.durationMs || 0);
const label = document.createElement('span');
label.textContent = 'Голосовое';
label.textContent = t('dialogs.modals.chat_view.label_026');
meta.append(duration, label);
body.append(track, meta);
card.append(playBtn, body);
@@ -1049,7 +1056,7 @@ function createDmVoiceAttachmentCard(attachment) {
audio.addEventListener('pause', syncProgress);
audio.addEventListener('ended', syncProgress);
audio.addEventListener('error', () => {
showToast('Не удалось воспроизвести голосовое сообщение', { kind: 'error', timeoutMs: 2200 });
showToast(t('screens.chat_view.text_041'), { kind: 'error', timeoutMs: 2200 });
});
return audio;
} finally {
@@ -1068,7 +1075,7 @@ function createDmVoiceAttachmentCard(attachment) {
else player.pause();
syncProgress();
} catch (error) {
showToast(actionErrorText('Не удалось открыть голосовое сообщение', error), { kind: 'error' });
showToast(actionErrorText(t('screens.chat_view.text_042'), error), { kind: 'error' });
}
});
@@ -1082,7 +1089,7 @@ function createDmVoiceAttachmentCard(attachment) {
player.currentTime = player.duration * ratio;
syncProgress();
} catch (error) {
showToast(actionErrorText('Не удалось открыть голосовое сообщение', error), { kind: 'error' });
showToast(actionErrorText(t('screens.chat_view.text_043'), error), { kind: 'error' });
}
});
@@ -1165,7 +1172,7 @@ function renderLog(
const sep = document.createElement('div');
sep.className = 'chat-unread-separator';
const label = document.createElement('span');
label.textContent = 'Новые сообщения';
label.textContent = t('dialogs.modals.chat_view.label_027');
sep.append(label);
list.append(sep);
unreadSeparatorInserted = true;
@@ -1205,7 +1212,7 @@ function renderLog(
const callTitle = document.createElement('span');
callTitle.className = 'bubble-call-title';
callTitle.textContent = 'Звонок';
callTitle.textContent = t('dialogs.modals.chat_view.label_028');
const callMetaLine = document.createElement('span');
callMetaLine.className = 'bubble-call-line';
@@ -1311,7 +1318,7 @@ function renderLog(
if (editedAtMs > 0) {
const editedNode = document.createElement('div');
editedNode.className = 'bubble-meta bubble-meta-edited';
editedNode.textContent = `изменено: ${formatMessageTime(editedAtMs)}`;
editedNode.textContent = t('screens.chat_view.text_087', { value1: formatMessageTime(editedAtMs) });
bubble.append(editedNode);
}
@@ -1423,7 +1430,7 @@ export function render({ navigate, route, chrome }) {
} catch (e) {
// Подробности запуска уже в журнале звонка; человеку – причина тостом, а не пузырь в переписке.
const mediaReason = mediaAccessErrorText(e);
showToast(mediaReason ? `Не удалось начать звонок. ${mediaReason}` : actionErrorText('Не удалось начать звонок', e), { kind: 'error' });
showToast(mediaReason ? t('screens.chat_view.text_088', { value1: mediaReason }) : actionErrorText(t('screens.chat_view.text_044'), e), { kind: 'error' });
renderChatLog({ scrollMode: 'latest', markAsRead: false });
}
};
@@ -1466,7 +1473,7 @@ export function render({ navigate, route, chrome }) {
const contactsPayload = await authService.listContacts();
setContacts(contactsPayload?.contacts || contactsPayload?.dialogs?.filter((x) => x?.relationFlag !== 'none').map((x) => x.peerLogin) || []);
notifyUnreadStateUpdated();
showToast('Добавлено в контакты', { timeoutMs: 1200 });
showToast(t('screens.chat_view.text_045'), { timeoutMs: 1200 });
};
const wrap = document.createElement('div');
@@ -1475,7 +1482,7 @@ export function render({ navigate, route, chrome }) {
historyLoader.className = 'dm-history-loader';
historyLoader.hidden = true;
historyLoader.innerHTML = `
<div class="dm-history-loader__pill" role="status" aria-busy="true" aria-label="Загрузка истории">
<div class="dm-history-loader__pill" role="status" aria-busy="true" aria-label="${th('screens.chat_view.text_111')}">
<span class="dm-history-loader__spinner" aria-hidden="true"></span>
</div>
`;
@@ -1500,67 +1507,67 @@ export function render({ navigate, route, chrome }) {
back: { label: '←', onClick: () => navigate('messages-list') },
actions: [
{
title: 'Позвонить',
ariaLabel: 'Позвонить',
title: t('screens.chat_view.text_009'),
ariaLabel: t('screens.chat_view.text_010'),
className: 'chat-header-icon-btn chat-header-call-btn',
iconNode: createHeaderPhoneHandsetIcon(),
onClick: () => handleStartCall('audio'),
},
{
title: 'Видеозвонок',
ariaLabel: 'Видеозвонок',
title: t('screens.chat_view.text_011'),
ariaLabel: t('screens.chat_view.text_012'),
className: 'chat-header-icon-btn chat-header-video-btn',
icon: 'video',
onClick: () => handleStartCall('video'),
},
{
iconNode: createOverflowDots(),
title: 'Действия чата',
ariaLabel: 'Открыть меню действий чата',
title: t('screens.chat_view.text_013'),
ariaLabel: t('screens.chat_view.text_014'),
className: 'chat-header-icon-btn chat-header-menu-btn topbar-overflow-action--raised',
menu: {
minWidth: 230,
items: () => [
{ label: 'Поиск', iconHtml: iconHtml('search', false, 'dm-menu-icon'), action: () => openChatSearch() },
{ label: 'Медиа и файлы', iconHtml: iconHtml('image', false, 'dm-menu-icon'), action: () => navigate(`chat/${encodeURIComponent(chatId)}/media`) },
{ label: t('screens.chat_view.text_015'), iconHtml: iconHtml('search', false, 'dm-menu-icon'), action: () => openChatSearch() },
{ label: t('screens.chat_view.text_016'), iconHtml: iconHtml('image', false, 'dm-menu-icon'), action: () => navigate(`chat/${encodeURIComponent(chatId)}/media`) },
createDmMuteMenuItem(chatId, { iconClass: 'dm-menu-icon', onChange: (muted) => chatHeaderParts?.setMuted(muted) }),
isDmChatPinned(chatId)
? { label: 'Открепить', iconHtml: iconHtml('pin', false, 'dm-menu-icon'), action: () => toggleChatPinned(false) }
: { label: 'Закрепить', iconHtml: iconHtml('pin', false, 'dm-menu-icon'), action: () => toggleChatPinned(true) },
? { label: t('screens.chat_view.text_017'), iconHtml: iconHtml('pin', false, 'dm-menu-icon'), action: () => toggleChatPinned(false) }
: { label: t('screens.chat_view.text_018'), iconHtml: iconHtml('pin', false, 'dm-menu-icon'), action: () => toggleChatPinned(true) },
normalizeChatRelationType(peerRelationType) === 'none'
? {
label: 'Добавить в контакты',
label: t('screens.chat_view.text_019'),
iconHtml: iconHtml('user-plus', false, 'dm-menu-icon'),
action: async () => {
try {
await addPeerToContacts();
} catch (error) {
showToast(actionErrorText('Не удалось добавить в контакты', error), { kind: 'error' });
showToast(actionErrorText(t('screens.chat_view.text_046'), error), { kind: 'error' });
}
},
}
: null,
{ divider: true },
{
label: 'Очистить историю',
label: t('screens.chat_view.text_020'),
iconHtml: menuIconSvg('clear'),
action: () => openChatConfirmModal({
title: 'Очистить историю?',
text: `Добавить техническое сообщение очистки истории переписки с ${contact.name}?`,
confirmLabel: 'Очистить',
title: t('dialogs.final.chat.confirm_clear_history_title'),
text: t('dialogs.final.chat.confirm_clear_history_text', { name: contact.name }),
confirmLabel: t('dialogs.final.chat.confirm_clear_history_button'),
confirmKind: 'danger',
onConfirm: async () => {
try {
await clearConversationHistory();
showToast('История чата очищена', { timeoutMs: 1200 });
showToast(t('dialogs.final.chat.confirm_clear_history_success'), { timeoutMs: 1200 });
} catch (error) {
showToast(actionErrorText('Не удалось очистить историю', error), { kind: 'error' });
showToast(actionErrorText(t('dialogs.final.chat.confirm_clear_history_error'), error), { kind: 'error' });
}
},
}),
},
{
label: 'Удалить чат',
label: t('screens.chat_view.text_021'),
iconHtml: menuIconSvg('delete'),
danger: true,
action: () => {
@@ -1590,10 +1597,10 @@ export function render({ navigate, route, chrome }) {
|| [],
);
notifyUnreadStateUpdated();
showToast('Чат удалён', { timeoutMs: 1200 });
showToast(t('dialogs.final.chat.confirm_delete_chat_success'), { timeoutMs: 1200 });
navigate('messages-list');
} catch (error) {
showToast(actionErrorText('Не удалось удалить чат', error), { kind: 'error' });
showToast(actionErrorText(t('dialogs.final.chat.confirm_delete_chat_error'), error), { kind: 'error' });
}
},
});
@@ -1610,7 +1617,7 @@ export function render({ navigate, route, chrome }) {
const toggleChatPinned = (pinned) => {
setDmChatPinned(chatId, pinned);
showToast(pinned ? 'Чат закреплён наверху списка' : 'Чат откреплён', { timeoutMs: 1400 });
showToast(pinned ? t('screens.chat_view.text_067') : t('screens.chat_view.text_068'), { timeoutMs: 1400 });
};
@@ -1696,7 +1703,7 @@ export function render({ navigate, route, chrome }) {
const query = normalizeSearchText(search.input.value).trim();
const loading = Boolean(historyFullLoad);
// Номер считается от новых: «1 из 12» – самое свежее совпадение.
search.counter.textContent = !query ? '' : (total ? `${total - search.index} из ${total}` : (loading ? '…' : 'нет'));
search.counter.textContent = !query ? '' : (total ? t('screens.chat_view.text_089', { value1: total - search.index, value2: total }) : (loading ? '…' : t('screens.chat_view.text_069')));
search.counter.classList.toggle('is-empty', Boolean(query) && !total && !loading);
search.upBtn.disabled = !total || search.index <= 0;
search.downBtn.disabled = !total || search.index >= total - 1;
@@ -1752,7 +1759,7 @@ export function render({ navigate, route, chrome }) {
counter.className = 'topbar-search__counter';
counter.setAttribute('aria-live', 'polite');
const searchBar = createSearchTopBar({
placeholder: 'Поиск в переписке',
placeholder: t('screens.chat_view.text_022'),
trailing: counter,
onClose: () => closeChatSearch(),
onInput: () => {
@@ -1769,9 +1776,9 @@ export function render({ navigate, route, chrome }) {
}
},
actions: [
{ id: 'date', icon: 'calendar', title: 'Перейти к дате', ariaLabel: 'Перейти к дате', className: 'chat-header-icon-btn', onClick: () => openDateJump() },
{ id: 'older', icon: 'chevron-up', title: 'Раньше', ariaLabel: 'Предыдущее совпадение', className: 'chat-header-icon-btn', onClick: () => stepSearch(-1) },
{ id: 'newer', icon: 'chevron-down', title: 'Позже', ariaLabel: 'Следующее совпадение', className: 'chat-header-icon-btn', onClick: () => stepSearch(1) },
{ id: 'date', icon: 'calendar', title: t('screens.chat_view.text_023'), ariaLabel: t('screens.chat_view.text_024'), className: 'chat-header-icon-btn', onClick: () => openDateJump() },
{ id: 'older', icon: 'chevron-up', title: t('screens.chat_view.text_025'), ariaLabel: t('screens.chat_view.text_026'), className: 'chat-header-icon-btn', onClick: () => stepSearch(-1) },
{ id: 'newer', icon: 'chevron-down', title: t('screens.chat_view.text_027'), ariaLabel: t('screens.chat_view.text_028'), className: 'chat-header-icon-btn', onClick: () => stepSearch(1) },
],
});
const input = searchBar.searchInput;
@@ -1837,25 +1844,25 @@ export function render({ navigate, route, chrome }) {
form.innerHTML = `
<div class="dm-edit-banner" id="chat-edit-banner" hidden>
<div class="dm-edit-banner__text" id="chat-edit-banner-text"></div>
<button class="ghost-btn dm-edit-banner__close" type="button" id="chat-edit-cancel" title="Отменить редактирование">✕</button>
<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>
<!-- Капсула как строка ответа в обсуждениях. В покое – один ряд: фото · текст · смайлик · отправка.
При вводе текст занимает весь верхний ряд, а все кнопки – нижний (как в терминале Claude). -->
<div class="dm-composer-bar">
<button class="dm-bar-icon dm-media-btn" type="button" id="chat-media-toggle" aria-label="Фото или видео" title="Фото или видео"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('image')}</button>
<button class="dm-bar-icon dm-camera-btn" type="button" id="chat-camera-toggle" aria-label="Камера" title="Камера"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('camera')}</button>
<button class="dm-bar-icon dm-file-btn" type="button" id="chat-file-toggle" aria-label="Файл" title="Файл"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('clip')}</button>
<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">↑ проведите вверх, чтобы закрепить</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="Сообщение" 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>
</div>
<button class="dm-bar-icon dm-emoji-btn" type="button" id="chat-emoji-toggle" aria-label="Эмодзи" title="Эмодзи">${iconHtml('emoji')}</button>
<button class="dm-send-btn dm-send-icon-btn" type="button" title="Записать голосовое сообщение" data-mode="voice" aria-label="Записать голосовое сообщение"></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>
</div>
<input id="chat-file-input" type="file" multiple hidden />
<input id="chat-media-input" type="file" accept="image/*,video/*" multiple hidden />
@@ -2019,24 +2026,24 @@ export function render({ navigate, route, chrome }) {
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
sendBtn.disabled = voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
if (mode === 'send') {
sendBtn.title = 'Отправить';
sendBtn.setAttribute('aria-label', 'Отправить');
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 = 'Остановить и отправить голосовое';
sendBtn.setAttribute('aria-label', 'Остановить и отправить голосовое');
sendBtn.title = t('screens.chat_view.text_030');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030'));
} else if (mode === 'busy') {
sendBtn.title = 'Шифрование и отправка голосового';
sendBtn.setAttribute('aria-label', 'Шифрование и отправка голосового');
sendBtn.title = t('screens.chat_view.text_031');
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_031'));
} else {
sendBtn.title = 'Удерживайте для записи голосового';
sendBtn.setAttribute('aria-label', 'Записать голосовое сообщение');
sendBtn.title = t('screens.chat_view.text_032');
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 = '↑ проведите вверх, чтобы закрепить';
if (!recording && voiceHint) voiceHint.textContent = t('dialogs.modals.chat_view.label_033');
syncVoiceTimer();
};
@@ -2072,15 +2079,15 @@ export function render({ navigate, route, chrome }) {
const startVoiceRecording = async ({ pointerY = 0, pointerId = null } = {}) => {
if (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
if (!fileTransferEnabled) {
showToast('Передача файлов и голосовых отключена в дополнительных настройках.', { kind: 'error', timeoutMs: 1900 });
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
return;
}
if (activeEdit) {
showToast('Сначала завершите редактирование сообщения.', { kind: 'error', timeoutMs: 1600 });
showToast(t('screens.chat_view.text_048'), { kind: 'error', timeoutMs: 1600 });
return;
}
if (!globalThis.MediaRecorder || !navigator.mediaDevices?.getUserMedia) {
showToast('Этот браузер не поддерживает запись голосовых сообщений.', { kind: 'error', timeoutMs: 2400 });
showToast(t('screens.chat_view.text_049'), { kind: 'error', timeoutMs: 2400 });
return;
}
@@ -2113,7 +2120,7 @@ export function render({ navigate, route, chrome }) {
if (event.data?.size > 0) voiceChunks.push(event.data);
});
recorder.addEventListener('error', (event) => {
showToast(actionErrorText('Запись с микрофона прервалась', event?.error), { kind: 'error' });
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
});
recorder.addEventListener('stop', async () => {
const shouldSend = recorder.__shineShouldSend !== false;
@@ -2144,13 +2151,13 @@ export function render({ navigate, route, chrome }) {
onProgress: ({ processedBytes, totalBytes }) => {
if (!totalBytes) return;
const percent = Math.round((processedBytes / totalBytes) * 100);
if (voiceHint) voiceHint.textContent = `Шифрование и загрузка ${Math.min(100, percent)}%`;
if (voiceHint) voiceHint.textContent = t('screens.chat_view.text_090', { value1: Math.min(100, percent) });
},
});
await sendFileAttachmentMessage([attachment]);
showToast('Голосовое отправлено', { timeoutMs: 1200 });
showToast(t('screens.chat_view.text_051'), { timeoutMs: 1200 });
} catch (error) {
showToast(actionErrorText('Голосовое не отправлено', error), { kind: 'error' });
showToast(actionErrorText(t('screens.chat_view.text_052'), error), { kind: 'error' });
} finally {
voiceBusy = false;
updateSendButtonMode();
@@ -2172,7 +2179,7 @@ export function render({ navigate, route, chrome }) {
stopVoiceStreamTracks();
updateSendButtonMode();
const mediaReason = mediaAccessErrorText(error);
showToast(mediaReason ? `Не удалось начать запись. ${mediaReason}` : actionErrorText('Не удалось начать запись', error), { kind: 'error' });
showToast(mediaReason ? t('screens.chat_view.text_091', { value1: mediaReason }) : actionErrorText(t('screens.chat_view.text_053'), error), { kind: 'error' });
}
};
@@ -2214,10 +2221,10 @@ export function render({ navigate, route, chrome }) {
}
editBanner.hidden = false;
if (activeEdit) {
editBannerText.textContent = `Редактируем сообщение: ${truncatePreviewText(activeEdit.originalText, 110)}`;
editBannerText.textContent = t('screens.chat_view.text_092', { value1: truncatePreviewText(activeEdit.originalText, 110) });
return;
}
editBannerText.textContent = `Ответить\n${truncatePreviewText(activeReply?.previewText || '', 110)}`;
editBannerText.textContent = t('screens.chat_view.text_093', { value1: truncatePreviewText(activeReply?.previewText || '', 110) });
};
const focusInputToEnd = () => {
@@ -2441,7 +2448,7 @@ export function render({ navigate, route, chrome }) {
addAppLogEntry({
level: 'info',
source: 'outgoing-dm',
message: editing ? `Сообщение изменено для ${chatId}` : `Сообщение отправлено для ${chatId}`,
message: editing ? t('screens.chat_view.text_094', { value1: chatId }) : t('screens.chat_view.text_095', { value1: chatId }),
details: {
toLogin: chatId,
messageId: result?.outgoingKey || '',
@@ -2460,14 +2467,14 @@ export function render({ navigate, route, chrome }) {
updateSendButtonMode();
focusInputToEnd();
}
showToast(actionErrorText(activeEdit ? 'Изменение не сохранено' : 'Сообщение не отправлено', e), {
showToast(actionErrorText(activeEdit ? t('screens.chat_view.text_070') : t('screens.chat_view.text_071'), e), {
kind: 'error',
action: { label: 'Повторить', onClick: () => { if (!disposed) form.requestSubmit(); } },
action: { label: t('screens.chat_view.text_033'), onClick: () => { if (!disposed) form.requestSubmit(); } },
});
addAppLogEntry({
level: 'warn',
source: 'outgoing-dm',
message: activeEdit ? 'Ошибка редактирования личного сообщения' : 'Ошибка отправки личного сообщения',
message: activeEdit ? t('screens.chat_view.text_072') : t('screens.chat_view.text_073'),
details: {
toLogin: chatId,
error: e?.message || 'unknown',
@@ -2481,17 +2488,17 @@ export function render({ navigate, route, chrome }) {
const attachments = (Array.isArray(attachmentsInput) ? attachmentsInput : [attachmentsInput]).filter(Boolean);
if (!attachments.length) return;
if (attachments.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
throw new Error(`За одно сообщение можно отправить максимум ${DM_MAX_ATTACHMENTS_PER_MESSAGE} файлов`);
throw new Error(t('screens.chat_view.text_096', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }));
}
const replying = activeEdit ? null : activeReply;
const fileBlocks = attachments.map((attachment) => buildDmFileTechBlock(attachment)).join('');
const replyBlock = replying ? buildDmReplyTechBlock({ baseKey: replying.baseKey }) : '';
const onlyVoice = attachments.length === 1 && attachments[0]?.kind === 'voice';
const fallbackText = onlyVoice
? '🎙 Голосовое сообщение'
? t('screens.chat_view.text_074')
: (attachments.length === 1
? `📎 ${String(attachments[0]?.name || 'file')}`
: `📎 Файлы: ${attachments.length}`);
: t('screens.chat_view.text_097', { value1: attachments.length }));
const finalText = `${replyBlock}${fileBlocks}${fallbackText}`;
hideUnreadSeparator({ rerender: false });
@@ -2528,7 +2535,7 @@ export function render({ navigate, route, chrome }) {
addAppLogEntry({
level: 'info',
source: onlyVoice ? 'outgoing-dm-voice' : 'outgoing-dm-file',
message: onlyVoice ? `Голосовое отправлено для ${chatId}` : `Вложения отправлены для ${chatId}`,
message: onlyVoice ? t('screens.chat_view.text_098', { value1: chatId }) : t('screens.chat_view.text_099', { value1: chatId }),
details: {
toLogin: chatId,
attachmentCount: attachments.length,
@@ -2543,7 +2550,7 @@ export function render({ navigate, route, chrome }) {
addAppLogEntry({
level: 'warn',
source: onlyVoice ? 'outgoing-dm-voice' : 'outgoing-dm-file',
message: 'Зашифрованные данные загружены, но DM с ключами не отправлен',
message: t('screens.chat_view.text_034'),
details: {
toLogin: chatId,
fileIds: attachments.map((attachment) => attachment?.id || ''),
@@ -2557,15 +2564,15 @@ export function render({ navigate, route, chrome }) {
// Файлы уже лежат на сервере – повторить можно одно сообщение с ключами, без новой загрузки.
const offerAttachmentsRetry = (attachments, error) => {
showToast(actionErrorText(attachments.length === 1 ? 'Файл не отправлен' : 'Файлы не отправлены', error), {
showToast(actionErrorText(attachments.length === 1 ? t('screens.chat_view.text_075') : t('screens.chat_view.text_076'), error), {
kind: 'error',
action: {
label: 'Повторить',
label: t('screens.chat_view.text_035'),
onClick: async () => {
if (disposed) return;
try {
await sendFileAttachmentMessage(attachments);
if (!disposed) showToast(attachments.length === 1 ? 'Файл отправлен' : `Отправлено файлов: ${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) {
if (!disposed) offerAttachmentsRetry(attachments, again);
}
@@ -2576,17 +2583,17 @@ export function render({ navigate, route, chrome }) {
const handleSelectedFiles = async (fileList) => {
if (!fileTransferEnabled) {
showToast('Передача файлов отключена в дополнительных настройках.', { kind: 'error', timeoutMs: 1800 });
showToast(t('screens.chat_view.text_054'), { kind: 'error', timeoutMs: 1800 });
return;
}
if (activeEdit) {
showToast('Сначала завершите редактирование сообщения.', { kind: 'error', timeoutMs: 1600 });
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) {
showToast(`Выберите не больше ${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;
}
@@ -2594,14 +2601,14 @@ export function render({ navigate, route, chrome }) {
button.disabled = true;
button.classList.add('is-busy');
});
if (fileToggle) fileToggle.setAttribute('aria-label', 'Шифрование и загрузка файлов');
if (fileToggle) fileToggle.setAttribute('aria-label', t('dialogs.modals.chat_view.label_034'));
const attachments = [];
let uploaded = false;
try {
for (let index = 0; index < allFiles.length; index += 1) {
const file = allFiles[index];
showToast(`Файл ${index + 1}/${allFiles.length}: «${String(file.name || 'file')}»`, { kind: 'info', timeoutMs: 1200 });
showToast(t('screens.chat_view.text_102', { value1: index + 1, value2: allFiles.length, value3: String(file.name || 'file') }), { kind: 'info', timeoutMs: 1200 });
const attachment = await encryptAndUploadDmFile({
file,
login: state.session.login,
@@ -2618,18 +2625,18 @@ export function render({ navigate, route, chrome }) {
uploaded = true;
await sendFileAttachmentMessage(attachments);
setFileActionVisible(false);
showToast(attachments.length === 1 ? 'Файл отправлен' : `Отправлено файлов: ${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) {
if (uploaded) offerAttachmentsRetry(attachments, error);
else showToast(actionErrorText(allFiles.length === 1 ? 'Не удалось загрузить файл' : 'Не удалось загрузить файлы', 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 {
attachButtons.forEach((button) => {
button.disabled = false;
button.classList.remove('is-busy');
});
if (fileToggle) {
fileToggle.title = 'Файл';
fileToggle.setAttribute('aria-label', 'Файл');
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 = ''; });
}
@@ -2637,9 +2644,9 @@ export function render({ navigate, route, chrome }) {
const forwardMessageToChat = async (msg, targetLogin) => {
const targetChatId = normalizeDmChatId(targetLogin);
if (!targetChatId) throw new Error('Не выбран чат для пересылки');
if (!targetChatId) throw new Error(t('screens.chat_view.text_081'));
const finalText = buildForwardedDmText(msg);
if (!String(finalText || '').trim()) throw new Error('В этом сообщении нечего пересылать');
if (!String(finalText || '').trim()) throw new Error(t('screens.chat_view.text_082'));
const tempId = addOutgoingPendingMessage(targetChatId, finalText);
if (targetChatId === chatId) {
@@ -2667,7 +2674,7 @@ export function render({ navigate, route, chrome }) {
addAppLogEntry({
level: 'info',
source: 'outgoing-dm-forward',
message: `Сообщение переслано для ${targetChatId}`,
message: t('screens.chat_view.text_104', { value1: targetChatId }),
details: {
toLogin: targetChatId,
sourceChatId: chatId,
@@ -2690,7 +2697,7 @@ export function render({ navigate, route, chrome }) {
anchorY: Number(event?.clientY || 0),
messageText: parsed?.displayText || msg?.text || '',
infoText: (msg?.from === 'out' && readState.readAtMs > 0)
? `Прочитано: ${formatMessageTime(readState.readAtMs)}`
? t('screens.chat_view.text_105', { value1: formatMessageTime(readState.readAtMs) })
: '',
canReply: true,
canForward: true,
@@ -2720,7 +2727,7 @@ export function render({ navigate, route, chrome }) {
try {
await sendDeleteRevision(msg);
} catch (error) {
showToast(actionErrorText('Не удалось удалить сообщение', error), { kind: 'error' });
showToast(actionErrorText(t('dialogs.final.chat.confirm_delete_message_error'), error), { kind: 'error' });
}
},
});
@@ -2780,7 +2787,7 @@ export function render({ navigate, route, chrome }) {
addAppLogEntry({
level: 'warn',
source: 'dm-history',
message: 'Не удалось загрузить историю DM',
message: t('screens.chat_view.text_037'),
details: { chatId, error: error?.message || 'unknown' },
});
} finally {
@@ -2914,7 +2921,7 @@ export function render({ navigate, route, chrome }) {
if (Number(event.clientY || 0) <= voiceStartY - 64) {
voiceLocked = true;
voiceReleaseRequested = false;
if (voiceHint) voiceHint.textContent = 'Запись закреплена · нажмите ■, чтобы отправить';
if (voiceHint) voiceHint.textContent = t('dialogs.modals.chat_view.label_036');
updateSendButtonMode();
try { navigator.vibrate?.(18); } catch { /* ignore */ }
}
@@ -3077,7 +3084,7 @@ async function sendReadReceiptsForVisible(chatId) {
addAppLogEntry({
level: 'warn',
source: 'read-receipt',
message: 'Не удалось отправить подтверждение прочтения',
message: t('screens.chat_view.text_038'),
details: { chatId, messageKey: row.messageKey || '', error: e?.message || 'unknown' },
});
}