Files
SHiNE-server/shine-UI/js/components/channel-editor.js
T
q b5ce7b0fa0 UI: редактор ответа и записи – поле сразу под именем, «прикрепить» в нижней панели, миниатюры
Текст пишется в колонке справа от аватара сразу под именем (и строкой
«В канал …»), без пустого места; «прикрепить» – слева в нижней панели,
«Очистить» – в шапке, пока есть текст или вложения; счётчик символов
показывается только с 1500 знаков. Картинки и видео во вложениях – миниатюрами
с крестиком (видео со значком воспроизведения), прочие файлы – строкой.
Нижняя панель на flex: на 320 px ничего не выходит за край, выбор типа записи
сжимается.
2026-10-11 23:55:41 +03:00

473 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 { iconHtml } from './ui-icon.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';
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 || 'Файл');
const size = Number(item?.size || 0);
if (!size) return name;
if (size < 1024) return `${name} · ${size} Б`;
if (size < 1024 * 1024) return `${name} · ${Math.ceil(size / 1024)} КБ`;
return `${name} · ${(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: 'Нужен аккаунт', text: 'Чтобы публиковать и отвечать, войдите или зарегистрируйтесь.' });
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', 'Закрыть редактор');
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 = 'Черновик';
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', 'На что вы отвечаете');
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 || 'Запись без текста');
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 ? `В ответ ${context.author}` : 'Контекст сообщения';
const quote = document.createElement('p');
quote.textContent = String(context.text || context.attachmentLabel || 'Сообщение без текста');
const expand = document.createElement('button');
expand.type = 'button';
expand.className = 'text-btn channel-editor__context-toggle';
expand.textContent = 'Показать целиком';
expand.setAttribute('aria-expanded', 'false');
expand.addEventListener('click', () => {
const expanded = contextBox.classList.toggle('is-expanded');
expand.textContent = expanded ? 'Свернуть' : 'Показать целиком';
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 = 'Очистить';
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 || 'Гость';
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">Прикрепить фото, видео или файл</span>`;
attachButton.title = 'Фото, видео или файл';
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 = 'Отправить · Ctrl+Enter / ⌘+Enter';
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 || 'Изображение');
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', `Убрать вложение ${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', `Убрать вложение ${item?.name || ''}`);
remove.textContent = '×';
remove.disabled = inFlight;
remove.addEventListener('click', () => {
attachments.splice(index, 1);
saveDraft();
sync();
});
card.append(label, remove);
attachmentsBox.append(card);
});
};
const openedUrl = location.href;
const historyId = `${Date.now()}:${Math.random()}`;
history.pushState({ ...history.state, channelEditor: historyId }, '', openedUrl);
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 onBack = (event) => {
if (closed) return;
event.stopImmediatePropagation();
close({ fromHistory: true });
};
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);
window.removeEventListener('popstate', onBack, true);
overlay.remove();
if (!fromHistory && location.href === openedUrl && history.state?.channelEditor === historyId) {
window.addEventListener('popstate', (event) => {
if (location.href === openedUrl) event.stopImmediatePropagation();
}, { capture: true, once: true });
history.back();
}
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 = 'Отправляем…';
sync();
try {
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, 'Не удалось отправить. Текст сохранён.');
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 = `Можно прикрепить максимум ${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, 'Не удалось добавить вложение.');
}
} finally {
picking = false;
dialog.inert = false;
if (!closed) { sync(); attachButton.focus(); }
}
});
submitButton.addEventListener('click', () => void submit());
document.addEventListener('keydown', onDocumentKeydown);
window.addEventListener('popstate', onBack, true);
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 };
}