Files
SHiNE-server/shine-UI/js/components/channel-editor.js
T

482 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { t, th } from '../i18n/index.js';
import { iconHtml } from './ui-icon.js';
import { confirmPublicHistoryAction } from '../services/public-history-consent.js';
import { markArweaveAttachmentPlaced } from './arweave-attachment-manager.js';
import { openChannelAttachmentManager } from './channel-attachment-manager.js';
import { composeMessageWithAttachments, MAX_MESSAGE_ATTACHMENTS } from '../services/attachment-format.js';
import { state } from '../state.js';
import { toUserMessage } from '../services/ui-error-texts.js';
import { renderUserAvatar } from './avatar-image.js';
import { openAuthRequiredModal } from '../services/auth-required-modal.js';
import { resolvePublicFileUrl } from '../services/public-file-service.js';
import { openHistoryLayer } from '../router.js';
const drafts = new Map();
function draftKey(key) {
const login = String(state.session.login || 'guest').trim().toLowerCase();
return `${login}:${String(key || 'editor')}`;
}
// Превью вложения в редакторе: картинки и видео – миниатюрой (как в Threads), остальное – строкой с именем.
const previewUrls = new Map();
function attachmentKind(item) {
const name = String(item?.name || '').toLowerCase();
if (/\.(jpe?g|png|gif|webp|avif|heic|bmp)$/.test(name)) return 'image';
if (/\.(mp4|webm|mov|m4v|ogv)$/.test(name)) return 'video';
return 'file';
}
function attachmentPreviewUrl(item, login) {
const key = item?.ar ? `ar:${item.ar}` : `sha:${item?.sha256 || ''}`;
if (!previewUrls.has(key)) {
previewUrls.set(key, item?.ar
? Promise.resolve(`${String(state.entrySettings.arweaveServer || 'https://arweave.net').replace(/\/$/, '')}/${item.ar}`)
: resolvePublicFileUrl({ sha256: item?.sha256, authorLogin: login, solanaEndpoint: state.entrySettings.solanaServer, fallbackServerLogin: state.entrySettings.shineServerLogin }).catch(() => ''));
}
return previewUrls.get(key);
}
function attachmentLabel(item) {
const name = String(item?.name || t('screens.channel_editor.text_012'));
const size = Number(item?.size || 0);
if (!size) return name;
if (size < 1024) return t('screens.channel_editor.text_017', { value1: name, value2: size });
if (size < 1024 * 1024) return t('screens.channel_editor.text_018', { value1: name, value2: Math.ceil(size / 1024) });
return t('screens.channel_editor.text_019', { value1: name, value2: (size / 1024 / 1024).toFixed(1) });
}
export function openChannelEditor({
id = 'channel-editor',
title = 'Ответ',
submitLabel = 'Ответить',
placeholder = 'Напишите ответ',
context = null,
destination = '',
key = 'reply',
extraControl = null,
initialText = '',
allowEmptyText = false,
allowAttachments = true,
rawText = false,
openAttachOnStart = false,
onSubmit,
isActive = () => true,
} = {}) {
if (!state.session.isAuthorized) {
openAuthRequiredModal({ title: t('dialogs.components.channel_editor.title_001'), text: t('dialogs.components.channel_editor.text_002') });
return null;
}
const root = document.getElementById('modal-root');
if (!root || typeof onSubmit !== 'function') return null;
if (root.querySelector('.channel-editor-overlay')) return null;
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
const storageKey = draftKey(key);
const login = state.session.login;
const saved = drafts.get(storageKey) || { text: initialText, attachments: [] };
const attachments = Array.isArray(saved.attachments) ? [...saved.attachments] : [];
const extraFields = extraControl ? [...extraControl.querySelectorAll('select,input')] : [];
extraFields.forEach((field, index) => {
if (saved.controls?.[index] !== undefined) field.value = saved.controls[index];
});
let inFlight = false;
let composing = false;
let closed = false;
let picking = false;
let completed = false;
const attachmentController = new AbortController();
const overlay = document.createElement('div');
overlay.className = 'channel-editor-overlay';
overlay.id = id;
overlay.setAttribute('role', 'dialog');
overlay.setAttribute('aria-modal', 'true');
overlay.setAttribute('aria-labelledby', `${id}-title`);
const dialog = document.createElement('div');
dialog.className = 'channel-editor';
const header = document.createElement('header');
header.className = 'channel-editor__header';
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.className = 'icon-btn channel-editor__close';
closeButton.setAttribute('aria-label', t('screens.channel_editor.text_025'));
closeButton.innerHTML = iconHtml('close');
const heading = document.createElement('h2');
heading.id = `${id}-title`;
heading.textContent = title;
// Закрытие не теряет текст: черновик хранится до отправки
const draftMark = document.createElement('span');
draftMark.className = 'channel-editor__draft';
draftMark.textContent = t('screens.channel_editor.text_001');
const headerEnd = document.createElement('div');
headerEnd.className = 'channel-editor__header-end';
header.append(closeButton, heading, headerEnd);
const body = document.createElement('div');
body.className = 'channel-editor__body';
// Цепочка как в Threads: исходная запись и ответы до той, на которую отвечаем, сверху вниз, соединены линией.
// Поле ввода – последним звеном; к началу цепочки – прокруткой вверх.
const chain = Array.isArray(context?.chain) ? context.chain.filter(Boolean) : [];
if (chain.length) {
const chainBox = document.createElement('ol');
chainBox.className = 'channel-editor__chain';
chainBox.setAttribute('aria-label', t('screens.channel_editor.text_026'));
chain.forEach((item) => {
const row = document.createElement('li');
row.className = 'channel-editor__chain-item';
const avatar = item.avatar instanceof Node ? item.avatar : renderUserAvatar({ login: item.author || 'unknown', className: 'avatar-plain', size: 'sm' });
avatar.classList.add('channel-editor__chain-avatar');
const main = document.createElement('div');
main.className = 'channel-editor__chain-main';
const head = document.createElement('div');
head.className = 'channel-editor__chain-head';
const name = document.createElement('strong');
name.textContent = String(item.title || item.author || '');
head.append(name);
if (item.time) {
const time = document.createElement('span');
time.textContent = item.time;
head.append(time);
}
const text = document.createElement('p');
text.textContent = String(item.text || item.attachmentLabel || t('screens.channel_editor.text_013'));
main.append(head, text);
row.append(avatar, main);
chainBox.append(row);
});
body.append(chainBox);
} else if (context && (context.author || context.text || context.attachmentLabel)) {
const contextBox = document.createElement('div');
contextBox.className = 'channel-editor__context';
const contextTitle = document.createElement('strong');
contextTitle.textContent = context.author ? t('screens.channel_editor.text_020', { value1: context.author }) : t('screens.channel_editor.text_009');
const quote = document.createElement('p');
quote.textContent = String(context.text || context.attachmentLabel || t('screens.channel_editor.text_014'));
const expand = document.createElement('button');
expand.type = 'button';
expand.className = 'text-btn channel-editor__context-toggle';
expand.textContent = t('screens.channel_editor.text_002');
expand.setAttribute('aria-expanded', 'false');
expand.addEventListener('click', () => {
const expanded = contextBox.classList.toggle('is-expanded');
expand.textContent = expanded ? t('screens.channel_editor.text_010') : t('screens.channel_editor.text_011');
expand.setAttribute('aria-expanded', String(expanded));
});
contextBox.append(contextTitle, quote, expand);
body.append(contextBox);
}
const textarea = document.createElement('textarea');
textarea.className = 'channel-editor__input';
textarea.rows = 1;
textarea.maxLength = 2000;
textarea.placeholder = placeholder;
textarea.setAttribute('aria-label', placeholder);
textarea.value = String(saved.text || '');
const attachmentsBox = document.createElement('div');
attachmentsBox.className = 'channel-editor__attachments';
attachmentsBox.setAttribute('aria-live', 'polite');
const error = document.createElement('p');
error.className = 'channel-editor__error';
error.setAttribute('role', 'alert');
const clearButton = document.createElement('button');
clearButton.type = 'button';
clearButton.className = 'text-btn channel-editor__clear';
clearButton.textContent = t('screens.channel_editor.text_003');
const author = document.createElement('div');
author.className = 'channel-editor__author';
author.append(renderUserAvatar({ login: login || 'guest', className: 'avatar-plain', size: 'md' }));
const authorText = document.createElement('span');
authorText.className = 'channel-editor__author-text';
const authorName = document.createElement('strong');
authorName.textContent = login || t('screens.channel_editor.text_015');
authorText.append(authorName);
if (destination) {
const where = document.createElement('small');
where.textContent = destination;
authorText.append(where);
}
author.append(authorText);
if (chain.length) author.classList.add('is-chained');
body.append(author);
const footer = document.createElement('footer');
footer.className = 'channel-editor__footer';
const attachButton = document.createElement('button');
attachButton.type = 'button';
attachButton.className = 'icon-btn channel-editor__attach';
attachButton.innerHTML = `${iconHtml('image')}<span class="sr-only">${th('screens.channel_editor.text_024')}</span>`;
attachButton.title = t('screens.channel_editor.text_004');
attachButton.hidden = !allowAttachments;
// Как в Threads: текст пишется прямо под именем, без рамки; под ним – вложения.
// «Прикрепить» – в нижней панели у кнопки отправки, «Очистить» – в шапке, пока есть что очищать.
const compose = document.createElement('div');
compose.className = 'channel-editor__compose';
compose.append(textarea, attachmentsBox, error);
authorText.append(compose);
headerEnd.append(clearButton, draftMark);
const counter = document.createElement('span');
counter.className = 'channel-editor__counter';
const submitButton = document.createElement('button');
submitButton.type = 'button';
submitButton.className = 'primary-btn channel-editor__submit';
submitButton.textContent = submitLabel;
submitButton.title = t('screens.channel_editor.text_005');
footer.append(attachButton);
if (extraControl instanceof Node) {
footer.classList.add('has-extra');
footer.append(extraControl);
}
footer.append(counter, submitButton);
dialog.append(header, body, footer);
overlay.append(dialog);
root.replaceChildren(overlay);
const saveDraft = () => {
const value = { text: textarea.value, attachments: [...attachments], controls: extraFields.map((field) => field.value) };
if (completed) { drafts.delete(storageKey); return; }
if (value.text || value.attachments.length) drafts.set(storageKey, value);
else drafts.delete(storageKey);
};
const sync = () => {
textarea.style.height = 'auto';
textarea.style.height = `${Math.max(24, textarea.scrollHeight)}px`;
const length = textarea.value.length;
counter.textContent = `${length} / 2000`;
counter.classList.toggle('is-near-limit', length >= 1800);
// Счётчик нужен только у предела, пустой «0 / 2000» лишь шумит.
counter.classList.toggle('is-hidden', length < 1500);
submitButton.disabled = inFlight || picking || length > textarea.maxLength || (!allowEmptyText && !textarea.value.trim() && attachments.length === 0);
dialog.setAttribute('aria-busy', String(inFlight || picking));
clearButton.hidden = !textarea.value && attachments.length === 0;
draftMark.hidden = !clearButton.hidden;
attachmentsBox.replaceChildren();
attachments.forEach((item, index) => {
const kind = attachmentKind(item);
if (kind !== 'file') {
const thumb = document.createElement('div');
thumb.className = `channel-editor__thumb channel-editor__thumb--${kind}`;
thumb.title = attachmentLabel(item);
const media = document.createElement(kind === 'image' ? 'img' : 'video');
if (kind === 'image') media.alt = String(item?.name || t('screens.channel_editor.text_016'));
else { media.muted = true; media.preload = 'metadata'; media.playsInline = true; }
void attachmentPreviewUrl(item, login).then((url) => { if (url && media.isConnected !== false) media.src = url; });
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'channel-editor__thumb-remove';
remove.setAttribute('aria-label', t('screens.channel_editor.text_021', { value1: item?.name || '' }));
remove.innerHTML = iconHtml('close');
remove.disabled = inFlight;
remove.addEventListener('click', () => {
attachments.splice(index, 1);
saveDraft();
sync();
});
thumb.append(media, remove);
attachmentsBox.append(thumb);
return;
}
const card = document.createElement('div');
card.className = 'channel-editor__attachment';
const label = document.createElement('span');
label.textContent = attachmentLabel(item);
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'icon-btn';
remove.setAttribute('aria-label', t('screens.channel_editor.text_022', { value1: item?.name || '' }));
remove.textContent = '×';
remove.disabled = inFlight;
remove.addEventListener('click', () => {
attachments.splice(index, 1);
saveDraft();
sync();
});
card.append(label, remove);
attachmentsBox.append(card);
});
};
// «Назад» закрывает редактор, а не уводит со страницы; слой в истории ведёт роутер.
const historyLayer = openHistoryLayer(() => close({ fromHistory: true }));
const viewport = window.visualViewport;
const updateViewport = () => {
overlay.style.setProperty('--editor-height', `${viewport?.height || window.innerHeight}px`);
overlay.style.setProperty('--editor-top', `${viewport?.offsetTop || 0}px`);
};
const observer = new MutationObserver(() => {
if (!overlay.isConnected) close({ restoreFocus: false });
});
const close = ({ fromHistory = false, restoreFocus = true } = {}) => {
if (closed) return;
closed = true;
saveDraft();
observer.disconnect();
attachmentController.abort();
document.removeEventListener('keydown', onDocumentKeydown);
viewport?.removeEventListener('resize', updateViewport);
viewport?.removeEventListener('scroll', updateViewport);
window.removeEventListener('resize', updateViewport);
overlay.remove();
if (!fromHistory) historyLayer.close();
if (restoreFocus && opener?.isConnected) opener.focus({ preventScroll: true });
};
overlay.cleanup = () => close({ restoreFocus: false });
const submit = async () => {
if (inFlight || submitButton.disabled) return;
inFlight = true;
error.textContent = '';
textarea.disabled = true;
attachButton.disabled = true;
clearButton.disabled = true;
if (extraControl) extraControl.querySelectorAll('select,button,input').forEach((el) => { el.disabled = true; });
submitButton.textContent = t('screens.channel_editor.text_006');
sync();
try {
const accepted = await confirmPublicHistoryAction({
title: t('dialogs.final.consent.publish_title'),
aboveEditor: true,
text: t('dialogs.final.consent.publish_warning'),
confirmLabel: t('dialogs.final.consent.publish_accept'),
cancelLabel: t('dialogs.final.consent.return_to_draft'),
});
if (!isActive() || closed) return;
if (!accepted) {
inFlight = false;
textarea.disabled = false;
attachButton.disabled = false;
clearButton.disabled = false;
if (extraControl) extraControl.querySelectorAll('select,button,input').forEach((el) => { el.disabled = false; });
submitButton.textContent = submitLabel;
saveDraft();
sync();
return;
}
await onSubmit({
text: rawText ? textarea.value.trim() : composeMessageWithAttachments(textarea.value.trim(), attachments),
attachments: [...attachments],
});
completed = true;
attachments.filter((item) => item?.ar).forEach((item) => markArweaveAttachmentPlaced(login, item));
// Не удаляем новый черновик, открытый после закрытия отправляющего редактора.
if (!closed || drafts.get(storageKey)?.text === textarea.value) drafts.delete(storageKey);
if (!isActive() || closed) return;
close();
} catch (submitError) {
if (!isActive() || closed) return;
inFlight = false;
textarea.disabled = false;
attachButton.disabled = false;
clearButton.disabled = false;
if (extraControl) extraControl.querySelectorAll('select,button,input').forEach((el) => { el.disabled = false; });
submitButton.textContent = submitLabel;
error.textContent = toUserMessage(submitError, t('screens.channel_editor.text_007'));
saveDraft();
sync();
}
};
const onDocumentKeydown = (event) => {
if (!overlay.isConnected || document.querySelector('.ar-attachment-manager-root, .public-attachment-manager-root')) return;
if (event.key === 'Escape') {
event.preventDefault();
close();
return;
}
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey) && !composing && !event.isComposing) {
event.preventDefault();
void submit();
return;
}
if (event.key !== 'Tab') return;
const focusable = [...overlay.querySelectorAll('button:not(:disabled), textarea:not(:disabled), select:not(:disabled)')].filter((el) => !el.hidden);
if (!focusable.length) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
closeButton.addEventListener('click', () => close());
clearButton.addEventListener('click', () => {
textarea.value = '';
attachments.splice(0);
drafts.delete(storageKey);
error.textContent = '';
sync();
textarea.focus();
});
textarea.addEventListener('input', () => {
error.textContent = '';
saveDraft();
sync();
});
textarea.addEventListener('compositionstart', () => { composing = true; });
extraFields.forEach((field) => field.addEventListener('change', saveDraft));
textarea.addEventListener('compositionend', () => { composing = false; });
attachButton.addEventListener('click', async () => {
if (picking || inFlight) return;
if (attachments.length >= MAX_MESSAGE_ATTACHMENTS) {
error.textContent = t('screens.channel_editor.text_023', { value1: MAX_MESSAGE_ATTACHMENTS });
return;
}
try {
picking = true;
dialog.inert = true;
sync();
const item = await openChannelAttachmentManager({
login,
storagePwd: state.session.storagePwdInMemory,
gateway: state.entrySettings.arweaveServer,
selectedTxIds: attachments.map((attachment) => attachment.ar),
signal: attachmentController.signal,
});
if (!isActive() || !overlay.isConnected || !item) return;
attachments.push(item);
saveDraft();
sync();
} catch (attachError) {
if (isActive() && overlay.isConnected) {
error.textContent = toUserMessage(attachError, t('screens.channel_editor.text_008'));
}
} finally {
picking = false;
dialog.inert = false;
if (!closed) { sync(); attachButton.focus(); }
}
});
submitButton.addEventListener('click', () => void submit());
document.addEventListener('keydown', onDocumentKeydown);
viewport?.addEventListener('resize', updateViewport);
viewport?.addEventListener('scroll', updateViewport);
window.addEventListener('resize', updateViewport);
observer.observe(root, { childList: true });
updateViewport();
sync();
requestAnimationFrame(() => {
if (closed || !isActive()) return;
const quote = overlay.querySelector('.channel-editor__context p');
const expand = overlay.querySelector('.channel-editor__context-toggle');
if (quote && expand && quote.clientHeight > 0) expand.hidden = quote.scrollHeight <= quote.clientHeight;
sync();
if (chain.length) body.scrollTop = author.offsetTop - body.offsetTop - 120;
textarea.focus({ preventScroll: chain.length > 0 });
if (openAttachOnStart && allowAttachments) attachButton.click();
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
});
return { close };
}