SHA256
3187 lines
134 KiB
JavaScript
3187 lines
134 KiB
JavaScript
import { formatDate, formatDateTime } from '../i18n/format.js';
|
||
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';
|
||
import { createDropdownMenu } from '../components/dropdown-menu.js';
|
||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||
import { directMessages } from '../mock-data.js';
|
||
import {
|
||
addAppLogEntry,
|
||
addSignedMessageToChat,
|
||
addOutgoingPendingMessage,
|
||
deleteConversationMessagesBefore,
|
||
getChatMessages,
|
||
markChatRead,
|
||
markOutgoingSent,
|
||
markReadReceiptSentByBaseKey,
|
||
normalizeDmChatId,
|
||
removeOutgoingPending,
|
||
authService,
|
||
getRememberedDmPeer,
|
||
rememberDmPeer,
|
||
setContacts,
|
||
state,
|
||
} from '../state.js';
|
||
import { startOutgoingCall } from '../services/call-service.js';
|
||
import {
|
||
createEmojiPicker,
|
||
createTwemojiAsset,
|
||
appendTwemojiText,
|
||
hasTwemojiAsset,
|
||
stopAllTwemojiAnimations,
|
||
} from '../components/emoji-picker.js?v=202607152130';
|
||
import { isTextToSpeechConfigured, speakTextBySettings } from '../services/speech-tools-service.js';
|
||
import { dayKey, formatClockTime, formatDayLabel, showToast } from '../services/channels-ux.js';
|
||
import { buildDmFileTechBlock, buildDmReplyTechBlock, parseDmTechBlocks, sanitizeUserDmTextForSend } from '../services/dm-tech-blocks.js';
|
||
import { isDmFileTransferEnabled } from '../services/feature-settings.js';
|
||
import {
|
||
decryptDmFileToBlob,
|
||
encryptAndUploadDmFile,
|
||
DM_MAX_ATTACHMENTS_PER_MESSAGE,
|
||
} from '../services/dm-file-service.js';
|
||
import { createAttachmentCarouselElement } from '../services/attachment-format.js';
|
||
import { createDmFileAttachmentCard, createDmExpiredAttachmentCard, isDmInlineMedia, resolveDmMediaUrl } from '../components/dm-attachments.js';
|
||
import { isDmFileExpired } from '../services/dm-file-service.js';
|
||
import {
|
||
DM_HISTORY_PAGE_SIZE,
|
||
isDmHistoryFullyLoaded,
|
||
loadFullDmHistory,
|
||
markDmHistoryFullyLoaded,
|
||
mergeDirectMessagesPage,
|
||
parseBaseKey,
|
||
resolveMessageTimeMs,
|
||
} from '../services/dm-history.js';
|
||
import { DM_CHAT_PREFS_EVENT, isDmChatMuted, isDmChatPinned, setDmChatPinned } from '../services/dm-chat-prefs.js';
|
||
import { createDmMuteMenuItem } from '../components/dm-mute-menu.js';
|
||
import { actionErrorText, mediaAccessErrorText } from '../services/ui-error-texts.js';
|
||
import { scrollNodeIntoContainer } from '../services/scroll-utils.js';
|
||
import { loadProfileSnapshot } from '../services/user-profile-params.js';
|
||
import { makeProfileLinksRoute, makeProfileRoute } from '../services/shine-routes.js';
|
||
import { openHistoryLayer } from '../router.js';
|
||
import { isDmSendEnter } from '../services/dm-composer-keys.js';
|
||
|
||
export const pageMeta = {
|
||
id: 'chat-view',
|
||
get title() { return t('screens.chat_view.text_001'); },
|
||
shellMode: {
|
||
topFade: true,
|
||
bottomFade: true,
|
||
bottomFadeAnchor: 'composer',
|
||
contentUnderTopbar: true,
|
||
contentUnderBottom: true,
|
||
scrollContainer: 'nested',
|
||
},
|
||
};
|
||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||
|
||
function menuIconSvg(name) {
|
||
const paths = {
|
||
reply: '<path d="M9 7 4 12l5 5"/><path d="M5 12h8a6 6 0 0 1 6 6"/>',
|
||
forward: '<path d="m15 7 5 5-5 5"/><path d="M19 12h-8a6 6 0 0 0-6 6"/>',
|
||
copy: '<rect x="8" y="8" width="10" height="10" rx="2"/><path d="M6 15H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1"/>',
|
||
read: '<path d="M5 9v6h4l5 4V5L9 9H5Z"/><path d="M17 9a4 4 0 0 1 0 6"/>',
|
||
edit: '<path d="m4 20 4.4-1 9.9-9.9a2.1 2.1 0 0 0-3-3L5.4 16 4 20Z"/><path d="m13.8 7.2 3 3"/>',
|
||
delete: '<path d="M4 7h16"/><path d="M9 7V4h6v3"/><path d="m7 7 1 13h8l1-13"/>',
|
||
call: '<path d="M7.6 10.8a15 15 0 0 0 5.6 5.6l1.9-1.9a1 1 0 0 1 1-.2c1.1.4 2.3.6 3.5.6a1 1 0 0 1 1 1V20a1 1 0 0 1-1 1C10.6 21 3 13.4 3 4a1 1 0 0 1 1-1h3.4a1 1 0 0 1 1 1c0 1.2.2 2.4.6 3.5a1 1 0 0 1-.3 1l-1.1 1.3Z"/>',
|
||
video: '<rect x="3" y="6" width="13" height="12" rx="2"/><path d="m16 10 5-3v10l-5-3"/>',
|
||
clear: '<path d="M4 7h16"/><path d="M9 7V4h6v3"/><path d="m7 7 1 13h8l1-13"/>',
|
||
};
|
||
return `<svg class="dm-menu-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] || ''}</svg>`;
|
||
}
|
||
|
||
function normalizeChatRelationType(value) {
|
||
const clean = String(value || '').trim().toLowerCase();
|
||
if (clean === 'close_friend' || clean === 'friend' || clean === 'contact') return clean;
|
||
return 'none';
|
||
}
|
||
|
||
function chatRelationLabel(value) {
|
||
switch (normalizeChatRelationType(value)) {
|
||
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 '';
|
||
}
|
||
}
|
||
|
||
function createChatHeaderParts(login, navigate) {
|
||
const cleanLogin = String(login || '').trim() || 'unknown';
|
||
let currentPeer = {
|
||
login: cleanLogin,
|
||
firstName: '',
|
||
lastName: '',
|
||
avatar: null,
|
||
relationType: 'none',
|
||
};
|
||
let muted = false;
|
||
|
||
const identityButton = document.createElement('button');
|
||
identityButton.type = 'button';
|
||
identityButton.className = 'topbar-identity chat-header-peer-btn';
|
||
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';
|
||
const textWrap = document.createElement('span');
|
||
textWrap.className = 'topbar-identity__text chat-header-peer-text';
|
||
const nameEl = document.createElement('span');
|
||
nameEl.className = 'topbar-identity__title chat-header-peer-name';
|
||
const metaEl = document.createElement('span');
|
||
metaEl.className = 'topbar-identity__sub chat-header-peer-meta';
|
||
textWrap.append(nameEl, metaEl);
|
||
identityButton.append(avatarSlot, textWrap);
|
||
|
||
const renderPeer = () => {
|
||
const firstName = String(currentPeer?.firstName || '').trim();
|
||
const lastName = String(currentPeer?.lastName || '').trim();
|
||
const fullName = [firstName, lastName].filter(Boolean).join(' ');
|
||
nameEl.textContent = fullName || cleanLogin;
|
||
if (muted) {
|
||
const mutedIcon = document.createElement('span');
|
||
mutedIcon.className = 'chat-header-muted';
|
||
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' ? t('screens.chat_view.text_059') : '';
|
||
metaEl.textContent = [fullName ? cleanLogin : '', shining, relation].filter(Boolean).join(' · ');
|
||
metaEl.hidden = !metaEl.textContent;
|
||
const avatar = renderUserAvatar({
|
||
login: cleanLogin,
|
||
firstName,
|
||
lastName,
|
||
avatar: (currentPeer?.avatar?.ar || currentPeer?.avatar?.pr)
|
||
? {
|
||
ar: String(currentPeer.avatar.ar || '').trim(),
|
||
pr: String(currentPeer.avatar.pr || '').trim(),
|
||
}
|
||
: null,
|
||
size: 'md',
|
||
className: 'chat-header-avatar',
|
||
title: cleanLogin,
|
||
});
|
||
avatarSlot.replaceChildren(avatar);
|
||
};
|
||
|
||
const updatePeer = (peer) => {
|
||
if (!peer || typeof peer !== 'object') return;
|
||
currentPeer = {
|
||
...currentPeer,
|
||
...peer,
|
||
login: String(peer.login || cleanLogin).trim() || cleanLogin,
|
||
relationType: normalizeChatRelationType(peer.relationType),
|
||
};
|
||
renderPeer();
|
||
};
|
||
|
||
renderPeer();
|
||
const identityMenu = createDropdownMenu({
|
||
transparent: true,
|
||
anchorEl: identityButton,
|
||
placement: 'bottom-start',
|
||
minWidth: 210,
|
||
items: [
|
||
{
|
||
label: t('screens.chat_view.text_003'),
|
||
iconSrc: '/assets/SHiNE_connections_blue.svg',
|
||
action: () => navigate(makeProfileLinksRoute(cleanLogin)),
|
||
},
|
||
{
|
||
label: t('screens.chat_view.text_004'),
|
||
iconSrc: '/assets/profile-icon-profile.svg',
|
||
action: () => navigate(makeProfileRoute(cleanLogin)),
|
||
},
|
||
],
|
||
});
|
||
|
||
return {
|
||
center: identityButton,
|
||
updatePeer,
|
||
setMuted: (value) => {
|
||
muted = Boolean(value);
|
||
renderPeer();
|
||
},
|
||
getPeer: () => ({ ...currentPeer }),
|
||
cleanup: () => identityMenu.destroy(),
|
||
};
|
||
}
|
||
|
||
function truncatePreviewText(value, maxLen = 72) {
|
||
const normalized = String(value || '').replace(/\s+/g, ' ').trim();
|
||
if (!normalized) return '';
|
||
if (normalized.length <= maxLen) return normalized;
|
||
return `${normalized.slice(0, Math.max(0, maxLen - 1)).trimEnd()}…`;
|
||
}
|
||
|
||
function findMessageByBaseKey(messages, baseKey) {
|
||
const normalized = String(baseKey || '').trim();
|
||
if (!normalized) return null;
|
||
return messages.find((row) => String(row?.baseKey || '').trim() === normalized) || null;
|
||
}
|
||
|
||
function openDeleteMessageConfirmModal({ onConfirm }) {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return;
|
||
root.innerHTML = `
|
||
<div class="modal" id="chat-delete-message-modal">
|
||
<div class="modal-card stack">
|
||
<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">${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>
|
||
`;
|
||
|
||
const close = () => {
|
||
root.innerHTML = '';
|
||
};
|
||
|
||
root.querySelector('#chat-delete-message-no')?.addEventListener('click', close);
|
||
root.querySelector('#chat-delete-message-yes')?.addEventListener('click', async () => {
|
||
close();
|
||
if (typeof onConfirm === 'function') await onConfirm();
|
||
});
|
||
}
|
||
|
||
function openChatConfirmModal({
|
||
title = t('dialogs.remaining.pages.chat_view.openchatconfirmmodal.podtverdit_deystvie'),
|
||
text = '',
|
||
confirmLabel = t('dialogs.remaining.pages.chat_view.openchatconfirmmodal.da'),
|
||
confirmKind = 'primary',
|
||
onConfirm,
|
||
}) {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return;
|
||
const confirmClass = confirmKind === 'danger' ? 'destructive-btn' : 'primary-btn';
|
||
root.innerHTML = `
|
||
<div class="modal" id="chat-confirm-modal">
|
||
<div class="modal-card stack">
|
||
<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">${t('dialogs.modals.chat_view.label_003')}</button>
|
||
<button class="${confirmClass}" type="button" id="chat-confirm-yes">${confirmLabel}</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
|
||
const close = () => {
|
||
root.innerHTML = '';
|
||
};
|
||
|
||
root.querySelector('#chat-confirm-no')?.addEventListener('click', close);
|
||
root.querySelector('#chat-confirm-yes')?.addEventListener('click', async () => {
|
||
close();
|
||
if (typeof onConfirm === 'function') await onConfirm();
|
||
});
|
||
}
|
||
|
||
function openExternalLinkModal(href) {
|
||
const root = document.getElementById('modal-root');
|
||
const url = String(href || '').trim();
|
||
if (!root || !/^https?:\/\//i.test(url)) return;
|
||
root.innerHTML = `
|
||
<div class="modal" id="chat-external-link-modal">
|
||
<div class="modal-card stack" role="dialog" aria-modal="true" aria-labelledby="chat-external-link-title">
|
||
<h3 class="modal-title" id="chat-external-link-title">${t('chat_links.title')}</h3>
|
||
<p class="meta-muted">${t('chat_links.description')}</p>
|
||
<p class="chat-external-link-url"></p>
|
||
<div class="form-actions-grid">
|
||
<button class="secondary-btn" type="button" id="chat-external-link-copy">${t('chat_links.copy')}</button>
|
||
<button class="primary-btn" type="button" id="chat-external-link-open">${t('chat_links.open')}</button>
|
||
<button class="secondary-btn" type="button" id="chat-external-link-cancel">${t('chat_links.cancel')}</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
root.querySelector('.chat-external-link-url').textContent = url;
|
||
const close = () => { root.innerHTML = ''; };
|
||
root.querySelector('#chat-external-link-cancel')?.addEventListener('click', close);
|
||
root.querySelector('#chat-external-link-open')?.addEventListener('click', () => {
|
||
window.open(url, '_blank', 'noopener,noreferrer');
|
||
close();
|
||
});
|
||
root.querySelector('#chat-external-link-copy')?.addEventListener('click', async () => {
|
||
try {
|
||
if (!navigator?.clipboard?.writeText) throw new Error('clipboard_unavailable');
|
||
await navigator.clipboard.writeText(url);
|
||
close();
|
||
showToast(t('chat_links.copied'), { timeoutMs: 1200 });
|
||
} catch {
|
||
showToast(t('chat_links.copy_failed'), { kind: 'error', timeoutMs: 1600 });
|
||
}
|
||
});
|
||
}
|
||
|
||
// Календарь «перейти к дате»: активны только дни, в которые была переписка.
|
||
// days – Map dayKey → { timeMs, count }; список можно обновить, пока догружается история.
|
||
// «октябрь 2026 г.» → «Октябрь 2026 г.» (CSS capitalize сделал бы «Г.»)
|
||
function capitalize(text) {
|
||
const value = String(text || '');
|
||
return value.charAt(0).toUpperCase() + value.slice(1);
|
||
}
|
||
|
||
function openDateJumpModal({ days = new Map(), loading = false, onPick } = {}) {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return null;
|
||
const monthTitle = (date) => formatDate(date, { month: 'long', year: 'numeric' });
|
||
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));
|
||
const earliestTime = () => Math.min(Date.now(), ...Array.from(currentDays.values(), (d) => d.timeMs));
|
||
const start = new Date(latestTime() || Date.now());
|
||
let viewYear = start.getFullYear();
|
||
let viewMonth = start.getMonth();
|
||
|
||
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="${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="${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="${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">${t('dialogs.modals.chat_view.label_008')}</button>
|
||
</div>
|
||
</div>
|
||
`;
|
||
const modal = root.querySelector('#chat-date-jump-modal');
|
||
const titleEl = root.querySelector('.dm-date-jump__title');
|
||
const grid = root.querySelector('.dm-date-jump__grid');
|
||
const note = root.querySelector('.dm-date-jump__note');
|
||
const [prevBtn, nextBtn] = root.querySelectorAll('.dm-date-jump__nav');
|
||
const monthIndex = (t) => { const d = new Date(t); return d.getFullYear() * 12 + d.getMonth(); };
|
||
|
||
const renderMonth = () => {
|
||
titleEl.textContent = capitalize(monthTitle(new Date(viewYear, viewMonth, 1)));
|
||
const current = viewYear * 12 + viewMonth;
|
||
prevBtn.disabled = current <= monthIndex(earliestTime());
|
||
nextBtn.disabled = current >= monthIndex(Date.now());
|
||
grid.replaceChildren(...weekdays.map((name) => {
|
||
const cell = document.createElement('span');
|
||
cell.className = 'dm-date-jump__weekday';
|
||
cell.textContent = name;
|
||
return cell;
|
||
}));
|
||
const firstWeekday = (new Date(viewYear, viewMonth, 1).getDay() + 6) % 7;
|
||
for (let i = 0; i < firstWeekday; i += 1) grid.append(document.createElement('span'));
|
||
const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate();
|
||
const todayKey = dayKey(Date.now());
|
||
for (let day = 1; day <= daysInMonth; day += 1) {
|
||
const key = `${viewYear}-${viewMonth}-${day}`;
|
||
const info = currentDays.get(key);
|
||
const btn = document.createElement('button');
|
||
btn.type = 'button';
|
||
btn.className = `dm-date-jump__day${info ? ' has-messages' : ''}${key === todayKey ? ' is-today' : ''}`;
|
||
btn.textContent = String(day);
|
||
btn.disabled = !info;
|
||
if (info) {
|
||
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);
|
||
});
|
||
}
|
||
grid.append(btn);
|
||
}
|
||
note.textContent = isLoading ? t('dialogs.modals.chat_view.label_016') : '';
|
||
note.hidden = !isLoading;
|
||
};
|
||
|
||
const onKey = (event) => { if (event.key === 'Escape') close(); };
|
||
let closed = false;
|
||
function close() {
|
||
if (closed) return;
|
||
closed = true;
|
||
document.removeEventListener('keydown', onKey);
|
||
if (root.contains(modal)) root.innerHTML = '';
|
||
}
|
||
prevBtn.addEventListener('click', () => { viewMonth -= 1; if (viewMonth < 0) { viewMonth = 11; viewYear -= 1; } renderMonth(); });
|
||
nextBtn.addEventListener('click', () => { viewMonth += 1; if (viewMonth > 11) { viewMonth = 0; viewYear += 1; } renderMonth(); });
|
||
root.querySelector('#chat-date-jump-close')?.addEventListener('click', close);
|
||
modal.addEventListener('click', (event) => { if (event.target === modal) close(); });
|
||
document.addEventListener('keydown', onKey);
|
||
renderMonth();
|
||
|
||
return {
|
||
close,
|
||
update({ days: nextDays = currentDays, loading: nextLoading = false } = {}) {
|
||
if (closed) return;
|
||
currentDays = nextDays;
|
||
isLoading = nextLoading;
|
||
renderMonth();
|
||
},
|
||
};
|
||
}
|
||
|
||
function escapeDialogHtml(value) {
|
||
return String(value ?? '').replace(/[&<>"']/g, (char) => ({
|
||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||
}[char]));
|
||
}
|
||
|
||
function openDeleteChatConfirmModal({ contactName = '', relationType = 'none', onConfirm }) {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return;
|
||
const relation = normalizeChatRelationType(relationType);
|
||
const isCloseFriend = relation === 'close_friend';
|
||
const isFriend = relation === 'friend';
|
||
const isProtectedRelation = isCloseFriend || isFriend;
|
||
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">${t('dialogs.modals.chat_view.label_009')}</h3>
|
||
${isProtectedRelation ? `
|
||
<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">${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>${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">${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>
|
||
`;
|
||
|
||
const close = () => {
|
||
root.innerHTML = '';
|
||
};
|
||
|
||
root.querySelector('#chat-delete-chat-no')?.addEventListener('click', close);
|
||
root.querySelector('#chat-delete-chat-yes')?.addEventListener('click', async () => {
|
||
const deleteHistory = isProtectedRelation
|
||
? true
|
||
: Boolean(root.querySelector('#chat-delete-chat-history')?.checked);
|
||
close();
|
||
if (typeof onConfirm === 'function') {
|
||
await onConfirm({ deleteHistory, removeRelation: isProtectedRelation });
|
||
}
|
||
});
|
||
}
|
||
|
||
function buildForwardedDmText(message = {}) {
|
||
const parsed = parseDmTechBlocks(String(message?.text || ''));
|
||
const attachments = Array.isArray(parsed?.fileAttachments) ? parsed.fileAttachments : [];
|
||
const attachmentBlocks = attachments.map((attachment) => buildDmFileTechBlock(attachment)).join('');
|
||
const visibleText = sanitizeUserDmTextForSend(String(parsed?.displayText || parsed?.visibleText || '').trim());
|
||
if (attachmentBlocks) {
|
||
const fallback = visibleText || (attachments.length === 1
|
||
? `📎 ${String(attachments[0]?.name || 'file')}`
|
||
: t('screens.chat_view.text_085', { value1: attachments.length }));
|
||
return `${attachmentBlocks}${fallback}`;
|
||
}
|
||
return visibleText;
|
||
}
|
||
|
||
function clipForwardPreview(text = '', maxLen = 130) {
|
||
const normalized = String(text || '').replace(/\s+/g, ' ').trim();
|
||
if (normalized.length <= maxLen) return normalized;
|
||
return `${normalized.slice(0, Math.max(1, maxLen - 1))}…`;
|
||
}
|
||
|
||
async function openForwardMessageDialog({ message, sourceChatId = '', onConfirm } = {}) {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return;
|
||
|
||
const parsed = parseDmTechBlocks(String(message?.text || ''));
|
||
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">${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="${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="${t('dialogs.modals.chat_view.label_010')}"></span></div></div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
|
||
const close = () => { root.innerHTML = ''; };
|
||
root.querySelector('#chat-forward-close')?.addEventListener('click', close);
|
||
root.querySelector('#chat-forward-modal')?.addEventListener('click', (event) => {
|
||
if (event.target?.id === 'chat-forward-modal') close();
|
||
});
|
||
|
||
const previewEl = root.querySelector('#chat-forward-preview');
|
||
if (previewEl) {
|
||
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');
|
||
if (!list) return;
|
||
|
||
try {
|
||
const payload = await authService.listContacts();
|
||
if (!root.querySelector('#chat-forward-modal')) return;
|
||
const dialogs = Array.isArray(payload?.dialogs) ? payload.dialogs : [];
|
||
const byLogin = new Map();
|
||
dialogs.forEach((dialog) => {
|
||
const peerLogin = normalizeDmChatId(dialog?.peerLogin);
|
||
if (!peerLogin) return;
|
||
byLogin.set(peerLogin.toLowerCase(), {
|
||
peerLogin,
|
||
firstName: String(dialog?.firstName || '').trim(),
|
||
lastName: String(dialog?.lastName || '').trim(),
|
||
lastMessageTimeMs: Number(dialog?.lastMessageTimeMs || 0),
|
||
});
|
||
});
|
||
Object.keys(state.chats || {}).forEach((chatKey) => {
|
||
const peerLogin = normalizeDmChatId(chatKey);
|
||
if (!peerLogin) return;
|
||
const key = peerLogin.toLowerCase();
|
||
if (!byLogin.has(key)) byLogin.set(key, { peerLogin, firstName: '', lastName: '', lastMessageTimeMs: 0 });
|
||
});
|
||
const sourceLogin = normalizeDmChatId(sourceChatId);
|
||
if (sourceLogin && !byLogin.has(sourceLogin.toLowerCase())) {
|
||
byLogin.set(sourceLogin.toLowerCase(), { peerLogin: sourceLogin, firstName: '', lastName: '', lastMessageTimeMs: 0 });
|
||
}
|
||
|
||
const rows = Array.from(byLogin.values()).sort((a, b) => {
|
||
const timeDiff = Number(b.lastMessageTimeMs || 0) - Number(a.lastMessageTimeMs || 0);
|
||
if (timeDiff) return timeDiff;
|
||
return a.peerLogin.localeCompare(b.peerLogin, 'ru');
|
||
});
|
||
list.replaceChildren();
|
||
if (!rows.length) {
|
||
const empty = document.createElement('div');
|
||
empty.className = 'meta-muted dm-forward-loading';
|
||
empty.textContent = t('dialogs.modals.chat_view.label_018');
|
||
list.append(empty);
|
||
return;
|
||
}
|
||
|
||
rows.forEach((item) => {
|
||
const fullName = [item.firstName, item.lastName].filter(Boolean).join(' ');
|
||
const row = document.createElement('button');
|
||
row.type = 'button';
|
||
row.className = 'ui-button dm-forward-chat-row';
|
||
|
||
const avatar = renderUserAvatar({
|
||
login: item.peerLogin,
|
||
firstName: item.firstName,
|
||
lastName: item.lastName,
|
||
size: 'md',
|
||
className: 'dm-forward-avatar',
|
||
title: item.peerLogin,
|
||
});
|
||
const copy = document.createElement('span');
|
||
copy.className = 'dm-forward-chat-copy';
|
||
const name = document.createElement('strong');
|
||
name.textContent = fullName || item.peerLogin;
|
||
const login = document.createElement('span');
|
||
login.className = 'meta-muted';
|
||
login.textContent = item.peerLogin;
|
||
copy.append(name, login);
|
||
const arrow = document.createElement('span');
|
||
arrow.className = 'dm-forward-chat-arrow';
|
||
arrow.textContent = '›';
|
||
row.append(avatar, copy, arrow);
|
||
|
||
row.addEventListener('click', () => {
|
||
const card = root.querySelector('.dm-forward-card');
|
||
if (!card) return;
|
||
card.innerHTML = '';
|
||
|
||
const confirmTitle = document.createElement('h3');
|
||
confirmTitle.className = 'modal-title';
|
||
confirmTitle.textContent = t('dialogs.modals.chat_view.label_019');
|
||
const recipient = document.createElement('div');
|
||
recipient.className = 'dm-forward-confirm-peer';
|
||
recipient.append(
|
||
renderUserAvatar({ login: item.peerLogin, firstName: item.firstName, lastName: item.lastName, size: 'lg' }),
|
||
);
|
||
const recipientCopy = document.createElement('div');
|
||
const recipientName = document.createElement('strong');
|
||
recipientName.textContent = fullName || item.peerLogin;
|
||
const recipientLogin = document.createElement('div');
|
||
recipientLogin.className = 'meta-muted';
|
||
recipientLogin.textContent = item.peerLogin;
|
||
recipientCopy.append(recipientName, recipientLogin);
|
||
recipient.append(recipientCopy);
|
||
|
||
const confirmPreview = document.createElement('div');
|
||
confirmPreview.className = 'dm-forward-preview dm-forward-preview--confirm';
|
||
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 = t('dialogs.modals.chat_view.label_020');
|
||
const confirm = document.createElement('button');
|
||
confirm.type = 'button';
|
||
confirm.className = 'primary-btn';
|
||
confirm.textContent = t('dialogs.modals.chat_view.label_021');
|
||
actions.append(back, confirm);
|
||
card.append(confirmTitle, recipient, confirmPreview, actions);
|
||
|
||
back.addEventListener('click', () => {
|
||
close();
|
||
void openForwardMessageDialog({ message, sourceChatId, onConfirm });
|
||
});
|
||
confirm.addEventListener('click', async () => {
|
||
if (confirm.disabled) return;
|
||
confirm.disabled = true;
|
||
back.disabled = true;
|
||
confirm.textContent = t('dialogs.modals.chat_view.label_022');
|
||
try {
|
||
await onConfirm?.(item.peerLogin);
|
||
close();
|
||
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 = t('dialogs.modals.chat_view.label_021');
|
||
showToast(actionErrorText(t('dialogs.remaining.pages.chat_view.openforwardmessagedialog.ne_udalos_pereslat_soobschenie'), error), { kind: 'error' });
|
||
}
|
||
});
|
||
});
|
||
list.append(row);
|
||
});
|
||
} catch (error) {
|
||
list.replaceChildren();
|
||
const fail = document.createElement('div');
|
||
fail.className = 'meta-muted dm-forward-loading';
|
||
fail.textContent = actionErrorText(t('dialogs.modals.chat_view.label_023'), error);
|
||
list.append(fail);
|
||
}
|
||
}
|
||
|
||
function openMessageActionsMenu({
|
||
anchorX = 0,
|
||
anchorY = 0,
|
||
messageText = '',
|
||
infoText = '',
|
||
canReply = false,
|
||
canForward = true,
|
||
showReadAloud = true,
|
||
canEdit = false,
|
||
canDelete = false,
|
||
onReply,
|
||
onForward,
|
||
onReadAloud,
|
||
onEdit,
|
||
onDelete,
|
||
}) {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return;
|
||
|
||
const menuId = `chat-message-actions-menu-${Date.now()}`;
|
||
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>${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>
|
||
`;
|
||
|
||
const menu = root.querySelector(`#${menuId}`);
|
||
if (!menu) return;
|
||
|
||
const close = () => {
|
||
document.removeEventListener('pointerdown', onDocumentPointerDown, true);
|
||
window.removeEventListener('resize', close);
|
||
window.removeEventListener('scroll', close, true);
|
||
root.innerHTML = '';
|
||
};
|
||
|
||
const onDocumentPointerDown = (event) => {
|
||
if (menu.contains(event.target)) return;
|
||
close();
|
||
};
|
||
|
||
document.addEventListener('pointerdown', onDocumentPointerDown, true);
|
||
window.addEventListener('resize', close);
|
||
window.addEventListener('scroll', close, true);
|
||
|
||
window.requestAnimationFrame(() => {
|
||
const menuRect = menu.getBoundingClientRect();
|
||
const viewportWidth = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
|
||
const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
|
||
const left = Math.min(
|
||
Math.max(12, Number(anchorX || 0) - (menuRect.width / 2)),
|
||
Math.max(12, viewportWidth - menuRect.width - 12)
|
||
);
|
||
const top = Math.min(
|
||
Math.max(12, Number(anchorY || 0) + 10),
|
||
Math.max(12, viewportHeight - menuRect.height - 12)
|
||
);
|
||
menu.style.left = `${left}px`;
|
||
menu.style.top = `${top}px`;
|
||
menu.style.transformOrigin = `${Math.round(Number(anchorX || left) - left)}px top`;
|
||
menu.classList.add('is-visible');
|
||
});
|
||
|
||
root.querySelector('#msg-action-copy')?.addEventListener('click', async () => {
|
||
try {
|
||
if (navigator?.clipboard?.writeText) {
|
||
await navigator.clipboard.writeText(String(messageText || ''));
|
||
}
|
||
showToast(t('screens.chat_view.text_039'), { timeoutMs: 1000 });
|
||
} catch {
|
||
showToast(t('screens.chat_view.text_040'), { kind: 'error', timeoutMs: 1200 });
|
||
} finally {
|
||
close();
|
||
}
|
||
});
|
||
|
||
root.querySelector('#msg-action-reply')?.addEventListener('click', async () => {
|
||
close();
|
||
if (typeof onReply === 'function') await onReply();
|
||
});
|
||
|
||
root.querySelector('#msg-action-forward')?.addEventListener('click', async () => {
|
||
close();
|
||
if (typeof onForward === 'function') await onForward();
|
||
});
|
||
|
||
root.querySelector('#msg-action-read')?.addEventListener('click', async () => {
|
||
close();
|
||
if (typeof onReadAloud === 'function') await onReadAloud();
|
||
});
|
||
|
||
root.querySelector('#msg-action-edit')?.addEventListener('click', async () => {
|
||
close();
|
||
if (typeof onEdit === 'function') await onEdit();
|
||
});
|
||
|
||
root.querySelector('#msg-action-delete')?.addEventListener('click', async () => {
|
||
close();
|
||
if (typeof onDelete === 'function') await onDelete();
|
||
});
|
||
}
|
||
|
||
function showTtsMissingConfigDialog() {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return;
|
||
root.innerHTML = `
|
||
<div class="modal" id="chat-tts-missing-modal">
|
||
<div class="modal-card stack">
|
||
<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>
|
||
</div>
|
||
</div>
|
||
`;
|
||
const close = () => { root.innerHTML = ''; };
|
||
root.querySelector('#chat-tts-ok')?.addEventListener('click', close);
|
||
}
|
||
|
||
// Высоту меряем по скрытой копии поля: так поле не сбрасывается в auto и растёт плавно (transition в chat.css).
|
||
const composerMeasures = new WeakMap();
|
||
function composerMeasure(textarea) {
|
||
let measure = composerMeasures.get(textarea);
|
||
if (!measure || !measure.isConnected) {
|
||
measure = textarea.cloneNode(false);
|
||
measure.removeAttribute('name');
|
||
measure.removeAttribute('id');
|
||
measure.tabIndex = -1;
|
||
measure.setAttribute('aria-hidden', 'true');
|
||
measure.classList.add('dm-input-measure');
|
||
measure.removeAttribute('style');
|
||
textarea.after(measure);
|
||
composerMeasures.set(textarea, measure);
|
||
}
|
||
return measure;
|
||
}
|
||
|
||
function autoResizeComposer(textarea) {
|
||
if (!textarea) return;
|
||
const measure = composerMeasure(textarea);
|
||
measure.style.width = `${textarea.offsetWidth}px`;
|
||
measure.value = textarea.value || ' ';
|
||
const style = getComputedStyle(textarea);
|
||
const borders = (Number.parseFloat(style.borderTopWidth) || 0) + (Number.parseFloat(style.borderBottomWidth) || 0);
|
||
const next = Math.min(180, Math.max(44, measure.scrollHeight + borders));
|
||
if (textarea.style.height !== `${next}px`) textarea.style.height = `${next}px`;
|
||
}
|
||
|
||
function createHeaderPhoneHandsetIcon() {
|
||
const ns = 'http://www.w3.org/2000/svg';
|
||
const svg = document.createElementNS(ns, 'svg');
|
||
svg.setAttribute('viewBox', '0 0 24 24');
|
||
svg.setAttribute('aria-hidden', 'true');
|
||
svg.setAttribute('class', 'header-icon-svg header-icon-svg--phone');
|
||
|
||
const path = document.createElementNS(ns, 'path');
|
||
path.setAttribute('d', 'M7.62 10.79a15.1 15.1 0 0 0 5.59 5.59l1.87-1.87a1 1 0 0 1 1.02-.24c1.12.37 2.31.57 3.52.57a1 1 0 0 1 1 1V20a1 1 0 0 1-1 1C10.61 21 3 13.39 3 4a1 1 0 0 1 1-1h3.37a1 1 0 0 1 1 1c0 1.21.2 2.4.57 3.52a1 1 0 0 1-.24 1.02l-1.08 1.27Z');
|
||
path.setAttribute('fill', 'currentColor');
|
||
svg.append(path);
|
||
return svg;
|
||
}
|
||
|
||
function openConfirmContactModal(targetLogin = '') {
|
||
const root = document.getElementById('modal-root');
|
||
if (!root) return Promise.resolve(false);
|
||
return new Promise((resolve) => {
|
||
root.innerHTML = `
|
||
<div class="modal" id="contact-confirm-modal">
|
||
<div class="modal-card stack">
|
||
<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">${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>
|
||
`;
|
||
|
||
const close = (answer) => {
|
||
root.innerHTML = '';
|
||
resolve(!!answer);
|
||
};
|
||
root.querySelector('#contact-confirm-no')?.addEventListener('click', () => close(false));
|
||
root.querySelector('#contact-confirm-yes')?.addEventListener('click', () => close(true));
|
||
});
|
||
}
|
||
|
||
|
||
|
||
function formatMessageTime(valueMs) {
|
||
const timeMs = Number(valueMs || 0);
|
||
if (!Number.isFinite(timeMs) || timeMs <= 0) return '';
|
||
return formatDateTime(new Date(timeMs), {
|
||
day: '2-digit',
|
||
month: '2-digit',
|
||
year: '2-digit',
|
||
hour: '2-digit',
|
||
minute: '2-digit',
|
||
});
|
||
}
|
||
|
||
function formatCallDurationCompact(totalSeconds) {
|
||
const total = Math.max(0, Math.floor(Number(totalSeconds || 0)));
|
||
const hours = Math.floor(total / 3600);
|
||
const minutes = Math.floor((total % 3600) / 60);
|
||
const seconds = total % 60;
|
||
if (hours > 0) {
|
||
return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
||
}
|
||
return `${minutes}:${String(seconds).padStart(2, '0')}`;
|
||
}
|
||
|
||
function buildCallStatusText(callSummary) {
|
||
if (!callSummary) return '';
|
||
if (callSummary.status === 'completed') {
|
||
return t('screens.chat_view.text_086', { value1: formatCallDurationCompact(callSummary.durationSec) });
|
||
}
|
||
const reason = String(callSummary.reason || '').trim().toLowerCase();
|
||
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) {
|
||
if (msg?.from !== 'out') return { isRead: false, readAtMs: 0 };
|
||
const explicitReadAtMs = Number(msg?.readAtMs || 0);
|
||
if (Number.isFinite(explicitReadAtMs) && explicitReadAtMs > 0) {
|
||
return { isRead: true, readAtMs: explicitReadAtMs };
|
||
}
|
||
if (msg?.secondTick) {
|
||
return { isRead: true, readAtMs: 0 };
|
||
}
|
||
const messageTimeMs = resolveMessageTimeMs(msg);
|
||
const hasNewerRead = (messages || []).some((row) => {
|
||
if (row?.from !== 'out') return false;
|
||
if (resolveMessageTimeMs(row) <= messageTimeMs) return false;
|
||
return Boolean(Number(row?.readAtMs || 0) > 0 || row?.secondTick);
|
||
});
|
||
return { isRead: hasNewerRead, readAtMs: 0 };
|
||
}
|
||
|
||
function resolveDeliveryStatus(messages, msg) {
|
||
if (msg?.from !== 'out') return '';
|
||
if (resolveEffectiveReadState(messages, msg).isRead) return '✓✓';
|
||
const deliveryState = String(msg?.deliveryState || '').trim().toLowerCase();
|
||
if (deliveryState === 'delivered') return '✓';
|
||
if (deliveryState === 'failed') return '!';
|
||
if (deliveryState === 'accepted' || msg?.firstTick) return '✓';
|
||
return '…';
|
||
}
|
||
|
||
// Статус сообщения — иконкой и словом для экранного чтения (цвет не единственный носитель смысла)
|
||
const DELIVERY_STATUS_VIEW = {
|
||
'✓✓': { 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) {
|
||
if (resolveEffectiveReadState(messages, msg).isRead) return 'read';
|
||
const deliveryState = String(msg?.deliveryState || '').trim().toLowerCase();
|
||
if (deliveryState === 'delivered') return 'delivered';
|
||
if (deliveryState === 'failed') return 'failed';
|
||
return 'accepted';
|
||
}
|
||
|
||
function resolveDeliveryNote(msg) {
|
||
if (msg?.from !== 'out') return '';
|
||
const deliveryState = String(msg?.deliveryState || '').trim().toLowerCase();
|
||
if (deliveryState === 'failed') return t('screens.chat_view.text_066');
|
||
return '';
|
||
}
|
||
|
||
function resolveMessageEditedTimeMs(msg) {
|
||
const revisionTimeMs = Number(msg?.revisionTimeMs || 0);
|
||
if (!Number.isFinite(revisionTimeMs) || revisionTimeMs <= 0) return 0;
|
||
return revisionTimeMs;
|
||
}
|
||
|
||
// Прокручивается лента (.dm-chat-wrap), а не .screen-content: у того overflow скрыт,
|
||
// и прокрутка «к последнему» оставляла последнее сообщение под панелью ввода.
|
||
function findChatScrollContainer(list) {
|
||
return list.closest('.dm-chat-wrap') || list.closest('.screen-content') || list.parentElement || list;
|
||
}
|
||
|
||
function scrollToLatestMessage(list) {
|
||
if (!list) return;
|
||
const scrollContainer = findChatScrollContainer(list);
|
||
const lastBubble = list.lastElementChild;
|
||
const apply = () => {
|
||
scrollNodeIntoContainer(lastBubble, { container: scrollContainer, block: 'end' });
|
||
scrollContainer.scrollTop = scrollContainer.scrollHeight;
|
||
};
|
||
apply();
|
||
window.requestAnimationFrame(apply);
|
||
window.requestAnimationFrame(() => window.requestAnimationFrame(apply));
|
||
window.setTimeout(apply, 0);
|
||
window.setTimeout(apply, 60);
|
||
window.setTimeout(apply, 120);
|
||
window.setTimeout(apply, 260);
|
||
}
|
||
|
||
function renderMessageText(textNode, messageText, chatNavigate) {
|
||
const text = String(messageText || '');
|
||
const emoji = text.trim();
|
||
if (text === emoji && hasTwemojiAsset(emoji)) {
|
||
textNode.classList.add('bubble-text--twemoji-only');
|
||
textNode.append(createTwemojiAsset(emoji, { className: 'chat-twemoji' }));
|
||
return;
|
||
}
|
||
appendShineMessageLinks(textNode, text, {
|
||
navigate: chatNavigate,
|
||
onExternalLink: ({ href }) => openExternalLinkModal(href),
|
||
appendText: (root, part) => {
|
||
const fragment = document.createDocumentFragment();
|
||
if (appendTwemojiText(fragment, part, { className: 'chat-twemoji chat-twemoji--inline' })) {
|
||
textNode.classList.add('bubble-text--twemoji-inline');
|
||
}
|
||
root.append(fragment);
|
||
},
|
||
});
|
||
}
|
||
|
||
function isTwemojiOnlyMessage(messageText) {
|
||
const emoji = String(messageText || '').trim();
|
||
return Boolean(emoji && String(messageText || '') === emoji && hasTwemojiAsset(emoji));
|
||
}
|
||
|
||
|
||
function formatVoiceDuration(durationMs = 0) {
|
||
const total = Math.max(0, Math.round(Number(durationMs || 0) / 1000));
|
||
const minutes = Math.floor(total / 60);
|
||
const seconds = total % 60;
|
||
return `${minutes}:${String(seconds).padStart(2, '0')}`;
|
||
}
|
||
|
||
function createDmVoiceAttachmentCard(attachment) {
|
||
const card = document.createElement('div');
|
||
card.className = 'dm-voice-card';
|
||
|
||
const playBtn = document.createElement('button');
|
||
playBtn.type = 'button';
|
||
playBtn.className = 'ui-button dm-voice-card__play';
|
||
playBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_024'));
|
||
playBtn.textContent = '▶';
|
||
|
||
const body = document.createElement('div');
|
||
body.className = 'dm-voice-card__body';
|
||
const track = document.createElement('button');
|
||
track.type = 'button';
|
||
track.className = 'ui-button dm-voice-card__track';
|
||
track.setAttribute('aria-label', t('dialogs.modals.chat_view.label_025'));
|
||
const fill = document.createElement('span');
|
||
fill.className = 'dm-voice-card__fill';
|
||
track.append(fill);
|
||
|
||
const meta = document.createElement('div');
|
||
meta.className = 'dm-voice-card__meta';
|
||
const duration = document.createElement('span');
|
||
duration.textContent = formatVoiceDuration(attachment?.durationMs || 0);
|
||
const label = document.createElement('span');
|
||
label.textContent = t('dialogs.modals.chat_view.label_026');
|
||
meta.append(duration, label);
|
||
body.append(track, meta);
|
||
card.append(playBtn, body);
|
||
|
||
let audio = null;
|
||
let objectUrl = '';
|
||
let loading = false;
|
||
|
||
const syncProgress = () => {
|
||
if (!audio) return;
|
||
if (!card.isConnected) {
|
||
try { audio.pause(); } catch { /* ignore */ }
|
||
if (objectUrl) {
|
||
URL.revokeObjectURL(objectUrl);
|
||
objectUrl = '';
|
||
}
|
||
return;
|
||
}
|
||
const total = Number.isFinite(audio.duration) && audio.duration > 0
|
||
? audio.duration
|
||
: Math.max(0, Number(attachment?.durationMs || 0) / 1000);
|
||
const current = Math.max(0, Number(audio.currentTime || 0));
|
||
fill.style.width = `${total > 0 ? Math.min(100, (current / total) * 100) : 0}%`;
|
||
duration.textContent = `${formatVoiceDuration(current * 1000)} / ${formatVoiceDuration(total * 1000)}`;
|
||
playBtn.textContent = audio.paused ? '▶' : 'Ⅱ';
|
||
};
|
||
|
||
const ensureAudio = async () => {
|
||
if (audio) return audio;
|
||
if (loading) return null;
|
||
loading = true;
|
||
playBtn.disabled = true;
|
||
playBtn.textContent = '…';
|
||
try {
|
||
const blob = await decryptDmFileToBlob(attachment);
|
||
objectUrl = URL.createObjectURL(blob);
|
||
audio = new Audio(objectUrl);
|
||
audio.preload = 'metadata';
|
||
audio.addEventListener('timeupdate', syncProgress);
|
||
audio.addEventListener('loadedmetadata', syncProgress);
|
||
audio.addEventListener('play', syncProgress);
|
||
audio.addEventListener('pause', syncProgress);
|
||
audio.addEventListener('ended', syncProgress);
|
||
audio.addEventListener('error', () => {
|
||
showToast(t('screens.chat_view.text_041'), { kind: 'error', timeoutMs: 2200 });
|
||
});
|
||
return audio;
|
||
} finally {
|
||
loading = false;
|
||
playBtn.disabled = false;
|
||
if (!audio) playBtn.textContent = '▶';
|
||
}
|
||
};
|
||
|
||
playBtn.addEventListener('click', async (event) => {
|
||
event.stopPropagation();
|
||
try {
|
||
const player = await ensureAudio();
|
||
if (!player) return;
|
||
if (player.paused) await player.play();
|
||
else player.pause();
|
||
syncProgress();
|
||
} catch (error) {
|
||
showToast(actionErrorText(t('screens.chat_view.text_042'), error), { kind: 'error' });
|
||
}
|
||
});
|
||
|
||
track.addEventListener('click', async (event) => {
|
||
event.stopPropagation();
|
||
try {
|
||
const player = await ensureAudio();
|
||
if (!player || !Number.isFinite(player.duration) || player.duration <= 0) return;
|
||
const rect = track.getBoundingClientRect();
|
||
const ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / Math.max(1, rect.width)));
|
||
player.currentTime = player.duration * ratio;
|
||
syncProgress();
|
||
} catch (error) {
|
||
showToast(actionErrorText(t('screens.chat_view.text_043'), error), { kind: 'error' });
|
||
}
|
||
});
|
||
|
||
return card;
|
||
}
|
||
|
||
function scrollToLatestMessageSmart(list, { smoothIfNearBottom = false } = {}) {
|
||
if (!list) return;
|
||
const scrollContainer = findChatScrollContainer(list);
|
||
const maxScrollTop = Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight);
|
||
const distanceToBottom = Math.max(0, maxScrollTop - scrollContainer.scrollTop);
|
||
const useSmooth = smoothIfNearBottom && distanceToBottom <= 180;
|
||
|
||
const apply = (behavior = useSmooth ? 'smooth' : 'auto') => {
|
||
if (behavior === 'smooth' && typeof scrollContainer.scrollTo === 'function') {
|
||
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior: 'smooth' });
|
||
} else {
|
||
scrollContainer.scrollTop = scrollContainer.scrollHeight;
|
||
}
|
||
};
|
||
|
||
apply(useSmooth ? 'smooth' : 'auto');
|
||
window.requestAnimationFrame(() => apply('auto'));
|
||
window.setTimeout(() => apply('auto'), useSmooth ? 220 : 90);
|
||
}
|
||
|
||
function scrollToUnreadSeparator(list) {
|
||
if (!list) return false;
|
||
const separator = list.querySelector('.chat-unread-separator');
|
||
if (!separator) return false;
|
||
const scrollContainer = findChatScrollContainer(list);
|
||
const apply = () => {
|
||
scrollNodeIntoContainer(separator, { container: scrollContainer, block: 'start' });
|
||
const bottomSlack = 72;
|
||
scrollContainer.scrollTop = Math.max(0, scrollContainer.scrollTop - bottomSlack);
|
||
};
|
||
apply();
|
||
window.requestAnimationFrame(apply);
|
||
window.requestAnimationFrame(() => window.requestAnimationFrame(apply));
|
||
window.setTimeout(apply, 60);
|
||
window.setTimeout(apply, 160);
|
||
return true;
|
||
}
|
||
|
||
// Постоянная справка в начале личного диалога. Это только UI: не DM, не запись в блокчейн.
|
||
function createDmEncryptionNotice() {
|
||
const notice = document.createElement('aside');
|
||
notice.className = 'dm-security-notice';
|
||
notice.setAttribute('role', 'note');
|
||
|
||
const heading = document.createElement('strong');
|
||
heading.className = 'dm-security-notice__title';
|
||
heading.textContent = `🔒 ${t('screens.chat_view.security_notice.title')}`;
|
||
notice.append(heading);
|
||
|
||
for (const text of [
|
||
t('screens.chat_view.security_notice.encryption'),
|
||
t('screens.chat_view.security_notice.servers'),
|
||
t('screens.chat_view.security_notice.derivation'),
|
||
t('screens.chat_view.security_notice.rotation'),
|
||
t('screens.chat_view.security_notice.source'),
|
||
]) {
|
||
const paragraph = document.createElement('p');
|
||
paragraph.textContent = text;
|
||
notice.append(paragraph);
|
||
}
|
||
|
||
const warning = document.createElement('p');
|
||
const warningLabel = document.createElement('strong');
|
||
warningLabel.textContent = `${t('screens.chat_view.security_notice.warning_label')} `;
|
||
warning.append(warningLabel, document.createTextNode(t('screens.chat_view.security_notice.warning')));
|
||
notice.append(warning);
|
||
|
||
const recovery = document.createElement('p');
|
||
recovery.textContent = t('screens.chat_view.security_notice.recovery');
|
||
notice.append(recovery);
|
||
return notice;
|
||
}
|
||
|
||
function renderLog(
|
||
list,
|
||
chatId,
|
||
{
|
||
onOpenActions,
|
||
navigate,
|
||
markAsRead = true,
|
||
scrollMode = 'latest',
|
||
showUnreadSeparator = true,
|
||
unreadSeparatorMessageKey = '',
|
||
} = {},
|
||
) {
|
||
list.innerHTML = '';
|
||
list.append(createDmEncryptionNotice());
|
||
const messages = getChatMessages(chatId);
|
||
let unreadSeparatorInserted = false;
|
||
const separatorMessageKey = String(unreadSeparatorMessageKey || '').trim();
|
||
let lastDayKey = '';
|
||
messages.forEach((msg) => {
|
||
const msgTimeMs = resolveMessageTimeMs(msg);
|
||
const msgDayKey = dayKey(msgTimeMs);
|
||
if (msgDayKey && msgDayKey !== lastDayKey) {
|
||
lastDayKey = msgDayKey;
|
||
const daySep = document.createElement('div');
|
||
daySep.className = 'dm-day-separator';
|
||
daySep.dataset.day = msgDayKey;
|
||
const dayLabel = document.createElement('span');
|
||
dayLabel.textContent = formatDayLabel(msgTimeMs);
|
||
daySep.append(dayLabel);
|
||
list.append(daySep);
|
||
}
|
||
const isUnreadBoundary = showUnreadSeparator
|
||
&& !unreadSeparatorInserted
|
||
&& separatorMessageKey
|
||
&& String(msg?.messageKey || '').trim() === separatorMessageKey;
|
||
if (isUnreadBoundary) {
|
||
const sep = document.createElement('div');
|
||
sep.className = 'chat-unread-separator';
|
||
const label = document.createElement('span');
|
||
label.textContent = t('dialogs.modals.chat_view.label_027');
|
||
sep.append(label);
|
||
list.append(sep);
|
||
unreadSeparatorInserted = true;
|
||
}
|
||
|
||
const bubble = document.createElement('div');
|
||
const parsedText = parseDmTechBlocks(String(msg?.text || ''));
|
||
const rawDmAttachments = Array.isArray(parsedText.fileAttachments) ? parsedText.fileAttachments : (parsedText.fileAttachment ? [parsedText.fileAttachment] : []);
|
||
const dmAttachments = rawDmAttachments.map((attachment) => ({
|
||
...attachment,
|
||
senderLogin: msg?.from === 'out' ? state.session?.login : chatId,
|
||
messageTimestampMs: msgTimeMs,
|
||
}));
|
||
const autoKind = parsedText.callSummary ? 'call-tech' : (dmAttachments.length ? 'file-tech' : '');
|
||
const bubbleKind = String(msg?.kind || autoKind || '').trim();
|
||
bubble.className = `bubble ${msg.from}${bubbleKind ? ` ${bubbleKind}` : ''}`;
|
||
const emojiOnly = !parsedText.callSummary && !dmAttachments.length && !parsedText.replyRef && isTwemojiOnlyMessage(parsedText.displayText || '');
|
||
if (emojiOnly) {
|
||
bubble.classList.add('bubble--emoji-only');
|
||
}
|
||
|
||
if (parsedText.callSummary) {
|
||
const callCard = document.createElement('div');
|
||
callCard.className = 'bubble-call-card';
|
||
|
||
const callHead = document.createElement('div');
|
||
callHead.className = 'bubble-call-head';
|
||
|
||
const callIcon = document.createElement('span');
|
||
callIcon.className = 'bubble-call-icon';
|
||
callIcon.classList.add(msg?.from === 'out' ? 'bubble-call-icon--outgoing' : 'bubble-call-icon--incoming');
|
||
|
||
const callIconPhone = document.createElement('span');
|
||
callIconPhone.className = 'bubble-call-icon-phone';
|
||
callIconPhone.textContent = '✆';
|
||
|
||
const callIconArrow = document.createElement('span');
|
||
callIconArrow.className = 'bubble-call-icon-arrow';
|
||
callIconArrow.textContent = msg?.from === 'out' ? '↑' : '↓';
|
||
|
||
callIcon.append(callIconPhone, callIconArrow);
|
||
|
||
const callTitle = document.createElement('span');
|
||
callTitle.className = 'bubble-call-title';
|
||
callTitle.textContent = t('dialogs.modals.chat_view.label_028');
|
||
|
||
const callMetaLine = document.createElement('span');
|
||
callMetaLine.className = 'bubble-call-line';
|
||
callMetaLine.classList.add(
|
||
parsedText.callSummary.status === 'completed'
|
||
? 'bubble-call-line--success'
|
||
: 'bubble-call-line--plain',
|
||
);
|
||
const callStatus = buildCallStatusText(parsedText.callSummary);
|
||
callMetaLine.textContent = callStatus;
|
||
|
||
callHead.append(callIcon, callTitle, callMetaLine);
|
||
callCard.append(callHead);
|
||
bubble.append(callCard);
|
||
}
|
||
|
||
if (dmAttachments.length) {
|
||
const attachmentsWrap = document.createElement('div');
|
||
attachmentsWrap.className = 'dm-attachment-stack';
|
||
const media = dmAttachments.filter(isDmInlineMedia);
|
||
if (media.length) {
|
||
bubble.classList.add('bubble--media');
|
||
attachmentsWrap.append(createAttachmentCarouselElement(media, {
|
||
messageTimestampMs: Number(msg?.timeMs || 0),
|
||
resolveUrl: resolveDmMediaUrl,
|
||
}));
|
||
}
|
||
for (const attachment of dmAttachments) {
|
||
if (media.includes(attachment)) continue;
|
||
attachmentsWrap.append(
|
||
isDmFileExpired(attachment)
|
||
? createDmExpiredAttachmentCard(attachment)
|
||
: (attachment?.kind === 'voice' ? createDmVoiceAttachmentCard(attachment) : createDmFileAttachmentCard(attachment)),
|
||
);
|
||
}
|
||
bubble.append(attachmentsWrap);
|
||
}
|
||
|
||
const textNode = document.createElement('div');
|
||
textNode.className = 'bubble-text';
|
||
renderMessageText(textNode, parsedText.displayText || '', navigate);
|
||
if (parsedText.replyRef) {
|
||
const replyTarget = findMessageByBaseKey(messages, parsedText.replyRef.baseKey);
|
||
if (replyTarget) {
|
||
const replyParsed = parseDmTechBlocks(String(replyTarget?.text || ''));
|
||
const replyBox = document.createElement('button');
|
||
replyBox.type = 'button';
|
||
replyBox.className = 'ui-button bubble-reply-preview';
|
||
|
||
const replyAuthor = document.createElement('div');
|
||
replyAuthor.className = 'bubble-reply-preview-author';
|
||
replyAuthor.textContent = String(replyTarget?.from === 'out' ? state.session.login : parsedText.replyRef.fromLogin);
|
||
|
||
const replyText = document.createElement('div');
|
||
replyText.className = 'bubble-reply-preview-text';
|
||
replyText.textContent = truncatePreviewText(replyParsed.displayText || '', 96);
|
||
|
||
replyBox.append(replyAuthor, replyText);
|
||
replyBox.addEventListener('click', (event) => {
|
||
event.stopPropagation();
|
||
const targetNode = list.querySelector(`[data-base-key="${CSS.escape(String(replyTarget?.baseKey || ''))}"]`);
|
||
scrollNodeIntoContainer(targetNode, { container: findChatScrollContainer(list), block: 'center', behavior: 'smooth' });
|
||
});
|
||
bubble.append(replyBox);
|
||
}
|
||
}
|
||
if (!parsedText.callSummary && !dmAttachments.length) {
|
||
bubble.append(textNode);
|
||
}
|
||
|
||
const metaNode = document.createElement('div');
|
||
metaNode.className = 'bubble-meta';
|
||
|
||
const timeNode = document.createElement('span');
|
||
timeNode.className = 'bubble-time';
|
||
timeNode.textContent = formatClockTime(resolveMessageTimeMs(msg));
|
||
timeNode.title = formatMessageTime(resolveMessageTimeMs(msg));
|
||
metaNode.append(timeNode);
|
||
|
||
const status = resolveDeliveryStatus(messages, msg);
|
||
if (status) {
|
||
const statusNode = document.createElement('span');
|
||
statusNode.className = `bubble-status bubble-status--${resolveDeliveryTone(messages, msg)}`;
|
||
const statusView = DELIVERY_STATUS_VIEW[status] || DELIVERY_STATUS_VIEW['…'];
|
||
statusNode.innerHTML = iconHtml(statusView.icon);
|
||
statusNode.setAttribute('role', 'img');
|
||
statusNode.setAttribute('aria-label', statusView.label);
|
||
statusNode.title = statusView.label;
|
||
metaNode.append(statusNode);
|
||
}
|
||
|
||
bubble.append(metaNode);
|
||
|
||
const deliveryNote = resolveDeliveryNote(msg);
|
||
if (deliveryNote) {
|
||
const deliveryNoteNode = document.createElement('div');
|
||
deliveryNoteNode.className = `bubble-delivery-note${String(msg?.deliveryState || '') === 'failed' ? ' bubble-delivery-note--failed' : ''}`;
|
||
deliveryNoteNode.textContent = deliveryNote;
|
||
bubble.append(deliveryNoteNode);
|
||
}
|
||
|
||
const editedAtMs = resolveMessageEditedTimeMs(msg);
|
||
if (editedAtMs > 0) {
|
||
const editedNode = document.createElement('div');
|
||
editedNode.className = 'bubble-meta bubble-meta-edited';
|
||
editedNode.textContent = t('screens.chat_view.text_087', { value1: formatMessageTime(editedAtMs) });
|
||
bubble.append(editedNode);
|
||
}
|
||
|
||
bubble.addEventListener('click', (event) => {
|
||
if (typeof onOpenActions === 'function') onOpenActions(msg, event);
|
||
});
|
||
bubble.dataset.baseKey = String(msg?.baseKey || '');
|
||
bubble.dataset.messageKey = String(msg?.messageKey || '');
|
||
list.append(bubble);
|
||
});
|
||
if (scrollMode === 'unread' && !scrollToUnreadSeparator(list)) {
|
||
scrollToLatestMessage(list);
|
||
} else if (scrollMode === 'latest') {
|
||
scrollToLatestMessage(list);
|
||
}
|
||
if (markAsRead) {
|
||
markChatRead(chatId);
|
||
}
|
||
}
|
||
|
||
function preserveComposerSelection(input, callback) {
|
||
if (!input || typeof callback !== 'function') {
|
||
if (typeof callback === 'function') callback();
|
||
return;
|
||
}
|
||
|
||
const wasFocused = document.activeElement === input;
|
||
const start = Number(input.selectionStart ?? input.value.length);
|
||
const end = Number(input.selectionEnd ?? input.value.length);
|
||
|
||
callback();
|
||
|
||
if (!wasFocused) return;
|
||
try {
|
||
input.focus({ preventScroll: true });
|
||
} catch {
|
||
input.focus();
|
||
}
|
||
try {
|
||
input.setSelectionRange(start, end);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
}
|
||
|
||
export function render({ navigate, route, chrome }) {
|
||
const routeChatId = route.params.chatId || 'u1';
|
||
const chatId = normalizeDmChatId(routeChatId) || 'u1';
|
||
const contact = directMessages.find((d) => normalizeDmChatId(d.id) === chatId) || {
|
||
id: chatId,
|
||
name: String(routeChatId || chatId),
|
||
initials: (String(routeChatId || chatId)[0] || '?').toUpperCase(),
|
||
};
|
||
|
||
const screen = document.createElement('section');
|
||
screen.className = 'stack dm-screen dm-chat-screen';
|
||
const isTextToSpeechReady = isTextToSpeechConfigured(state.entrySettings);
|
||
const isKnownContact = (state.contacts || []).some((x) => String(x || '').toLowerCase() === String(chatId || '').toLowerCase());
|
||
const rememberedPeer = getRememberedDmPeer(chatId);
|
||
let peerRelationType = rememberedPeer?.relationType
|
||
? normalizeChatRelationType(rememberedPeer.relationType)
|
||
: (isKnownContact ? 'contact' : 'none');
|
||
const hasUnreadIncoming = getChatMessages(chatId).some((msg) => msg?.from === 'in' && msg?.unread);
|
||
let historyHasMore = true;
|
||
let historyLoading = false;
|
||
let historyNextBeforeTimeMs = 0;
|
||
let historyNextBeforeMessageKey = '';
|
||
let historyBootstrapped = false;
|
||
let boundScrollContainer = null;
|
||
let unreadSeparatorVisible = hasUnreadIncoming;
|
||
let unreadSeparatorAnchorMessageKey = getChatMessages(chatId).find((msg) => msg?.from === 'in' && msg?.unread)?.messageKey || '';
|
||
|
||
let disposed = false;
|
||
let search = null; // открытый поиск: { input, counter, upBtn, downBtn, hits: [messageKey], index, layer }
|
||
const renderChatLog = ({ scrollMode = 'latest', markAsRead = true } = {}) => {
|
||
renderLog(log, chatId, {
|
||
onOpenActions: handleOpenActions,
|
||
navigate,
|
||
markAsRead,
|
||
// Пока открыт поиск, новое сообщение не должно уводить ленту от найденного.
|
||
scrollMode: search && scrollMode === 'latest' ? 'preserve' : scrollMode,
|
||
showUnreadSeparator: unreadSeparatorVisible,
|
||
unreadSeparatorMessageKey: unreadSeparatorAnchorMessageKey,
|
||
});
|
||
if (search) runSearch({ keepPosition: true, scroll: false });
|
||
};
|
||
|
||
const hideUnreadSeparator = ({ rerender = true } = {}) => {
|
||
if (!unreadSeparatorVisible) return;
|
||
unreadSeparatorVisible = false;
|
||
if (rerender) {
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
}
|
||
};
|
||
|
||
const handleReadAloud = async (msg) => {
|
||
if (!isTextToSpeechConfigured(state.entrySettings)) {
|
||
showTtsMissingConfigDialog();
|
||
return;
|
||
}
|
||
const parsedText = parseDmTechBlocks(String(msg?.text || ''));
|
||
await speakTextBySettings(String(parsedText.displayText || ''), state.entrySettings);
|
||
};
|
||
|
||
const handleStartCall = async (mode = 'audio') => {
|
||
try {
|
||
await startOutgoingCall(chatId, { mode });
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
} catch (e) {
|
||
// Подробности запуска уже в журнале звонка; человеку – причина тостом, а не пузырь в переписке.
|
||
const mediaReason = mediaAccessErrorText(e);
|
||
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 });
|
||
}
|
||
};
|
||
|
||
const clearConversationHistory = async () => {
|
||
const result = await authService.deleteConversation({
|
||
login: state.session.login,
|
||
toLogin: chatId,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
deleteByRecipient: true,
|
||
});
|
||
const parsed = authService.parseSignedMessageBlob(String(result?.localBlobB64 || '').trim());
|
||
deleteConversationMessagesBefore(chatId, Number(parsed?.timeMs || 0));
|
||
addSignedMessageToChat({
|
||
chatId,
|
||
messageKey: String(parsed?.messageKey || ''),
|
||
baseKey: String(parsed?.baseKey || ''),
|
||
from: 'out',
|
||
text: CONVERSATION_CLEAR_NOTICE_TEXT,
|
||
messageType: Number(parsed?.messageType || 8),
|
||
unread: false,
|
||
rawBlobB64: String(result?.localBlobB64 || ''),
|
||
});
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
notifyUnreadStateUpdated();
|
||
};
|
||
|
||
const addPeerToContacts = async () => {
|
||
const approved = await openConfirmContactModal(chatId);
|
||
if (!approved) return;
|
||
await authService.setUserRelation({
|
||
login: state.session.login,
|
||
toLogin: chatId,
|
||
kind: 'contact',
|
||
enabled: true,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
});
|
||
peerRelationType = 'contact';
|
||
updateHeaderPeer({ relationType: 'contact' });
|
||
const contactsPayload = await authService.listContacts();
|
||
setContacts(contactsPayload?.contacts || contactsPayload?.dialogs?.filter((x) => x?.relationFlag !== 'none').map((x) => x.peerLogin) || []);
|
||
notifyUnreadStateUpdated();
|
||
showToast(t('screens.chat_view.text_045'), { timeoutMs: 1200 });
|
||
};
|
||
|
||
const wrap = document.createElement('div');
|
||
wrap.className = 'chat-wrap dm-chat-wrap';
|
||
const historyLoader = document.createElement('div');
|
||
historyLoader.className = 'dm-history-loader';
|
||
historyLoader.hidden = true;
|
||
historyLoader.innerHTML = `
|
||
<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>
|
||
`;
|
||
|
||
const log = document.createElement('div');
|
||
log.className = 'messages-log dm-messages-log';
|
||
|
||
// Шапка пересоздаётся при выходе из поиска: chrome.setTopbar убирает прежнюю вместе с её меню.
|
||
let chatHeaderParts = null;
|
||
let lastHeaderPeer = rememberedPeer || null;
|
||
const updateHeaderPeer = (peer) => {
|
||
lastHeaderPeer = { ...(lastHeaderPeer || {}), ...peer };
|
||
chatHeaderParts?.updatePeer(peer);
|
||
};
|
||
const buildChatHeader = () => {
|
||
chatHeaderParts = createChatHeaderParts(chatId, navigate);
|
||
if (lastHeaderPeer) chatHeaderParts.updatePeer(lastHeaderPeer);
|
||
chatHeaderParts.setMuted(isDmChatMuted(chatId));
|
||
const header = createTopBar({
|
||
center: chatHeaderParts.center,
|
||
className: 'topbar--identity',
|
||
back: { label: '←', onClick: () => navigate('messages-list') },
|
||
actions: [
|
||
{
|
||
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: 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({ className: 'app-overflow-dots--vertical' }),
|
||
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: 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: 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: t('screens.chat_view.text_019'),
|
||
iconHtml: iconHtml('user-plus', false, 'dm-menu-icon'),
|
||
action: async () => {
|
||
try {
|
||
await addPeerToContacts();
|
||
} catch (error) {
|
||
showToast(actionErrorText(t('screens.chat_view.text_046'), error), { kind: 'error' });
|
||
}
|
||
},
|
||
}
|
||
: null,
|
||
{ label: t('wallet_multi.transfer_to_contact'), iconHtml: menuIconSvg('forward'), action: () => navigate(`wallet/transfer/${encodeURIComponent(chatId)}`) },
|
||
{ divider: true },
|
||
{
|
||
label: t('screens.chat_view.text_020'),
|
||
iconHtml: menuIconSvg('clear'),
|
||
action: () => openChatConfirmModal({
|
||
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(t('dialogs.final.chat.confirm_clear_history_success'), { timeoutMs: 1200 });
|
||
} catch (error) {
|
||
showToast(actionErrorText(t('dialogs.final.chat.confirm_clear_history_error'), error), { kind: 'error' });
|
||
}
|
||
},
|
||
}),
|
||
},
|
||
{
|
||
label: t('screens.chat_view.text_021'),
|
||
iconHtml: menuIconSvg('delete'),
|
||
danger: true,
|
||
action: () => {
|
||
const relationBeforeDelete = normalizeChatRelationType(peerRelationType);
|
||
openDeleteChatConfirmModal({
|
||
contactName: contact.name,
|
||
relationType: relationBeforeDelete,
|
||
onConfirm: async ({ deleteHistory }) => {
|
||
try {
|
||
if (deleteHistory) await clearConversationHistory();
|
||
const relationKinds = relationBeforeDelete === 'close_friend' || relationBeforeDelete === 'friend'
|
||
? ['close_friend', 'friend', 'contact']
|
||
: ['contact'];
|
||
for (const kind of relationKinds) {
|
||
await authService.setUserRelation({
|
||
login: state.session.login,
|
||
toLogin: chatId,
|
||
kind,
|
||
enabled: false,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
});
|
||
}
|
||
const contactsPayload = await authService.listContacts();
|
||
setContacts(
|
||
contactsPayload?.contacts
|
||
|| contactsPayload?.dialogs?.filter((x) => x?.relationFlag !== 'none').map((x) => x.peerLogin)
|
||
|| [],
|
||
);
|
||
notifyUnreadStateUpdated();
|
||
showToast(t('dialogs.final.chat.confirm_delete_chat_success'), { timeoutMs: 1200 });
|
||
navigate('messages-list');
|
||
} catch (error) {
|
||
showToast(actionErrorText(t('dialogs.final.chat.confirm_delete_chat_error'), error), { kind: 'error' });
|
||
}
|
||
},
|
||
});
|
||
},
|
||
},
|
||
].filter(Boolean),
|
||
},
|
||
},
|
||
],
|
||
});
|
||
header.addCleanup(chatHeaderParts.cleanup);
|
||
return header;
|
||
};
|
||
|
||
const toggleChatPinned = (pinned) => {
|
||
setDmChatPinned(chatId, pinned);
|
||
showToast(pinned ? t('screens.chat_view.text_067') : t('screens.chat_view.text_068'), { timeoutMs: 1400 });
|
||
};
|
||
|
||
|
||
// ── Поиск по переписке ─────────────────────────────────────────────────────
|
||
// Шапка превращается в строку поиска. Ищем по всей истории: она догружается с сервера
|
||
// в фоне, а совпадения среди уже загруженных сообщений видны сразу.
|
||
let historyFullLoad = null;
|
||
|
||
const normalizeSearchText = (value) => String(value || '').toLowerCase().replace(/ё/g, 'е');
|
||
|
||
const ensureFullHistory = () => {
|
||
if (isDmHistoryFullyLoaded(chatId)) return Promise.resolve(false);
|
||
if (!historyFullLoad) {
|
||
const countBefore = getChatMessages(chatId).length;
|
||
historyFullLoad = loadFullDmHistory(chatId)
|
||
.then(() => {
|
||
historyHasMore = false;
|
||
if (disposed) return false;
|
||
const grew = getChatMessages(chatId).length !== countBefore;
|
||
if (grew) renderChatLog({ scrollMode: 'preserve', markAsRead: false });
|
||
return grew;
|
||
})
|
||
.finally(() => { historyFullLoad = null; });
|
||
}
|
||
return historyFullLoad;
|
||
};
|
||
|
||
const messageSearchText = (msg) => {
|
||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||
const files = Array.isArray(parsed.fileAttachments) ? parsed.fileAttachments : (parsed.fileAttachment ? [parsed.fileAttachment] : []);
|
||
return normalizeSearchText([parsed.displayText || '', ...files.map((f) => f?.name || '')].join('\n'));
|
||
};
|
||
|
||
const clearSearchMarks = () => {
|
||
log.querySelectorAll('mark.dm-search-mark').forEach((mark) => mark.replaceWith(...mark.childNodes));
|
||
log.querySelectorAll('.is-search-hit, .is-search-current').forEach((el) => el.classList.remove('is-search-hit', 'is-search-current'));
|
||
log.normalize();
|
||
};
|
||
|
||
// Подсвечиваем совпадения внутри текста пузыря, не трогая ссылки и эмодзи-картинки.
|
||
const markSearchText = (bubble, query) => {
|
||
const textRoot = bubble.querySelector('.bubble-text');
|
||
if (!textRoot || !query) return;
|
||
const walker = document.createTreeWalker(textRoot, NodeFilter.SHOW_TEXT);
|
||
const nodes = [];
|
||
while (walker.nextNode()) nodes.push(walker.currentNode);
|
||
for (const node of nodes) {
|
||
const text = node.nodeValue || '';
|
||
const haystack = normalizeSearchText(text);
|
||
let from = 0;
|
||
let at = haystack.indexOf(query, from);
|
||
if (at < 0) continue;
|
||
const fragment = document.createDocumentFragment();
|
||
while (at >= 0) {
|
||
fragment.append(text.slice(from, at));
|
||
const mark = document.createElement('mark');
|
||
mark.className = 'dm-search-mark';
|
||
mark.textContent = text.slice(at, at + query.length);
|
||
fragment.append(mark);
|
||
from = at + query.length;
|
||
at = haystack.indexOf(query, from);
|
||
}
|
||
fragment.append(text.slice(from));
|
||
node.replaceWith(fragment);
|
||
}
|
||
};
|
||
|
||
// Рядом – плавно, далеко – сразу: плавная прокрутка через сотни сообщений идёт секундами.
|
||
const scrollFeedTo = (node, block) => {
|
||
if (!node) return;
|
||
stickToBottom = false;
|
||
const distance = Math.abs(node.getBoundingClientRect().top - wrap.getBoundingClientRect().top - wrap.clientHeight / 2);
|
||
scrollNodeIntoContainer(node, { container: wrap, block, behavior: distance < wrap.clientHeight ? 'smooth' : 'auto' });
|
||
};
|
||
|
||
const findBubble = (messageKey) => (messageKey
|
||
? log.querySelector(`.bubble[data-message-key="${CSS.escape(messageKey)}"]`)
|
||
: null);
|
||
|
||
const syncSearchControls = () => {
|
||
if (!search) return;
|
||
const total = search.hits.length;
|
||
const query = normalizeSearchText(search.input.value).trim();
|
||
const loading = Boolean(historyFullLoad);
|
||
// Номер считается от новых: «1 из 12» – самое свежее совпадение.
|
||
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;
|
||
};
|
||
|
||
const applySearchHighlights = ({ scroll = false } = {}) => {
|
||
if (!search) return;
|
||
clearSearchMarks();
|
||
const query = normalizeSearchText(search.input.value).trim();
|
||
search.hits.forEach((key, i) => {
|
||
const bubble = findBubble(key);
|
||
if (!bubble) return;
|
||
bubble.classList.add('is-search-hit');
|
||
if (i === search.index) bubble.classList.add('is-search-current');
|
||
markSearchText(bubble, query);
|
||
});
|
||
if (scroll) scrollFeedTo(findBubble(search.hits[search.index]), 'center');
|
||
syncSearchControls();
|
||
};
|
||
|
||
const runSearch = ({ keepPosition = false, scroll = true } = {}) => {
|
||
if (!search) return;
|
||
const query = normalizeSearchText(search.input.value).trim();
|
||
const previousKey = search.hits[search.index];
|
||
search.hits = query
|
||
? getChatMessages(chatId).filter((msg) => msg?.messageKey && !msg?.deleted && messageSearchText(msg).includes(query)).map((msg) => String(msg.messageKey))
|
||
: [];
|
||
const kept = keepPosition ? search.hits.indexOf(previousKey) : -1;
|
||
search.index = kept >= 0 ? kept : search.hits.length - 1;
|
||
applySearchHighlights({ scroll: scroll && kept < 0 && search.hits.length > 0 });
|
||
};
|
||
|
||
const stepSearch = (delta) => {
|
||
if (!search?.hits.length) return;
|
||
search.index = Math.max(0, Math.min(search.hits.length - 1, search.index + delta));
|
||
applySearchHighlights({ scroll: true });
|
||
};
|
||
|
||
let searchDebounce = 0;
|
||
const closeChatSearch = ({ fromHistory = false } = {}) => {
|
||
if (!search) return;
|
||
const { layer } = search;
|
||
window.clearTimeout(searchDebounce);
|
||
clearSearchMarks();
|
||
search = null;
|
||
if (!fromHistory) layer?.close();
|
||
if (!disposed) chrome?.setTopbar(buildChatHeader());
|
||
};
|
||
|
||
function openChatSearch() {
|
||
if (search) return;
|
||
const counter = document.createElement('span');
|
||
counter.className = 'topbar-search__counter';
|
||
counter.setAttribute('aria-live', 'polite');
|
||
const searchBar = createSearchTopBar({
|
||
placeholder: t('screens.chat_view.text_022'),
|
||
trailing: counter,
|
||
onClose: () => closeChatSearch(),
|
||
onInput: () => {
|
||
window.clearTimeout(searchDebounce);
|
||
searchDebounce = window.setTimeout(() => runSearch(), 180);
|
||
},
|
||
onSubmit: (value, event) => {
|
||
window.clearTimeout(searchDebounce);
|
||
if (!search.hits.length || normalizeSearchText(value).trim() !== search.lastQuery) {
|
||
runSearch();
|
||
search.lastQuery = normalizeSearchText(value).trim();
|
||
} else {
|
||
stepSearch(event.shiftKey ? 1 : -1);
|
||
}
|
||
},
|
||
actions: [
|
||
{ 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;
|
||
search = {
|
||
input,
|
||
counter,
|
||
upBtn: searchBar.querySelector('[data-action="older"]'),
|
||
downBtn: searchBar.querySelector('[data-action="newer"]'),
|
||
hits: [],
|
||
index: -1,
|
||
layer: openHistoryLayer(() => closeChatSearch({ fromHistory: true })),
|
||
};
|
||
chrome?.setTopbar(searchBar);
|
||
syncSearchControls();
|
||
window.requestAnimationFrame(() => input.focus());
|
||
void ensureFullHistory().then((grew) => {
|
||
if (!search) return;
|
||
runSearch({ keepPosition: true, scroll: false });
|
||
// Сверху добавились старые сообщения – возвращаем найденное в центр.
|
||
if (grew) applySearchHighlights({ scroll: true });
|
||
}).catch(() => {
|
||
if (search) syncSearchControls();
|
||
});
|
||
}
|
||
|
||
// ── Перейти к дате ─────────────────────────────────────────────────────────
|
||
let dateJumpModal = null;
|
||
const collectChatDays = () => {
|
||
const days = new Map();
|
||
for (const msg of getChatMessages(chatId)) {
|
||
const timeMs = resolveMessageTimeMs(msg);
|
||
const key = dayKey(timeMs);
|
||
if (!key) continue;
|
||
const info = days.get(key);
|
||
if (info) info.count += 1;
|
||
else days.set(key, { timeMs, count: 1 });
|
||
}
|
||
return days;
|
||
};
|
||
const jumpToDay = (key) => {
|
||
const separator = log.querySelector(`.dm-day-separator[data-day="${CSS.escape(key)}"]`);
|
||
scrollFeedTo(separator, 'start');
|
||
};
|
||
function openDateJump() {
|
||
const loading = !isDmHistoryFullyLoaded(chatId);
|
||
dateJumpModal = openDateJumpModal({ days: collectChatDays(), loading, onPick: jumpToDay });
|
||
if (!loading) return;
|
||
void ensureFullHistory()
|
||
.then(() => dateJumpModal?.update({ days: collectChatDays(), loading: false }))
|
||
.catch(() => dateJumpModal?.update({ days: collectChatDays(), loading: false }));
|
||
}
|
||
// Нажатие на плашку дня в ленте открывает тот же календарь.
|
||
log.addEventListener('click', (event) => {
|
||
if (event.target.closest?.('.dm-day-separator')) openDateJump();
|
||
});
|
||
|
||
chrome?.setTopbar(buildChatHeader());
|
||
|
||
|
||
const fileTransferEnabledAtRender = isDmFileTransferEnabled();
|
||
const form = document.createElement('form');
|
||
form.className = 'chat-input dm-chat-input';
|
||
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="${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="${th('screens.chat_view.text_113')}" title="${th('screens.chat_view.text_114')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('image')}</button>
|
||
<button class="dm-bar-icon dm-camera-btn" type="button" id="chat-camera-toggle" aria-label="${th('screens.chat_view.text_115')}" title="${th('screens.chat_view.text_116')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('camera')}</button>
|
||
<button class="dm-bar-icon dm-file-btn" type="button" id="chat-file-toggle" aria-label="${th('screens.chat_view.text_117')}" title="${th('screens.chat_view.text_118')}"${fileTransferEnabledAtRender ? '' : ' hidden'}>${iconHtml('clip')}</button>
|
||
<div class="dm-voice-recording-status" id="chat-voice-recording-status" hidden>
|
||
<span class="dm-voice-recording-dot" aria-hidden="true"></span>
|
||
<span class="dm-voice-recording-time" id="chat-voice-recording-time">0:00</span>
|
||
<span class="dm-voice-recording-hint" id="chat-voice-recording-hint">${th('screens.chat_view.text_119')}</span>
|
||
</div>
|
||
<div class="dm-field">
|
||
<textarea class="input dm-input" name="message" rows="1" placeholder="${th('screens.chat_view.text_120')}" maxlength="12000" enterkeyhint="enter"></textarea>
|
||
</div>
|
||
<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 />
|
||
<input id="chat-camera-input" type="file" accept="image/*,video/*" capture="environment" hidden />
|
||
`;
|
||
|
||
const input = form.elements.message;
|
||
const emojiSlot = form.querySelector('#chat-emoji-picker-slot');
|
||
const emojiToggle = form.querySelector('#chat-emoji-toggle');
|
||
const fileToggle = form.querySelector('#chat-file-toggle');
|
||
const fileInput = form.querySelector('#chat-file-input');
|
||
// Три входа для вложений: галерея (фото/видео), камера и любой файл – дальше путь один.
|
||
const attachSources = [
|
||
[fileToggle, fileInput],
|
||
[form.querySelector('#chat-media-toggle'), form.querySelector('#chat-media-input')],
|
||
[form.querySelector('#chat-camera-toggle'), form.querySelector('#chat-camera-input')],
|
||
];
|
||
const attachButtons = attachSources.map(([button]) => button).filter(Boolean);
|
||
const sendBtn = form.querySelector('.dm-send-btn');
|
||
const voiceStatus = form.querySelector('#chat-voice-recording-status');
|
||
const voiceTime = form.querySelector('#chat-voice-recording-time');
|
||
const voiceHint = form.querySelector('#chat-voice-recording-hint');
|
||
const fileTransferEnabled = isDmFileTransferEnabled();
|
||
const editBanner = form.querySelector('#chat-edit-banner');
|
||
const editBannerText = form.querySelector('#chat-edit-banner-text');
|
||
const editCancelBtn = form.querySelector('#chat-edit-cancel');
|
||
let activeEdit = null;
|
||
let activeReply = null;
|
||
let inputFocused = false;
|
||
let emojiPickerOpen = false;
|
||
let emojiSelection = null;
|
||
let emojiLongPressTimer = null;
|
||
let emojiLongPressTriggered = false;
|
||
let fileActionVisible = false;
|
||
let voiceRecorder = null;
|
||
let voiceStream = null;
|
||
let voiceChunks = [];
|
||
let voiceStartedAt = 0;
|
||
let voiceTimer = null;
|
||
let voiceLocked = false;
|
||
let voicePointerHeld = false;
|
||
let voiceReleaseRequested = false;
|
||
let voiceStartY = 0;
|
||
let voicePointerId = null;
|
||
let voiceBusy = false;
|
||
let suppressVoiceClick = false;
|
||
|
||
let historyLoaderTimer = 0;
|
||
const setHistoryLoadingState = (isLoading) => {
|
||
window.clearTimeout(historyLoaderTimer);
|
||
if (!isLoading) {
|
||
historyLoader.hidden = true;
|
||
historyLoader.classList.remove('is-visible');
|
||
return;
|
||
}
|
||
// Быстрый ответ сервера не должен мелькать спиннером.
|
||
historyLoaderTimer = window.setTimeout(() => {
|
||
historyLoader.classList.toggle('is-centered', !getChatMessages(chatId).length);
|
||
historyLoader.hidden = false;
|
||
window.requestAnimationFrame(() => historyLoader.classList.add('is-visible'));
|
||
}, 300);
|
||
};
|
||
|
||
// В покое (поле пустое и не в фокусе) капсула в один ряд. Нажали в поле – текст сразу получает
|
||
// весь верхний ряд, кнопки уходят в нижний. Раскладка меняется по нажатию, а не посреди набора текста.
|
||
let composerPressing = false;
|
||
const syncComposerLayout = () => {
|
||
if (!input) return;
|
||
const expanded = inputFocused || composerPressing || emojiPickerOpen || Boolean(activeEdit)
|
||
|| Boolean(String(input.value || '').trim());
|
||
if (expanded === form.classList.contains('dm-chat-input--expanded')) return;
|
||
form.classList.toggle('dm-chat-input--expanded', expanded);
|
||
autoResizeComposer(input);
|
||
};
|
||
// Нажатие на кнопку в капсуле снимает фокус с поля; без этой задержки капсула схлопнулась бы
|
||
// прямо под пальцем, и нажатие пришлось бы на другую кнопку.
|
||
form.addEventListener('pointerdown', () => { composerPressing = true; });
|
||
const releaseComposerPress = () => window.setTimeout(() => { composerPressing = false; syncComposerLayout(); }, 350);
|
||
form.addEventListener('pointerup', releaseComposerPress);
|
||
form.addEventListener('pointercancel', releaseComposerPress);
|
||
|
||
const rememberEmojiSelection = () => {
|
||
if (!input) return;
|
||
const valueLength = String(input.value || '').length;
|
||
const start = Math.max(0, Math.min(valueLength, Number(input.selectionStart ?? valueLength)));
|
||
const end = Math.max(start, Math.min(valueLength, Number(input.selectionEnd ?? start)));
|
||
emojiSelection = { start, end };
|
||
};
|
||
|
||
const closeEmojiPicker = () => {
|
||
if (!emojiPickerOpen) return;
|
||
emojiPickerOpen = false;
|
||
stopAllTwemojiAnimations();
|
||
emojiSlot.hidden = true;
|
||
emojiToggle?.setAttribute('aria-expanded', 'false');
|
||
syncComposerLayout();
|
||
};
|
||
|
||
const clearEmojiLongPress = () => {
|
||
if (emojiLongPressTimer != null) {
|
||
window.clearTimeout(emojiLongPressTimer);
|
||
emojiLongPressTimer = null;
|
||
}
|
||
};
|
||
|
||
// Кнопка вложения всегда в строке ввода; прячется только на время записи голосового.
|
||
const setFileActionVisible = (visible) => {
|
||
fileActionVisible = Boolean(visible && fileTransferEnabled);
|
||
attachButtons.forEach((button) => { button.hidden = !fileTransferEnabled; });
|
||
syncComposerLayout();
|
||
};
|
||
|
||
|
||
const sendIconMarkup = (mode) => {
|
||
if (mode === 'send') {
|
||
return iconHtml('send');
|
||
}
|
||
if (mode === 'stop') {
|
||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor"/></svg>';
|
||
}
|
||
if (mode === 'busy') {
|
||
return '<span class="dm-send-busy-dot">…</span>';
|
||
}
|
||
return iconHtml('mic');
|
||
};
|
||
|
||
const currentVoiceDurationMs = () => voiceStartedAt > 0 ? Math.max(0, Date.now() - voiceStartedAt) : 0;
|
||
|
||
const syncVoiceTimer = () => {
|
||
if (voiceTime) voiceTime.textContent = formatVoiceDuration(currentVoiceDurationMs());
|
||
};
|
||
|
||
const clearVoiceTimer = () => {
|
||
if (voiceTimer != null) {
|
||
window.clearInterval(voiceTimer);
|
||
voiceTimer = null;
|
||
}
|
||
};
|
||
|
||
const stopVoiceStreamTracks = () => {
|
||
try {
|
||
voiceStream?.getTracks?.().forEach((track) => track.stop());
|
||
} catch {
|
||
// ignore microphone cleanup failures
|
||
}
|
||
voiceStream = null;
|
||
};
|
||
|
||
const updateSendButtonMode = () => {
|
||
if (!sendBtn) return;
|
||
const recording = Boolean(voiceRecorder && voiceRecorder.state !== 'inactive');
|
||
let mode = 'voice';
|
||
if (voiceBusy) mode = 'busy';
|
||
else if (recording && voiceLocked) mode = 'stop';
|
||
else if (recording) mode = 'voice';
|
||
else if (activeEdit || String(input?.value || '').trim()) mode = 'send';
|
||
|
||
sendBtn.dataset.mode = mode;
|
||
sendBtn.innerHTML = sendIconMarkup(mode);
|
||
sendBtn.classList.toggle('is-recording', recording);
|
||
sendBtn.classList.toggle('is-locked', recording && voiceLocked);
|
||
sendBtn.disabled = voiceBusy || (mode === 'voice' && !recording && !fileTransferEnabled);
|
||
if (mode === 'send') {
|
||
sendBtn.title = t('screens.chat_view.text_029');
|
||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_029'));
|
||
} else if (mode === 'stop') {
|
||
sendBtn.title = t('screens.chat_view.text_030');
|
||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_030'));
|
||
} else if (mode === 'busy') {
|
||
sendBtn.title = t('screens.chat_view.text_031');
|
||
sendBtn.setAttribute('aria-label', t('dialogs.modals.chat_view.label_031'));
|
||
} else {
|
||
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 = t('dialogs.modals.chat_view.label_033');
|
||
syncVoiceTimer();
|
||
};
|
||
|
||
const selectVoiceMimeType = () => {
|
||
const candidates = [
|
||
'audio/webm;codecs=opus',
|
||
'audio/ogg;codecs=opus',
|
||
'audio/mp4',
|
||
'audio/webm',
|
||
];
|
||
return candidates.find((mime) => globalThis.MediaRecorder?.isTypeSupported?.(mime)) || '';
|
||
};
|
||
|
||
const voiceExtension = (mime = '') => {
|
||
const value = String(mime || '').toLowerCase();
|
||
if (value.includes('ogg')) return 'ogg';
|
||
if (value.includes('mp4') || value.includes('m4a')) return 'm4a';
|
||
return 'webm';
|
||
};
|
||
|
||
const stopVoiceRecording = ({ send = true } = {}) => {
|
||
voicePointerHeld = false;
|
||
voiceReleaseRequested = true;
|
||
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
|
||
voiceRecorder.__shineShouldSend = Boolean(send);
|
||
try {
|
||
voiceRecorder.stop();
|
||
} catch {
|
||
stopVoiceStreamTracks();
|
||
}
|
||
};
|
||
|
||
const startVoiceRecording = async ({ pointerY = 0, pointerId = null } = {}) => {
|
||
if (voiceBusy || (voiceRecorder && voiceRecorder.state !== 'inactive')) return;
|
||
if (!fileTransferEnabled) {
|
||
showToast(t('screens.chat_view.text_047'), { kind: 'error', timeoutMs: 1900 });
|
||
return;
|
||
}
|
||
if (activeEdit) {
|
||
showToast(t('screens.chat_view.text_048'), { kind: 'error', timeoutMs: 1600 });
|
||
return;
|
||
}
|
||
if (!globalThis.MediaRecorder || !navigator.mediaDevices?.getUserMedia) {
|
||
showToast(t('screens.chat_view.text_049'), { kind: 'error', timeoutMs: 2400 });
|
||
return;
|
||
}
|
||
|
||
voicePointerHeld = true;
|
||
voiceReleaseRequested = false;
|
||
voiceLocked = false;
|
||
voiceStartY = Number(pointerY || 0);
|
||
voicePointerId = pointerId;
|
||
suppressVoiceClick = false;
|
||
|
||
try {
|
||
closeEmojiPicker();
|
||
setFileActionVisible(false);
|
||
voiceStream = await navigator.mediaDevices.getUserMedia({
|
||
audio: {
|
||
echoCancellation: true,
|
||
noiseSuppression: true,
|
||
autoGainControl: true,
|
||
},
|
||
video: false,
|
||
});
|
||
const mimeType = selectVoiceMimeType();
|
||
const recorder = mimeType
|
||
? new MediaRecorder(voiceStream, { mimeType })
|
||
: new MediaRecorder(voiceStream);
|
||
voiceRecorder = recorder;
|
||
voiceChunks = [];
|
||
recorder.__shineShouldSend = true;
|
||
recorder.addEventListener('dataavailable', (event) => {
|
||
if (event.data?.size > 0) voiceChunks.push(event.data);
|
||
});
|
||
recorder.addEventListener('error', (event) => {
|
||
showToast(actionErrorText(t('screens.chat_view.text_050'), event?.error), { kind: 'error' });
|
||
});
|
||
recorder.addEventListener('stop', async () => {
|
||
const shouldSend = recorder.__shineShouldSend !== false;
|
||
const durationMs = currentVoiceDurationMs();
|
||
const chunks = voiceChunks.slice();
|
||
voiceChunks = [];
|
||
voiceRecorder = null;
|
||
voiceLocked = false;
|
||
voiceStartedAt = 0;
|
||
clearVoiceTimer();
|
||
stopVoiceStreamTracks();
|
||
voiceBusy = shouldSend && chunks.some((chunk) => chunk.size > 0);
|
||
updateSendButtonMode();
|
||
|
||
if (!voiceBusy) return;
|
||
try {
|
||
const mime = String(recorder.mimeType || mimeType || chunks[0]?.type || 'audio/webm');
|
||
const blob = new Blob(chunks, { type: mime });
|
||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
||
const file = new File([blob], `voice-${timestamp}.${voiceExtension(mime)}`, { type: mime, lastModified: Date.now() });
|
||
const attachment = await encryptAndUploadDmFile({
|
||
file,
|
||
login: state.session.login,
|
||
sessionId: state.session.sessionId,
|
||
wsUrl: authService.serverUrl,
|
||
kind: 'voice',
|
||
durationMs,
|
||
onProgress: ({ processedBytes, totalBytes }) => {
|
||
if (!totalBytes) return;
|
||
const percent = Math.round((processedBytes / totalBytes) * 100);
|
||
if (voiceHint) voiceHint.textContent = t('screens.chat_view.text_090', { value1: Math.min(100, percent) });
|
||
},
|
||
});
|
||
await sendFileAttachmentMessage([attachment]);
|
||
showToast(t('screens.chat_view.text_051'), { timeoutMs: 1200 });
|
||
} catch (error) {
|
||
showToast(actionErrorText(t('screens.chat_view.text_052'), error), { kind: 'error' });
|
||
} finally {
|
||
voiceBusy = false;
|
||
updateSendButtonMode();
|
||
}
|
||
}, { once: true });
|
||
|
||
voiceStartedAt = Date.now();
|
||
recorder.start(1000);
|
||
voiceTimer = window.setInterval(syncVoiceTimer, 250);
|
||
updateSendButtonMode();
|
||
if (voiceReleaseRequested && !voiceLocked) stopVoiceRecording({ send: true });
|
||
} catch (error) {
|
||
voicePointerHeld = false;
|
||
voiceReleaseRequested = false;
|
||
voiceLocked = false;
|
||
voiceRecorder = null;
|
||
voiceStartedAt = 0;
|
||
clearVoiceTimer();
|
||
stopVoiceStreamTracks();
|
||
updateSendButtonMode();
|
||
const mediaReason = mediaAccessErrorText(error);
|
||
showToast(mediaReason ? t('screens.chat_view.text_091', { value1: mediaReason }) : actionErrorText(t('screens.chat_view.text_053'), error), { kind: 'error' });
|
||
}
|
||
};
|
||
|
||
// На сенсорных устройствах фокус в textarea поднимает клавиатуру поверх пикера —
|
||
// поэтому при вставке эмодзи фокусируем поле только там, где есть «точный» указатель.
|
||
const isFinePointer = window.matchMedia?.('(hover: hover) and (pointer: fine)')?.matches ?? true;
|
||
|
||
const insertEmoji = (emoji) => {
|
||
if (!input) return;
|
||
const value = String(input.value || '');
|
||
const start = emojiSelection?.start ?? Number(input.selectionStart ?? value.length);
|
||
const end = emojiSelection?.end ?? Number(input.selectionEnd ?? value.length);
|
||
input.value = `${value.slice(0, start)}${emoji}${value.slice(end)}`;
|
||
const nextPosition = start + emoji.length;
|
||
emojiSelection = { start: nextPosition, end: nextPosition };
|
||
if (isFinePointer) {
|
||
input.focus();
|
||
try {
|
||
input.setSelectionRange(nextPosition, nextPosition);
|
||
} catch {
|
||
// Ignore browsers that do not expose textarea selection during focus changes.
|
||
}
|
||
}
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
updateSendButtonMode();
|
||
};
|
||
|
||
if (emojiSlot) {
|
||
emojiSlot.append(createEmojiPicker({ onSelect: insertEmoji }));
|
||
}
|
||
|
||
const syncEditBanner = () => {
|
||
if (!editBanner || !editBannerText) return;
|
||
if (!activeEdit && !activeReply) {
|
||
editBanner.hidden = true;
|
||
editBannerText.textContent = '';
|
||
return;
|
||
}
|
||
editBanner.hidden = false;
|
||
if (activeEdit) {
|
||
editBannerText.textContent = t('screens.chat_view.text_092', { value1: truncatePreviewText(activeEdit.originalText, 110) });
|
||
return;
|
||
}
|
||
editBannerText.textContent = t('screens.chat_view.text_093', { value1: truncatePreviewText(activeReply?.previewText || '', 110) });
|
||
};
|
||
|
||
const focusInputToEnd = () => {
|
||
if (!input) return;
|
||
input.focus();
|
||
try {
|
||
const nextPos = String(input.value || '').length;
|
||
input.setSelectionRange(nextPos, nextPos);
|
||
} catch {
|
||
// ignore
|
||
}
|
||
};
|
||
|
||
const cancelEditMode = ({ restoreDraft = true } = {}) => {
|
||
if (!activeEdit) return;
|
||
const draftToRestore = activeEdit.draftBeforeEdit;
|
||
activeEdit = null;
|
||
syncEditBanner();
|
||
if (restoreDraft && input) {
|
||
input.value = draftToRestore || '';
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
focusInputToEnd();
|
||
}
|
||
updateSendButtonMode();
|
||
};
|
||
|
||
const cancelReplyMode = ({ restoreDraft = true } = {}) => {
|
||
if (!activeReply) return;
|
||
activeReply = null;
|
||
syncEditBanner();
|
||
if (restoreDraft && input) {
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
focusInputToEnd();
|
||
}
|
||
updateSendButtonMode();
|
||
};
|
||
|
||
const startEditMode = (msg) => {
|
||
const base = parseBaseKey(msg?.baseKey);
|
||
if (!base || msg?.from !== 'out') return;
|
||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||
const currentDraft = String(input?.value || '');
|
||
activeReply = null;
|
||
activeEdit = {
|
||
messageKey: String(msg?.messageKey || ''),
|
||
originalText: String(parsed?.displayText || ''),
|
||
prefixText: String(parsed?.prefixText || ''),
|
||
draftBeforeEdit: activeEdit ? String(activeEdit.draftBeforeEdit || '') : currentDraft,
|
||
timeMs: base.timeMs,
|
||
nonce: base.nonce,
|
||
};
|
||
syncEditBanner();
|
||
if (input) {
|
||
input.value = String(parsed?.visibleText || '');
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
focusInputToEnd();
|
||
}
|
||
updateSendButtonMode();
|
||
};
|
||
|
||
const startReplyMode = (msg) => {
|
||
const base = parseBaseKey(msg?.baseKey);
|
||
if (!base) return;
|
||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||
activeEdit = null;
|
||
activeReply = {
|
||
baseKey: String(msg?.baseKey || ''),
|
||
fromLogin: base.fromLogin,
|
||
toLogin: base.toLogin,
|
||
previewText: String(parsed?.displayText || parsed?.visibleText || ''),
|
||
};
|
||
syncEditBanner();
|
||
focusInputToEnd();
|
||
};
|
||
|
||
const applyLocalRevision = async ({
|
||
localOutgoingBlobB64,
|
||
fallbackMessageKey = '',
|
||
fallbackBaseKey = '',
|
||
deliveryState = '',
|
||
}) => {
|
||
if (!localOutgoingBlobB64) return;
|
||
try {
|
||
const parsed = authService.parseSignedMessageBlob(localOutgoingBlobB64);
|
||
let text = '';
|
||
if (Number(parsed?.messageType || 0) === 1 || Number(parsed?.messageType || 0) === 2) {
|
||
const decrypted = await authService.decryptSignedMessageContent({
|
||
parsed,
|
||
login: state.session.login,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
});
|
||
text = String(decrypted?.text || '');
|
||
}
|
||
addSignedMessageToChat({
|
||
chatId,
|
||
messageKey: fallbackMessageKey || parsed?.messageKey || '',
|
||
baseKey: fallbackBaseKey || parsed?.baseKey || '',
|
||
from: 'out',
|
||
text,
|
||
messageType: Number(parsed?.messageType || 2),
|
||
unread: false,
|
||
rawBlobB64: localOutgoingBlobB64,
|
||
revisionTimeMs: Number(parsed?.revisionTimeMs || 0),
|
||
deliveryState,
|
||
deleted: Boolean(parsed?.deleted),
|
||
});
|
||
return true;
|
||
} catch {
|
||
// ignore local parse failure; server backlog/realtime will reconcile later
|
||
return false;
|
||
}
|
||
};
|
||
|
||
const notifyUnreadStateUpdated = () => {
|
||
window.dispatchEvent(new CustomEvent('shine-unread-state-updated', {
|
||
detail: { chatId },
|
||
}));
|
||
};
|
||
|
||
const sendDeleteRevision = async (msg) => {
|
||
const base = parseBaseKey(msg?.baseKey);
|
||
if (!base) return;
|
||
const result = await authService.deleteDirectMessage({
|
||
login: state.session.login,
|
||
toLogin: chatId,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
timeMs: base.timeMs,
|
||
nonce: base.nonce,
|
||
revisionTimeMs: Date.now(),
|
||
deleteByRecipient: msg?.from === 'in',
|
||
});
|
||
addSignedMessageToChat({
|
||
chatId,
|
||
messageKey: String(msg?.messageKey || ''),
|
||
baseKey: String(msg?.baseKey || ''),
|
||
deleted: true,
|
||
});
|
||
if (activeEdit?.messageKey && activeEdit.messageKey === String(msg?.messageKey || '')) {
|
||
cancelEditMode({ restoreDraft: true });
|
||
}
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
};
|
||
|
||
const sendTextMessage = async (rawText) => {
|
||
const safeText = sanitizeUserDmTextForSend(String(rawText || ''));
|
||
const text = safeText.trim();
|
||
if (!text) return;
|
||
const editing = activeEdit;
|
||
const replying = !editing ? activeReply : null;
|
||
const finalText = editing
|
||
? `${String(editing?.prefixText || '')}${text}`
|
||
: `${replying ? buildDmReplyTechBlock({ baseKey: replying.baseKey }) : ''}${text}`;
|
||
|
||
// A new outgoing message immediately ends the visual "Новые сообщения" section.
|
||
// Do this before awaiting the server: the divider is a UI-session marker, not a
|
||
// delivery/read receipt indicator. Editing an existing message does not clear it.
|
||
if (!editing) {
|
||
hideUnreadSeparator({ rerender: false });
|
||
}
|
||
|
||
const tempId = editing ? '' : addOutgoingPendingMessage(chatId, text);
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
scrollToLatestMessageSmart(log, { smoothIfNearBottom: true });
|
||
|
||
try {
|
||
let result;
|
||
if (editing) {
|
||
result = await authService.sendDirectMessageRevision({
|
||
login: state.session.login,
|
||
toLogin: chatId,
|
||
text: finalText,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
timeMs: editing.timeMs,
|
||
nonce: editing.nonce,
|
||
revisionTimeMs: Date.now(),
|
||
});
|
||
} else {
|
||
result = await authService.sendDirectMessage({
|
||
login: state.session.login,
|
||
toLogin: chatId,
|
||
text: finalText,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
});
|
||
markOutgoingSent(tempId, {
|
||
messageKey: result?.outgoingKey || '',
|
||
baseKey: result?.baseKey || result?.localBaseKey || '',
|
||
deliveryState: result?.deliveryState || 'accepted',
|
||
});
|
||
}
|
||
|
||
const localRevisionApplied = await applyLocalRevision({
|
||
localOutgoingBlobB64: result?.localOutgoingBlobB64 || '',
|
||
fallbackMessageKey: result?.outgoingKey || '',
|
||
fallbackBaseKey: result?.baseKey || result?.localBaseKey || '',
|
||
deliveryState: result?.deliveryState || 'accepted',
|
||
});
|
||
|
||
if (editing) {
|
||
cancelEditMode({ restoreDraft: true });
|
||
} else if (replying) {
|
||
cancelReplyMode({ restoreDraft: false });
|
||
}
|
||
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
if (localRevisionApplied) {
|
||
notifyUnreadStateUpdated();
|
||
}
|
||
scrollToLatestMessageSmart(log, { smoothIfNearBottom: true });
|
||
window.requestAnimationFrame(() => scrollToLatestMessageSmart(log, { smoothIfNearBottom: true }));
|
||
window.setTimeout(() => scrollToLatestMessageSmart(log, { smoothIfNearBottom: true }), 220);
|
||
if (input) {
|
||
try {
|
||
input.focus({ preventScroll: true });
|
||
} catch {
|
||
input.focus();
|
||
}
|
||
}
|
||
addAppLogEntry({
|
||
level: 'info',
|
||
source: 'outgoing-dm',
|
||
message: editing ? t('screens.chat_view.text_094', { value1: chatId }) : t('screens.chat_view.text_095', { value1: chatId }),
|
||
details: {
|
||
toLogin: chatId,
|
||
messageId: result?.outgoingKey || '',
|
||
deliveredWsSessions: Number(result?.deliveredWsSessions || 0),
|
||
deliveredWebPushSessions: Number(result?.deliveredWebPushSessions || 0),
|
||
replyToBaseKey: replying?.baseKey || '',
|
||
},
|
||
});
|
||
} catch (e) {
|
||
// Текст возвращается в поле ввода, «часики» из ленты убираются; «Повторить» отправляет его снова.
|
||
removeOutgoingPending(tempId);
|
||
if (input) {
|
||
input.value = text;
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
updateSendButtonMode();
|
||
focusInputToEnd();
|
||
}
|
||
showToast(actionErrorText(activeEdit ? t('screens.chat_view.text_070') : t('screens.chat_view.text_071'), e), {
|
||
kind: 'error',
|
||
action: { label: t('screens.chat_view.text_033'), onClick: () => { if (!disposed) form.requestSubmit(); } },
|
||
});
|
||
addAppLogEntry({
|
||
level: 'warn',
|
||
source: 'outgoing-dm',
|
||
message: activeEdit ? t('screens.chat_view.text_072') : t('screens.chat_view.text_073'),
|
||
details: {
|
||
toLogin: chatId,
|
||
error: e?.message || 'unknown',
|
||
},
|
||
});
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
}
|
||
};
|
||
|
||
const sendFileAttachmentMessage = async (attachmentsInput) => {
|
||
const attachments = (Array.isArray(attachmentsInput) ? attachmentsInput : [attachmentsInput]).filter(Boolean);
|
||
if (!attachments.length) return;
|
||
if (attachments.length > 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')}`
|
||
: t('screens.chat_view.text_097', { value1: attachments.length }));
|
||
const finalText = `${replyBlock}${fileBlocks}${fallbackText}`;
|
||
|
||
hideUnreadSeparator({ rerender: false });
|
||
const tempId = addOutgoingPendingMessage(chatId, finalText);
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
scrollToLatestMessageSmart(log, { smoothIfNearBottom: true });
|
||
|
||
try {
|
||
const result = await authService.sendDirectMessage({
|
||
login: state.session.login,
|
||
toLogin: chatId,
|
||
text: finalText,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
});
|
||
markOutgoingSent(tempId, {
|
||
messageKey: result?.outgoingKey || '',
|
||
baseKey: result?.baseKey || result?.localBaseKey || '',
|
||
deliveryState: result?.deliveryState || 'accepted',
|
||
});
|
||
|
||
const localRevisionApplied = await applyLocalRevision({
|
||
localOutgoingBlobB64: result?.localOutgoingBlobB64 || '',
|
||
fallbackMessageKey: result?.outgoingKey || '',
|
||
fallbackBaseKey: result?.baseKey || result?.localBaseKey || '',
|
||
deliveryState: result?.deliveryState || 'accepted',
|
||
});
|
||
|
||
if (replying) cancelReplyMode({ restoreDraft: false });
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
if (localRevisionApplied) notifyUnreadStateUpdated();
|
||
scrollToLatestMessageSmart(log, { smoothIfNearBottom: true });
|
||
window.requestAnimationFrame(() => scrollToLatestMessageSmart(log, { smoothIfNearBottom: true }));
|
||
|
||
addAppLogEntry({
|
||
level: 'info',
|
||
source: onlyVoice ? 'outgoing-dm-voice' : 'outgoing-dm-file',
|
||
message: onlyVoice ? t('screens.chat_view.text_098', { value1: chatId }) : t('screens.chat_view.text_099', { value1: chatId }),
|
||
details: {
|
||
toLogin: chatId,
|
||
attachmentCount: attachments.length,
|
||
fileIds: attachments.map((attachment) => attachment?.id || ''),
|
||
totalFileSize: attachments.reduce((sum, attachment) => sum + Number(attachment?.size || 0), 0),
|
||
messageId: result?.outgoingKey || '',
|
||
replyToBaseKey: replying?.baseKey || '',
|
||
},
|
||
});
|
||
} catch (error) {
|
||
removeOutgoingPending(tempId);
|
||
addAppLogEntry({
|
||
level: 'warn',
|
||
source: onlyVoice ? 'outgoing-dm-voice' : 'outgoing-dm-file',
|
||
message: t('screens.chat_view.text_034'),
|
||
details: {
|
||
toLogin: chatId,
|
||
fileIds: attachments.map((attachment) => attachment?.id || ''),
|
||
error: error?.message || 'unknown',
|
||
},
|
||
});
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
throw error;
|
||
}
|
||
};
|
||
|
||
// Файлы уже лежат на сервере – повторить можно одно сообщение с ключами, без новой загрузки.
|
||
const offerAttachmentsRetry = (attachments, error) => {
|
||
showToast(actionErrorText(attachments.length === 1 ? t('screens.chat_view.text_075') : t('screens.chat_view.text_076'), error), {
|
||
kind: 'error',
|
||
action: {
|
||
label: t('screens.chat_view.text_035'),
|
||
onClick: async () => {
|
||
if (disposed) return;
|
||
try {
|
||
await sendFileAttachmentMessage(attachments);
|
||
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);
|
||
}
|
||
},
|
||
},
|
||
});
|
||
};
|
||
|
||
const handleSelectedFiles = async (fileList) => {
|
||
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 = Array.from(fileList || []).filter(Boolean);
|
||
if (!allFiles.length) return;
|
||
if (allFiles.length > DM_MAX_ATTACHMENTS_PER_MESSAGE) {
|
||
showToast(t('screens.chat_view.text_101', { value1: DM_MAX_ATTACHMENTS_PER_MESSAGE }), { kind: 'error', timeoutMs: 2200 });
|
||
return;
|
||
}
|
||
|
||
attachButtons.forEach((button) => {
|
||
button.disabled = true;
|
||
button.classList.add('is-busy');
|
||
});
|
||
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(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,
|
||
sessionId: state.session.sessionId,
|
||
wsUrl: authService.serverUrl,
|
||
onProgress: ({ processedBytes, totalBytes }) => {
|
||
if (!fileToggle || !totalBytes) return;
|
||
const percent = Math.min(100, Math.max(0, Math.round((processedBytes / totalBytes) * 100)));
|
||
fileToggle.title = `${index + 1}/${allFiles.length} · ${percent}%`;
|
||
},
|
||
});
|
||
attachments.push(attachment);
|
||
}
|
||
uploaded = true;
|
||
await sendFileAttachmentMessage(attachments);
|
||
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' });
|
||
} finally {
|
||
attachButtons.forEach((button) => {
|
||
button.disabled = false;
|
||
button.classList.remove('is-busy');
|
||
});
|
||
if (fileToggle) {
|
||
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 = ''; });
|
||
}
|
||
};
|
||
|
||
const forwardMessageToChat = async (msg, targetLogin) => {
|
||
const targetChatId = normalizeDmChatId(targetLogin);
|
||
if (!targetChatId) throw new Error(t('screens.chat_view.text_081'));
|
||
const finalText = buildForwardedDmText(msg);
|
||
if (!String(finalText || '').trim()) throw new Error(t('screens.chat_view.text_082'));
|
||
|
||
const tempId = addOutgoingPendingMessage(targetChatId, finalText);
|
||
if (targetChatId === chatId) {
|
||
hideUnreadSeparator({ rerender: false });
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
scrollToLatestMessageSmart(log, { smoothIfNearBottom: true });
|
||
}
|
||
|
||
try {
|
||
const result = await authService.sendDirectMessage({
|
||
login: state.session.login,
|
||
toLogin: targetChatId,
|
||
text: finalText,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
});
|
||
markOutgoingSent(tempId, {
|
||
messageKey: result?.outgoingKey || '',
|
||
baseKey: result?.baseKey || result?.localBaseKey || '',
|
||
deliveryState: result?.deliveryState || 'accepted',
|
||
});
|
||
if (targetChatId === chatId) {
|
||
renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
scrollToLatestMessageSmart(log, { smoothIfNearBottom: true });
|
||
}
|
||
addAppLogEntry({
|
||
level: 'info',
|
||
source: 'outgoing-dm-forward',
|
||
message: t('screens.chat_view.text_104', { value1: targetChatId }),
|
||
details: {
|
||
toLogin: targetChatId,
|
||
sourceChatId: chatId,
|
||
messageId: result?.outgoingKey || '',
|
||
},
|
||
});
|
||
} catch (error) {
|
||
// Неотправленное не остаётся в ленте «часиками»; ошибку с причиной покажет окно пересылки.
|
||
removeOutgoingPending(tempId);
|
||
if (targetChatId === chatId) renderChatLog({ scrollMode: 'latest', markAsRead: false });
|
||
throw error;
|
||
}
|
||
};
|
||
|
||
const handleOpenActions = (msg, event) => {
|
||
const parsed = parseDmTechBlocks(String(msg?.text || ''));
|
||
const readState = resolveEffectiveReadState(getChatMessages(chatId), msg);
|
||
openMessageActionsMenu({
|
||
anchorX: Number(event?.clientX || 0),
|
||
anchorY: Number(event?.clientY || 0),
|
||
messageText: parsed?.displayText || msg?.text || '',
|
||
infoText: (msg?.from === 'out' && readState.readAtMs > 0)
|
||
? t('screens.chat_view.text_105', { value1: formatMessageTime(readState.readAtMs) })
|
||
: '',
|
||
canReply: true,
|
||
canForward: true,
|
||
showReadAloud: isTextToSpeechReady,
|
||
canEdit: msg?.from === 'out' && Number(msg?.messageType || 0) === 2 && !parsed?.callSummary && !(parsed?.fileAttachments?.length || parsed?.fileAttachment),
|
||
canDelete: (
|
||
(msg?.from === 'out' && Number(msg?.messageType || 0) === 2)
|
||
|| (msg?.from === 'in' && Number(msg?.messageType || 0) === 1)
|
||
),
|
||
onReply: async () => {
|
||
startReplyMode(msg);
|
||
},
|
||
onForward: async () => {
|
||
await openForwardMessageDialog({
|
||
message: msg,
|
||
sourceChatId: chatId,
|
||
onConfirm: async (targetLogin) => forwardMessageToChat(msg, targetLogin),
|
||
});
|
||
},
|
||
onReadAloud: async () => handleReadAloud(msg),
|
||
onEdit: async () => {
|
||
startEditMode(msg);
|
||
},
|
||
onDelete: async () => {
|
||
openDeleteMessageConfirmModal({
|
||
onConfirm: async () => {
|
||
try {
|
||
await sendDeleteRevision(msg);
|
||
} catch (error) {
|
||
showToast(actionErrorText(t('dialogs.final.chat.confirm_delete_message_error'), error), { kind: 'error' });
|
||
}
|
||
},
|
||
});
|
||
},
|
||
});
|
||
};
|
||
|
||
const loadHistoryPage = async ({ preserveScroll = false } = {}) => {
|
||
if (historyLoading) return;
|
||
if (historyBootstrapped && !historyHasMore) return;
|
||
historyLoading = true;
|
||
const isBootstrap = !historyBootstrapped;
|
||
const messagesBefore = JSON.stringify(getChatMessages(chatId));
|
||
let pageAddedNothing = false;
|
||
// При открытии чата сообщения из памяти уже на экране – их обновление идёт тихо.
|
||
if (!isBootstrap || !getChatMessages(chatId).length) setHistoryLoadingState(true);
|
||
const scrollContainer = boundScrollContainer || log.closest('.screen-content') || wrap.parentElement || wrap;
|
||
const prevScrollTop = Number(scrollContainer?.scrollTop || 0);
|
||
const prevScrollHeight = Number(scrollContainer?.scrollHeight || 0);
|
||
try {
|
||
const payload = await authService.getDirectMessages({
|
||
peerLogin: chatId,
|
||
limit: DM_HISTORY_PAGE_SIZE,
|
||
beforeTimeMs: historyBootstrapped ? historyNextBeforeTimeMs : 0,
|
||
beforeMessageKey: historyBootstrapped ? historyNextBeforeMessageKey : '',
|
||
});
|
||
if (payload?.peer) {
|
||
peerRelationType = normalizeChatRelationType(payload.peer.relationType);
|
||
updateHeaderPeer(payload.peer);
|
||
rememberDmPeer({ login: chatId, ...payload.peer });
|
||
}
|
||
await mergeDirectMessagesPage(chatId, payload?.messages || []);
|
||
historyHasMore = Boolean(payload?.hasMore);
|
||
historyNextBeforeTimeMs = Number(payload?.nextBeforeTimeMs || 0);
|
||
historyNextBeforeMessageKey = String(payload?.nextBeforeMessageKey || '').trim();
|
||
historyBootstrapped = true;
|
||
// Вся история уже в памяти (её загрузил поиск или «Медиа и файлы») – листать сервер дальше незачем.
|
||
if (isDmHistoryFullyLoaded(chatId)) historyHasMore = false;
|
||
else if (!historyHasMore) markDmHistoryFullyLoaded(chatId);
|
||
let scrollModeAfterLoad = isBootstrap ? 'latest' : (preserveScroll ? 'preserve' : 'latest');
|
||
if (isBootstrap) {
|
||
const firstUnread = getChatMessages(chatId).find((msg) => msg?.from === 'in' && msg?.unread);
|
||
if (firstUnread?.messageKey) {
|
||
unreadSeparatorVisible = true;
|
||
unreadSeparatorAnchorMessageKey = String(firstUnread.messageKey);
|
||
stickToBottom = false;
|
||
scrollModeAfterLoad = 'unread';
|
||
}
|
||
}
|
||
// Страница уже была в памяти: перерисовка не нужна, лента не дёргается.
|
||
if (messagesBefore === JSON.stringify(getChatMessages(chatId))) {
|
||
pageAddedNothing = true;
|
||
void sendReadReceiptsForVisible(chatId);
|
||
return;
|
||
}
|
||
renderChatLog({ markAsRead: false, scrollMode: scrollModeAfterLoad });
|
||
if (scrollModeAfterLoad === 'preserve') {
|
||
window.requestAnimationFrame(() => {
|
||
const nextHeight = Number(scrollContainer?.scrollHeight || 0);
|
||
scrollContainer.scrollTop = Math.max(0, prevScrollTop + (nextHeight - prevScrollHeight));
|
||
});
|
||
} else if (scrollModeAfterLoad === 'unread') {
|
||
window.requestAnimationFrame(() => scrollToUnreadSeparator(log));
|
||
} else {
|
||
window.requestAnimationFrame(() => scrollToLatestMessage(log));
|
||
}
|
||
void sendReadReceiptsForVisible(chatId);
|
||
} catch (error) {
|
||
addAppLogEntry({
|
||
level: 'warn',
|
||
source: 'dm-history',
|
||
message: t('screens.chat_view.text_037'),
|
||
details: { chatId, error: error?.message || 'unknown' },
|
||
});
|
||
} finally {
|
||
historyLoading = false;
|
||
setHistoryLoadingState(false);
|
||
// Лента не выросла, а пользователь всё ещё у верха – события scroll не будет, грузим дальше сами.
|
||
if (pageAddedNothing) window.setTimeout(() => handleHistoryScroll(), 0);
|
||
}
|
||
};
|
||
|
||
const handleHistoryScroll = () => {
|
||
const scrollContainer = boundScrollContainer || log.closest('.screen-content') || wrap.parentElement || wrap;
|
||
if (!scrollContainer) return;
|
||
if (Number(scrollContainer.scrollTop || 0) > 120) return;
|
||
if (!historyBootstrapped || !historyHasMore || historyLoading) return;
|
||
void loadHistoryPage({ preserveScroll: true });
|
||
};
|
||
|
||
editCancelBtn?.addEventListener('click', () => {
|
||
if (activeEdit) {
|
||
cancelEditMode({ restoreDraft: true });
|
||
return;
|
||
}
|
||
cancelReplyMode({ restoreDraft: true });
|
||
});
|
||
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
updateSendButtonMode();
|
||
input?.addEventListener('input', () => {
|
||
rememberEmojiSelection();
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
updateSendButtonMode();
|
||
});
|
||
input?.addEventListener('select', rememberEmojiSelection);
|
||
input?.addEventListener('keyup', rememberEmojiSelection);
|
||
input?.addEventListener('click', rememberEmojiSelection);
|
||
input?.addEventListener('focus', () => {
|
||
rememberEmojiSelection();
|
||
inputFocused = true;
|
||
syncComposerLayout();
|
||
window.requestAnimationFrame(() => {
|
||
if (inputFocused) scrollToLatestMessage(log);
|
||
});
|
||
});
|
||
input?.addEventListener('blur', () => {
|
||
inputFocused = false;
|
||
window.setTimeout(syncComposerLayout, 0);
|
||
});
|
||
emojiToggle?.setAttribute('aria-expanded', 'false');
|
||
emojiToggle?.addEventListener('pointerdown', (event) => {
|
||
rememberEmojiSelection();
|
||
emojiLongPressTriggered = false;
|
||
clearEmojiLongPress();
|
||
try {
|
||
emojiToggle.setPointerCapture?.(event.pointerId);
|
||
} catch {
|
||
// Pointer capture is optional; long press still works without it.
|
||
}
|
||
event.preventDefault();
|
||
});
|
||
emojiToggle?.addEventListener('pointerup', clearEmojiLongPress);
|
||
emojiToggle?.addEventListener('pointercancel', clearEmojiLongPress);
|
||
emojiToggle?.addEventListener('pointerleave', (event) => {
|
||
if (event.buttons) clearEmojiLongPress();
|
||
});
|
||
emojiToggle?.addEventListener('click', (event) => {
|
||
if (emojiLongPressTriggered) {
|
||
emojiLongPressTriggered = false;
|
||
event.preventDefault();
|
||
return;
|
||
}
|
||
setFileActionVisible(false);
|
||
emojiPickerOpen = !emojiPickerOpen;
|
||
emojiSlot.hidden = !emojiPickerOpen;
|
||
emojiToggle.setAttribute('aria-expanded', String(emojiPickerOpen));
|
||
syncComposerLayout();
|
||
// Либо клавиатура, либо пикер. На тач-устройствах при
|
||
// открытии пикера прячем клавиатуру, чтобы поле ввода оставалось видно.
|
||
if (emojiPickerOpen && !isFinePointer) input?.blur();
|
||
});
|
||
attachSources.forEach(([button, picker]) => {
|
||
button?.addEventListener('click', () => {
|
||
if (!fileTransferEnabled || button.disabled) return;
|
||
picker?.click();
|
||
});
|
||
picker?.addEventListener('change', () => {
|
||
const files = Array.from(picker.files || []);
|
||
if (files.length) void handleSelectedFiles(files);
|
||
});
|
||
});
|
||
screen.addEventListener('pointerdown', (event) => {
|
||
if (form.contains(event.target)) return;
|
||
if (emojiPickerOpen) closeEmojiPicker();
|
||
if (fileActionVisible) setFileActionVisible(false);
|
||
});
|
||
|
||
sendBtn?.addEventListener('pointerdown', (event) => {
|
||
const mode = String(sendBtn.dataset.mode || 'voice');
|
||
if (mode === 'busy') {
|
||
event.preventDefault();
|
||
return;
|
||
}
|
||
if (mode === 'send') {
|
||
try {
|
||
input?.focus({ preventScroll: true });
|
||
} catch {
|
||
input?.focus();
|
||
}
|
||
return;
|
||
}
|
||
if (mode === 'stop') {
|
||
event.preventDefault();
|
||
suppressVoiceClick = true;
|
||
stopVoiceRecording({ send: true });
|
||
return;
|
||
}
|
||
event.preventDefault();
|
||
voicePointerHeld = true;
|
||
voiceReleaseRequested = false;
|
||
voiceStartY = Number(event.clientY || 0);
|
||
voicePointerId = event.pointerId;
|
||
try { sendBtn.setPointerCapture?.(event.pointerId); } catch { /* optional */ }
|
||
void startVoiceRecording({ pointerY: voiceStartY, pointerId: event.pointerId });
|
||
});
|
||
|
||
sendBtn?.addEventListener('pointermove', (event) => {
|
||
if (!voicePointerHeld || voiceLocked || voicePointerId !== event.pointerId) return;
|
||
if (!voiceRecorder || voiceRecorder.state === 'inactive') return;
|
||
if (Number(event.clientY || 0) <= voiceStartY - 64) {
|
||
voiceLocked = true;
|
||
voiceReleaseRequested = false;
|
||
if (voiceHint) voiceHint.textContent = t('dialogs.modals.chat_view.label_036');
|
||
updateSendButtonMode();
|
||
try { navigator.vibrate?.(18); } catch { /* ignore */ }
|
||
}
|
||
});
|
||
|
||
const finishVoicePointerGesture = (event) => {
|
||
if (!voicePointerHeld && voicePointerId == null) return;
|
||
if (voicePointerId != null && event.pointerId !== voicePointerId) return;
|
||
voicePointerHeld = false;
|
||
voiceReleaseRequested = true;
|
||
try { sendBtn?.releasePointerCapture?.(event.pointerId); } catch { /* optional */ }
|
||
voicePointerId = null;
|
||
if (!voiceLocked) {
|
||
suppressVoiceClick = true;
|
||
stopVoiceRecording({ send: true });
|
||
}
|
||
};
|
||
sendBtn?.addEventListener('pointerup', finishVoicePointerGesture);
|
||
sendBtn?.addEventListener('pointercancel', finishVoicePointerGesture);
|
||
sendBtn?.addEventListener('contextmenu', (event) => {
|
||
if (String(sendBtn.dataset.mode || '') !== 'send') event.preventDefault();
|
||
});
|
||
sendBtn?.addEventListener('click', (event) => {
|
||
event.preventDefault();
|
||
if (suppressVoiceClick) {
|
||
suppressVoiceClick = false;
|
||
return;
|
||
}
|
||
const mode = String(sendBtn.dataset.mode || 'voice');
|
||
if (mode === 'send') {
|
||
form.requestSubmit();
|
||
} else if (mode === 'stop') {
|
||
stopVoiceRecording({ send: true });
|
||
}
|
||
});
|
||
|
||
// Только обычный Enter отправляет текст. С модификаторами Enter остаётся переносом строки.
|
||
// IME-композиция не должна случайно отправлять незавершённый ввод.
|
||
input.addEventListener('keydown', (event) => {
|
||
if (!isDmSendEnter(event)) return;
|
||
event.preventDefault();
|
||
if (String(input.value || '').trim()) form.requestSubmit();
|
||
});
|
||
|
||
form.addEventListener('submit', async (event) => {
|
||
event.preventDefault();
|
||
const text = String(input.value || '').trim();
|
||
if (!text) return;
|
||
input.value = '';
|
||
autoResizeComposer(input);
|
||
syncComposerLayout();
|
||
updateSendButtonMode();
|
||
closeEmojiPicker();
|
||
await sendTextMessage(text);
|
||
focusInputToEnd();
|
||
});
|
||
|
||
const handleIncomingChatRefresh = async (event) => {
|
||
const updatedChatId = normalizeDmChatId(event?.detail?.chatId);
|
||
if (updatedChatId !== chatId) return;
|
||
// Если диалог уже открыт, новое входящее сразу показывается в текущем потоке и не создаёт
|
||
// новый визуальный разделитель «Новые сообщения». Такой разделитель относится только к
|
||
// непрочитанным, которые существовали ДО открытия экрана чата.
|
||
preserveComposerSelection(input, () => {
|
||
renderChatLog({ scrollMode: 'latest' });
|
||
});
|
||
window.requestAnimationFrame(() => scrollToLatestMessage(log));
|
||
void sendReadReceiptsForVisible(chatId);
|
||
};
|
||
|
||
const handleDeliveryRefresh = () => {
|
||
preserveComposerSelection(input, () => {
|
||
renderChatLog({ scrollMode: 'preserve', markAsRead: false });
|
||
});
|
||
};
|
||
|
||
window.addEventListener('shine-chat-messages-updated', handleIncomingChatRefresh);
|
||
window.addEventListener('shine-dm-delivery-updated', handleDeliveryRefresh);
|
||
// Срок «без звука» вышел или звук переключили из списка чатов – значок в шапке следует за этим.
|
||
const handleChatPrefsUpdated = () => { if (!disposed) chatHeaderParts?.setMuted(isDmChatMuted(chatId)); };
|
||
window.addEventListener(DM_CHAT_PREFS_EVENT, handleChatPrefsUpdated);
|
||
|
||
wrap.append(historyLoader, log);
|
||
screen.append(wrap);
|
||
// Лента у низа остаётся у низа, когда её высота меняется сама (догрузилась картинка, пришло сообщение).
|
||
let stickToBottom = !hasUnreadIncoming; // с непрочитанными чат открывается на разделителе, а не внизу
|
||
wrap.addEventListener('scroll', () => {
|
||
stickToBottom = wrap.scrollHeight - wrap.scrollTop - wrap.clientHeight < 80;
|
||
}, { passive: true });
|
||
const logResizeObserver = typeof ResizeObserver === 'function'
|
||
? new ResizeObserver(() => { if (stickToBottom) wrap.scrollTop = wrap.scrollHeight; })
|
||
: null;
|
||
logResizeObserver?.observe(log);
|
||
chrome?.setComposer(form);
|
||
renderLog(log, chatId, {
|
||
onOpenActions: handleOpenActions,
|
||
navigate,
|
||
markAsRead: false,
|
||
scrollMode: hasUnreadIncoming ? 'unread' : 'latest',
|
||
showUnreadSeparator: unreadSeparatorVisible,
|
||
unreadSeparatorMessageKey: unreadSeparatorAnchorMessageKey,
|
||
});
|
||
window.setTimeout(() => {
|
||
if (markChatRead(chatId) > 0) {
|
||
notifyUnreadStateUpdated();
|
||
}
|
||
}, 220);
|
||
void sendReadReceiptsForVisible(chatId);
|
||
window.requestAnimationFrame(() => {
|
||
boundScrollContainer = wrap;
|
||
boundScrollContainer?.addEventListener('scroll', handleHistoryScroll, { passive: true });
|
||
void loadHistoryPage({ preserveScroll: true });
|
||
});
|
||
screen.cleanup = () => {
|
||
if (disposed) return;
|
||
disposed = true;
|
||
window.clearTimeout(searchDebounce);
|
||
// После ухода со страницы запись поиска в истории уже не текущая: close() только снимает слой.
|
||
search?.layer?.close();
|
||
search = null;
|
||
dateJumpModal?.close();
|
||
hideUnreadSeparator({ rerender: false });
|
||
stopAllTwemojiAnimations();
|
||
clearEmojiLongPress();
|
||
try { stopVoiceRecording({ send: false }); } catch { /* ignore */ }
|
||
clearVoiceTimer();
|
||
stopVoiceStreamTracks();
|
||
window.removeEventListener('shine-chat-messages-updated', handleIncomingChatRefresh);
|
||
window.removeEventListener('shine-dm-delivery-updated', handleDeliveryRefresh);
|
||
window.removeEventListener(DM_CHAT_PREFS_EVENT, handleChatPrefsUpdated);
|
||
boundScrollContainer?.removeEventListener('scroll', handleHistoryScroll);
|
||
logResizeObserver?.disconnect();
|
||
};
|
||
return screen;
|
||
}
|
||
|
||
async function sendReadReceiptsForVisible(chatId) {
|
||
const pending = getChatMessages(chatId)
|
||
.filter((row) => row?.from === 'in' && Number(row?.messageType) === 1 && !row?.readReceiptSent)
|
||
.slice(0, 50);
|
||
for (const row of pending) {
|
||
const ref = parseBaseKey(row.baseKey);
|
||
if (!ref) continue;
|
||
try {
|
||
await authService.sendReadReceipt({
|
||
login: state.session.login,
|
||
toLogin: ref.fromLogin,
|
||
storagePwd: state.session.storagePwdInMemory,
|
||
refToLogin: ref.toLogin,
|
||
refFromLogin: ref.fromLogin,
|
||
refTimeMs: ref.timeMs,
|
||
refNonce: ref.nonce,
|
||
});
|
||
if (row.baseKey) {
|
||
markReadReceiptSentByBaseKey(row.baseKey);
|
||
} else {
|
||
row.readReceiptSent = true;
|
||
}
|
||
} catch (e) {
|
||
addAppLogEntry({
|
||
level: 'warn',
|
||
source: 'read-receipt',
|
||
message: t('screens.chat_view.text_038'),
|
||
details: { chatId, messageKey: row.messageKey || '', error: e?.message || 'unknown' },
|
||
});
|
||
}
|
||
}
|
||
}
|