UI v4: новый стиль по макету V3/V4 и доводка экранов

Палитра «Сияние» по умолчанию, новые роли цветов. Лента канала: плоские записи, ряд действий
с равным шагом иконок, дата у записи. Обсуждение со строкой ввода, личный чат, шторки.
Вход и регистрация: стартовый экран (надпись «СИЯНИЕ», сияние мандалы), настройки входа
со статусами серверов, статус логина в одну строку, вход с другого устройства (код, таймер, шаги),
сохранение ключей с переключателями. Корневые разделы – заголовок по центру; фильтр чатов –
переключатель; уведомления – список как в чатах; фото – просмотр на весь экран.
Общее: один зазор под шапкой (--page-top-gap), переключатели высотой с поле ввода,
второстепенные кнопки по одной роли (в том числе на экранах устройств и серверов),
иконки только из ui-icon.js, полоса прокрутки скрыта, среднее тире в текстах интерфейса.

Что нужно от сервера и разработчика – docs/UI-Design/UI-v4-for-dev.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
q
2026-09-29 01:36:52 +03:00
co-authored by Claude Opus 5.5
parent 13693a0a53
commit 2e62616b46
84 changed files with 2507 additions and 1583 deletions
+2 -2
View File
@@ -17,7 +17,7 @@ function createToggleRow({ id, title, hint, checked }) {
<strong class="settings-feature-toggle-title">${title}</strong>
<span class="settings-feature-toggle-hint">${hint}</span>
</span>
<input class="settings-feature-switch" id="${id}" type="checkbox" ${checked ? 'checked' : ''} />
<input class="switch" id="${id}" type="checkbox" ${checked ? 'checked' : ''} />
`;
return label;
}
@@ -34,7 +34,7 @@ export function render({ navigate, chrome }) {
const intro = document.createElement('div');
intro.className = 'settings-intro';
intro.innerHTML = `
<p class="meta-muted">Скрытые возможности. Экран открывается пятью быстрыми нажатиями по логотипу в настройках.</p>
<p class="meta-muted">Скрытые возможности. Экран открывается пятью быстрыми нажатиями по заголовку «Настройки».</p>
`;
const developerRow = createToggleRow({
+1 -1
View File
@@ -119,7 +119,7 @@ export function render({navigate, chrome}) {
back: { onClick: () => navigate('settings-view') },
actions: [
{
label: '+',
icon: 'plus',
title: 'Добавить файл',
ariaLabel: 'Добавить файл',
className: 'arweave-uploads-add',
+10 -10
View File
@@ -163,18 +163,18 @@ function openSupportChannelModal({ ownerLogin, ownerUser, channelTitle }) {
<select class="select" id="channel-support-recipient-key" ${recipientChoices.length ? '' : 'disabled'}>
${recipientChoices.map((choice) => `<option value="${escapeHtml(choice.id)}">${escapeHtml(choice.label)}</option>`).join('')}
</select>
<div class="channel-support-address" id="channel-support-recipient-address">—</div>
<div class="channel-support-address" id="channel-support-recipient-address">–</div>
<label class="field-label" for="channel-support-sender-key">Перевести с моего счёта</label>
<select class="select" id="channel-support-sender-key">
<option value="client-key">Client key</option>
<option value="root-key">Root key</option>
</select>
<div class="channel-support-address" id="channel-support-sender-address">—</div>
<div class="channel-support-address" id="channel-support-sender-address">–</div>
<div class="channel-support-balance-row">
<span class="meta-muted">Баланс</span>
<strong id="channel-support-balance">—</strong>
<strong id="channel-support-balance">–</strong>
<button class="secondary-btn channel-support-refresh" id="channel-support-refresh" type="button">Обновить</button>
</div>
@@ -281,7 +281,7 @@ function openSupportChannelModal({ ownerLogin, ownerUser, channelTitle }) {
if (busy || closed) return;
setBusy(true);
setStatus('Загрузка баланса…');
if (balanceEl) balanceEl.textContent = '—';
if (balanceEl) balanceEl.textContent = '–';
try {
const wallet = await resolveSenderWallet();
if (closed) return;
@@ -295,7 +295,7 @@ function openSupportChannelModal({ ownerLogin, ownerUser, channelTitle }) {
setStatus('');
} catch (error) {
if (closed) return;
if (senderAddressEl) senderAddressEl.textContent = '—';
if (senderAddressEl) senderAddressEl.textContent = '–';
setStatus(toUserMessage(error, 'Не удалось получить баланс.'), 'error');
} finally {
if (!closed) setBusy(false);
@@ -304,8 +304,8 @@ function openSupportChannelModal({ ownerLogin, ownerUser, channelTitle }) {
recipientSelect?.addEventListener('change', updateRecipientAddress);
senderSelect?.addEventListener('change', () => {
if (senderAddressEl) senderAddressEl.textContent = '—';
if (balanceEl) balanceEl.textContent = '—';
if (senderAddressEl) senderAddressEl.textContent = '–';
if (balanceEl) balanceEl.textContent = '–';
setStatus('');
void refreshBalance();
});
@@ -494,13 +494,13 @@ export function render({ navigate, route, chrome }) {
<div class="channel-about-hero">
<div class="channel-about-avatar-slot" id="channel-about-avatar-slot"></div>
<h2 class="channel-about-title">${escapeHtml(cleanName)}</h2>
<div class="channel-about-subline">@${escapeHtml(ownerLogin)} · ${escapeHtml(statsText(subscribersCount))} ${escapeHtml(subscribersWord(subscribersCount))}</div>
<div class="channel-about-subline">@${escapeHtml(channelName || ownerLogin)} · ${escapeHtml(statsText(subscribersCount))} ${escapeHtml(subscribersWord(subscribersCount))}</div>
</div>
<div class="channel-about-tiles">
${cameFromChannel ? '' : `<button class="channel-about-tile" id="channel-about-open" type="button">${iconHtml('open')}<span>Открыть</span></button>`}
${subscriptionTile}
<button class="channel-about-tile" id="channel-about-support" type="button">${iconHtml('gift')}<span>Донат</span></button>
${isOwnChannel ? '' : `<button class="channel-about-tile" id="channel-about-support" type="button">${iconHtml('gift')}<span>Поддержать автора</span></button>`}
</div>
<div class="channel-about-list">
@@ -521,7 +521,7 @@ export function render({ navigate, route, chrome }) {
<span class="channel-about-row-label">Ссылка</span>
<span class="channel-about-link">${escapeHtml(shortLink)}</span>
</span>
<span class="channel-about-row-chevron" aria-hidden="true">${iconHtml('link')}</span>
<span class="channel-about-row-chevron" aria-hidden="true">${iconHtml('copy')}</span>
</button>
</div>
`;
+7 -7
View File
@@ -164,7 +164,7 @@ export function render({ navigate, route, chrome }) {
<select class="select" id="channel-donate-recipient-key" ${recipientChoices.length ? '' : 'disabled'}>
${recipientChoices.map((choice) => `<option value="${escapeHtml(choice.id)}">${escapeHtml(choice.label)}</option>`).join('')}
</select>
<div class="channel-donate-address" id="channel-donate-recipient-address">—</div>
<div class="channel-donate-address" id="channel-donate-recipient-address">–</div>
</section>
<section class="channel-donate-section">
@@ -173,11 +173,11 @@ export function render({ navigate, route, chrome }) {
<option value="client-key">Client key</option>
<option value="root-key">Root key</option>
</select>
<div class="channel-donate-address" id="channel-donate-sender-address">—</div>
<div class="channel-donate-address" id="channel-donate-sender-address">–</div>
<div class="channel-donate-balance-row">
<span class="meta-muted">Баланс</span>
<strong id="channel-donate-balance">—</strong>
<strong id="channel-donate-balance">–</strong>
<button class="secondary-btn channel-donate-refresh" id="channel-donate-refresh" type="button">Обновить</button>
</div>
</section>
@@ -267,7 +267,7 @@ export function render({ navigate, route, chrome }) {
if (busy || disposed) return;
setBusy(true);
setStatus('Загрузка баланса…');
if (balanceEl) balanceEl.textContent = '—';
if (balanceEl) balanceEl.textContent = '–';
try {
const wallet = await resolveSenderWallet();
if (disposed) return;
@@ -281,7 +281,7 @@ export function render({ navigate, route, chrome }) {
setStatus('');
} catch (error) {
if (disposed) return;
if (senderAddressEl) senderAddressEl.textContent = '—';
if (senderAddressEl) senderAddressEl.textContent = '–';
setStatus(toUserMessage(error, 'Не удалось получить баланс.'), 'error');
} finally {
if (!disposed) setBusy(false);
@@ -290,8 +290,8 @@ export function render({ navigate, route, chrome }) {
recipientSelect?.addEventListener('change', updateRecipientAddress);
senderSelect?.addEventListener('change', () => {
if (senderAddressEl) senderAddressEl.textContent = '—';
if (balanceEl) balanceEl.textContent = '—';
if (senderAddressEl) senderAddressEl.textContent = '–';
if (balanceEl) balanceEl.textContent = '–';
setStatus('');
void refreshBalance();
});
+407 -63
View File
@@ -9,6 +9,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
import {
animatePress,
createSkeletonCard,
formatPostStamp,
formatRelativeTime,
longPressFeel,
shareOrCopyLink,
@@ -18,6 +19,9 @@ import {
import { getPreviousTrackedPath, parseRouteFromPath } from '../router.js';
import { renderUserAvatar } from '../components/avatar-image.js';
import { openChannelEditor } from '../components/channel-editor.js';
import { createDropdownMenu } from '../components/dropdown-menu.js';
import { createEmojiPicker } from '../components/emoji-picker.js';
import { openShareSheet } from '../components/share-sheet.js';
import {
composeMessageWithAttachments,
createAttachmentCarouselElement,
@@ -466,7 +470,7 @@ function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
<span>Номер записи</span><code>${escapeHtml(details.blockNumber)}</code>
<span>Хэш</span><code>${escapeHtml(details.blockHash)}</code>
<span>Тип</span><code>${escapeHtml(details.msgSubType)}</code>
<span>Время</span><code>${escapeHtml(details.createdAtMs ? new Date(Number(details.createdAtMs)).toLocaleString('ru-RU') : '—')}</code>
<span>Время</span><code>${escapeHtml(details.createdAtMs ? new Date(Number(details.createdAtMs)).toLocaleString('ru-RU') : '–')}</code>
<span>Public key</span><code>${escapeHtml(details.publicKey)}</code>
<span>Подпись</span><code>${escapeHtml(details.signature)}</code>
</div>
@@ -623,7 +627,7 @@ function openMessageHistoryModal({ versions = [], title = 'История изм
const text = String(item?.text || '').trim() || 'удалено';
row.innerHTML = `
<strong>Версия ${index + 1}</strong>
<div class="meta-muted">${ts > 0 ? new Date(ts).toLocaleString('ru-RU') : '—'}</div>
<div class="meta-muted">${ts > 0 ? new Date(ts).toLocaleString('ru-RU') : '–'}</div>
<p class="channel-message-body">${text}</p>
`;
list.append(row);
@@ -715,7 +719,7 @@ function renderNodeCard(node, heading, handlers, localNumber) {
}
const timestamp = document.createElement('div');
timestamp.className = 'channel-message-time';
timestamp.textContent = node?.createdAtMs ? formatRelativeTime(node.createdAtMs) : '—';
timestamp.textContent = node?.createdAtMs ? formatRelativeTime(node.createdAtMs) : '–';
if (node?.createdAtMs) timestamp.title = new Date(node.createdAtMs).toLocaleString('ru-RU');
authorBlock.append(title, timestamp);
authorTile.append(avatar, authorBlock);
@@ -961,6 +965,176 @@ function renderNodeCard(node, heading, handlers, localNumber) {
return card;
}
// ===== Обсуждение в раскладке V4: контекст записи, плоский список комментариев, строка ввода =====
// Дерево ответов → плоский список в порядке чтения; у каждого — на что он отвечает
function flattenDescendants(items, parent = null, out = []) {
(Array.isArray(items) ? items : []).forEach((branch) => {
if (!branch?.node) return;
out.push({ node: branch.node, parent });
flattenDescendants(branch.children, branch.node, out);
});
return out;
}
function nodeKey(node) {
return messageRefKey(buildTargetFromNode(node));
}
// Исходная запись сверху: две строки, «Развернуть» — только если текст правда обрезан
function renderThreadContext(node, { onOpenPost }) {
const parsed = parseMessageAttachments(resolveNodeText(node));
const box = document.createElement('section');
box.className = 'thread-context';
const text = document.createElement('p');
text.className = 'thread-context__text';
text.textContent = parsed.text || (parsed.attachments.length ? 'Запись с вложением' : '');
const meta = document.createElement('div');
meta.className = 'thread-context__meta';
const time = document.createElement('span');
time.textContent = formatPostStamp(node?.createdAtMs);
const expand = document.createElement('button');
expand.type = 'button';
expand.className = 'text-btn thread-context__expand';
expand.textContent = 'Развернуть';
expand.hidden = true;
expand.addEventListener('click', () => {
const open = box.classList.toggle('is-expanded');
expand.textContent = open ? 'Свернуть' : 'Развернуть';
});
const toPost = document.createElement('button');
toPost.type = 'button';
toPost.className = 'text-btn thread-context__open';
toPost.innerHTML = `<span>${parsed.attachments.length ? 'Запись с фото' : 'К записи'}</span>${iconHtml('open')}`;
toPost.addEventListener('click', onOpenPost);
meta.append(time, expand, toPost);
box.append(text, meta);
// обрезан ли текст — видно только после вставки в документ
requestAnimationFrame(() => { expand.hidden = text.scrollHeight <= text.clientHeight + 1; });
return box;
}
function renderComment({ node, parent, focus, channelOwner, handlers }) {
const target = buildTargetFromNode(node);
const key = messageRefKey(target);
const author = String(node?.authorLogin || 'автор');
const parsed = parseMessageAttachments(resolveNodeText(node));
const versions = Array.isArray(node?.versions) ? node.versions : [];
const isOwn = Boolean(state.session.login) && author.toLowerCase() === String(state.session.login).toLowerCase();
const item = document.createElement('article');
item.className = 'thread-comment channel-message-card';
if (key) item.dataset.messageKey = key;
const person = document.createElement('div');
person.className = 'thread-comment__person';
const who = document.createElement('button');
who.type = 'button';
who.className = 'thread-comment__who';
who.append(renderUserAvatar({ login: author, size: 'xs', className: 'thread-comment__avatar' }));
const name = document.createElement('span');
name.className = 'thread-comment__name';
name.textContent = author;
who.append(name);
who.addEventListener('click', () => handlers.navigate(makeProfileRoute(author)));
person.append(who);
if (channelOwner && author.toLowerCase() === channelOwner.toLowerCase()) {
const badge = document.createElement('span');
badge.className = 'thread-comment__badge';
badge.textContent = 'Автор';
person.append(badge);
}
const time = document.createElement('time');
time.textContent = formatPostStamp(node?.createdAtMs);
if (node?.createdAtMs) time.title = new Date(node.createdAtMs).toLocaleString('ru-RU');
person.append(time);
item.append(person);
// Ответ на другой комментарий — цитата в две строки; нажатие ведёт к оригиналу
if (parent && parent !== focus) {
const quote = document.createElement('button');
quote.type = 'button';
quote.className = 'thread-quote';
const qa = document.createElement('strong');
qa.textContent = String(parent.authorLogin || '');
const qt = document.createElement('span');
qt.textContent = parseMessageAttachments(resolveNodeText(parent)).text || 'Вложение';
quote.append(qa, qt);
quote.setAttribute('aria-label', `Ответ на комментарий ${parent.authorLogin || ''}. Перейти к нему`);
quote.addEventListener('click', () => handlers.jumpTo(nodeKey(parent), key));
item.append(quote);
}
if (parsed.attachments.length) {
item.append(createAttachmentCarouselElement(parsed.attachments, { gateway: state.entrySettings.arweaveServer, messageTimestampMs: node?.createdAtMs }));
}
const text = document.createElement('p');
text.className = 'thread-comment__text';
text.textContent = parsed.text;
item.append(text);
const actions = document.createElement('div');
actions.className = 'thread-comment__actions';
const reply = document.createElement('button');
reply.type = 'button';
reply.className = 'thread-comment__reply';
reply.textContent = 'Ответить';
reply.addEventListener('click', () => handlers.setReplyTo(node));
setMessageReactionState(target, node?.likedByMe === true ? 'liked' : 'unliked');
const liked = getMessageReactionState(target) === 'liked';
const likes = Number(node?.likesCount || 0);
const like = document.createElement('button');
like.type = 'button';
like.className = `channel-action-item thread-comment__like${liked ? ' is-liked' : ''}`;
like.innerHTML = `${iconHtml('heart', liked)}<span>${likes || ''}</span>`;
like.setAttribute('aria-pressed', String(liked));
like.setAttribute('aria-label', `${liked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${likes}`);
like.addEventListener('click', async () => {
like.disabled = true;
try { await handlers.onToggleLike(target, liked ? 'unlike' : 'like'); }
catch (error) { handlers.onActionError(error, liked ? 'unlike' : 'like'); }
finally { if (like.isConnected) like.disabled = false; }
});
const more = document.createElement('button');
more.type = 'button';
more.className = 'channel-action-item thread-comment__more';
more.innerHTML = iconHtml('more');
more.setAttribute('aria-label', `Действия с комментарием ${author}`);
const menuItems = [
{ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => handlers.setReplyTo(node) },
{ label: 'Поделиться комментарием', iconHtml: iconHtml('share'), action: () => handlers.shareComment(node) },
{ label: 'Скопировать текст', iconHtml: iconHtml('copy'), action: async () => {
try { await navigator.clipboard.writeText(parsed.text); showToast('Текст скопирован'); }
catch { showToast('Не удалось скопировать', { kind: 'error' }); }
} },
{ label: 'Данные публикации', iconHtml: iconHtml('info'), action: () => openBlockchainDetailsModal(buildBlockchainDetails({ target, authorLogin: author, timestampMs: node?.createdAtMs, text: resolveNodeText(node), raw: node, localNumber: 0, msgSubType: Number(node?.msgSubType || 0) }), { isActive: handlers.isActive }) },
];
if (versions.length > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions }) });
if (isOwn) {
menuItems.splice(1, 0, { label: 'Редактировать', iconHtml: iconHtml('edit'), action: () => openEditMessageModal({
isActive: handlers.isActive,
draftKey: `edit:${key}`,
initialText: parsed.text,
allowEmptyText: parsed.attachments.length > 0,
onSave: async (nextText) => handlers.onEdit(target, composeMessageWithAttachments(nextText, parsed.attachments), { isChannelPost: false }),
onDelete: async () => handlers.onEdit(target, '', { isChannelPost: false, isDelete: true }),
}) });
menuItems.push({ divider: true }, { label: 'Удалить', danger: true, iconHtml: iconHtml('trash'), action: async () => {
if (!await confirmDialog({ title: 'Удалить комментарий?', text: 'Он скроется из обсуждения. Прежние версии останутся в блокчейне.', confirmLabel: 'Удалить', danger: true })) return;
try { await handlers.onEdit(target, '', { isChannelPost: false, isDelete: true }); }
catch (error) { if (handlers.isActive()) showToast(toUserMessage(error, 'Не удалось удалить комментарий.')); }
} });
}
const menu = createDropdownMenu({ anchorEl: more, items: menuItems });
item.cleanup = () => menu.destroy();
actions.append(reply, like, more);
item.append(actions);
return item;
}
function renderDescendants(items, handlers, nextNumber, depth = 0, parent = null) {
const wrap = document.createElement('div');
wrap.className = 'stack';
@@ -1025,6 +1199,124 @@ function renderSkeleton(screen) {
return wrap;
}
// «Не уведомлять об ответах» — пока только на этом устройстве (серверной настройки нет, см. docs/UI-Design)
const THREAD_MUTE_KEY = 'shine-ui-thread-muted-v1';
function readMuted() { try { return JSON.parse(localStorage.getItem(THREAD_MUTE_KEY) || '{}') || {}; } catch { return {}; } }
function isThreadMuted(key) { return Boolean(readMuted()[key]); }
function setThreadMuted(key, muted) {
const all = readMuted();
if (muted) all[key] = Date.now(); else delete all[key];
try { localStorage.setItem(THREAD_MUTE_KEY, JSON.stringify(all)); } catch { /* приватный режим */ }
}
// Черновик и адресат ответа принадлежат конкретному обсуждению
const threadDrafts = new Map();
function createThreadComposer({ draftKey, isAuthorized, onLogin, onSend }) {
const root = document.createElement('div');
root.className = 'channel-composer thread-composer';
if (!isAuthorized) {
const login = document.createElement('button');
login.type = 'button';
login.className = 'primary-btn channel-main-action';
login.textContent = 'Войти и ответить';
login.addEventListener('click', onLogin);
root.append(login);
return { root, setReplyTo() {} };
}
const draft = threadDrafts.get(draftKey) || { text: '', replyTo: null };
threadDrafts.set(draftKey, draft);
const replying = document.createElement('div');
replying.className = 'thread-replying';
const row = document.createElement('div');
row.className = 'compose-row';
const field = document.createElement('div');
field.className = 'compose-field';
const input = document.createElement('textarea');
input.rows = 1;
input.className = 'compose-field__input';
input.value = draft.text;
const emojiBtn = document.createElement('button');
emojiBtn.type = 'button';
emojiBtn.className = 'compose-field__emoji';
emojiBtn.setAttribute('aria-label', 'Эмодзи');
emojiBtn.innerHTML = iconHtml('emoji');
field.append(input, emojiBtn);
const send = document.createElement('button');
send.type = 'button';
send.className = 'compose-send';
send.setAttribute('aria-label', 'Отправить');
send.innerHTML = iconHtml('send');
row.append(field, send);
const emojiSlot = document.createElement('div');
emojiSlot.className = 'thread-composer__emoji';
emojiSlot.hidden = true;
root.append(replying, row, emojiSlot);
const sync = () => {
draft.text = input.value;
send.disabled = !input.value.trim();
input.placeholder = draft.replyTo ? `Ответить ${draft.replyTo.authorLogin || ''}…` : 'Написать комментарий…';
replying.replaceChildren();
replying.hidden = !draft.replyTo;
if (draft.replyTo) {
const quote = document.createElement('div');
quote.className = 'thread-quote';
const a = document.createElement('strong');
a.textContent = String(draft.replyTo.authorLogin || '');
const t = document.createElement('span');
t.textContent = parseMessageAttachments(resolveNodeText(draft.replyTo)).text;
quote.append(a, t);
const cancel = document.createElement('button');
cancel.type = 'button';
cancel.className = 'thread-replying__cancel';
cancel.setAttribute('aria-label', 'Не отвечать на комментарий');
cancel.innerHTML = iconHtml('close');
cancel.addEventListener('click', () => { draft.replyTo = null; sync(); });
replying.append(quote, cancel);
}
};
input.addEventListener('input', sync);
emojiBtn.addEventListener('click', () => {
if (!emojiSlot.childElementCount) {
emojiSlot.append(createEmojiPicker({ onSelect: (emoji) => {
const at = input.selectionStart ?? input.value.length;
input.value = `${input.value.slice(0, at)}${emoji}${input.value.slice(at)}`;
sync();
} }));
}
emojiSlot.hidden = !emojiSlot.hidden;
});
const submit = async () => {
const text = input.value.trim();
if (!text) return;
send.disabled = true;
try {
await onSend(text, draft.replyTo);
draft.text = '';
draft.replyTo = null;
input.value = '';
emojiSlot.hidden = true;
} catch (error) {
showToast(toUserMessage(error, 'Комментарий не отправлен. Текст сохранён.'), { kind: 'error' });
} finally {
sync();
}
};
send.addEventListener('click', submit);
bindSubmitOnPlainEnter(input, submit);
sync();
return {
root,
setReplyTo(node) {
draft.replyTo = node;
sync();
input.focus();
},
};
}
export function render({ navigate, route, chrome }) {
let selector = parseThreadSelector(route);
const channelDisplayName = resolveChannelDisplayName(selector?.channel);
@@ -1042,19 +1334,31 @@ export function render({ navigate, route, chrome }) {
const threadHeaderButton = document.createElement('button');
threadHeaderButton.type = 'button';
threadHeaderButton.className = 'icon-btn channel-header-route-btn app-topbar-title-action';
threadHeaderButton.className = 'topbar-identity channel-header-route-btn';
const threadHeaderText = document.createElement('span');
threadHeaderText.className = 'topbar-identity__text';
const threadHeaderTitle = document.createElement('span');
threadHeaderTitle.className = 'channel-header-title';
threadHeaderTitle.className = 'topbar-identity__title';
threadHeaderTitle.textContent = 'Обсуждение';
const threadHeaderChannel = document.createElement('span');
threadHeaderChannel.className = 'channel-header-owner';
threadHeaderChannel.className = 'topbar-identity__sub';
threadHeaderChannel.textContent = '…';
threadHeaderButton.append(threadHeaderTitle, threadHeaderChannel);
threadHeaderText.append(threadHeaderTitle, threadHeaderChannel);
threadHeaderButton.append(threadHeaderText);
threadHeaderButton.disabled = true;
// Меню обсуждения (V4): к записи, уведомления об ответах, поделиться записью
let threadMenuActions = null;
const header = createTopBar({
center: threadHeaderButton,
className: 'topbar--identity',
back: { label: '<', onClick: () => navigate(resolveThreadPreviousInChannels(selector, activeResolvedChannelLabel)) },
actions: [{
label: '⋯',
ariaLabel: 'Меню обсуждения',
className: 'thread-menu-btn',
menu: { minWidth: 240, items: () => threadMenuActions?.() || [] },
}],
});
header.classList.add('channel-thread-topbar');
chrome?.setTopbar(header);
@@ -1396,7 +1700,7 @@ export function render({ navigate, route, chrome }) {
const fallbackChannel = String(selector?.channel?.ownerBlockchainName || '').trim() || 'неизвестно';
const resolvedChannelTitle = resolvedChannelLabel || fallbackChannel;
if (threadHeaderButton) {
threadHeaderChannel.textContent = `в канале «${channelTitleByLabel.get(resolvedChannelTitle) || resolvedChannelTitle}»`;
threadHeaderChannel.textContent = channelTitleByLabel.get(resolvedChannelTitle) || resolvedChannelTitle;
threadHeaderButton.title = 'Открыть канал';
threadHeaderButton.disabled = false;
threadHeaderButton.onclick = (event) => {
@@ -1409,74 +1713,114 @@ export function render({ navigate, route, chrome }) {
}
clearContent();
let localSeq = 0;
const nextNumber = () => {
localSeq += 1;
return localSeq;
const channelOwner = extractLoginFromBlockchainName(selector?.channel?.ownerBlockchainName || focus?.channelInfo?.ownerBlockchainName || '');
const openPost = () => {
const routeToChannel = buildChannelRouteFromThread(selector, resolvedChannelLabel);
if (routeToChannel) navigate(routeToChannel);
};
const focusTarget = focus ? buildTargetFromNode(focus) : null;
threadMenuActions = () => {
const muted = isThreadMuted(routeKey);
return [
{ label: 'Перейти к записи', iconHtml: iconHtml('doc'), action: openPost },
{ label: muted ? 'Уведомлять об ответах' : 'Не уведомлять об ответах', iconHtml: iconHtml(muted ? 'bell' : 'bell-off'), action: () => {
setThreadMuted(routeKey, !muted);
showToast(muted ? 'Уведомления об ответах включены' : 'Ответы в этом обсуждении не будут приходить в уведомления');
} },
{ label: 'Поделиться записью', iconHtml: iconHtml('share'), action: () => {
if (!focusTarget) return;
openShareSheet({
title: 'Поделиться записью',
kicker: `${resolvedChannelTitle} · запись`,
text: parseMessageAttachments(resolveNodeText(focus)).text,
url: buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector)),
});
} },
];
};
let ancestorsWrap = null;
if (ancestors.length) {
ancestorsWrap = document.createElement('div');
ancestorsWrap.className = 'stack thread-block thread-block--ancestors';
ancestors.forEach((node, index) => {
const heading = index === 0 ? resolveChannelHeadingFromNode(node) : '';
ancestorsWrap.append(renderNodeCard(node, heading, handlers, nextNumber()));
});
const ancestorsWrap = document.createElement('div');
ancestorsWrap.className = 'thread-block thread-block--ancestors';
ancestors.forEach((node) => ancestorsWrap.append(renderThreadContext(node, { onOpenPost: openPost })));
screen.append(ancestorsWrap);
}
let focusWrap = null;
if (focus) {
focusWrap = document.createElement('div');
focusWrap.className = 'stack thread-block thread-block--focus';
const focusTitle = document.createElement('h3');
focusTitle.className = 'section-title';
focusTitle.textContent = 'Исходное сообщение';
focusWrap.append(renderNodeCard(focus, '', handlers, nextNumber()));
const composer = document.createElement('div');
composer.className = 'channel-composer';
const reply = document.createElement('button');
reply.type = 'button';
reply.className = 'channel-compose-bar';
reply.innerHTML = `<span class="channel-compose-bar__text">${state.session.isAuthorized ? 'Написать ответ…' : 'Войти и ответить'}</span><span class="channel-compose-bar__icon" aria-hidden="true">${iconHtml('plus')}</span>`;
reply.addEventListener('click', () => {
const parsed = parseMessageAttachments(resolveNodeText(focus));
openReplyModal({
draftKey: `message:${messageRefKey(buildTargetFromNode(focus))}`,
context: { author: focus.authorLogin, text: parsed.text, attachmentLabel: parsed.attachments[0]?.name },
isActive: () => !disposed,
onSubmit: (text) => handlers.onReply(buildTargetFromNode(focus), text),
});
});
composer.append(reply);
chrome?.setComposer(composer);
const focusWrap = document.createElement('div');
focusWrap.className = 'thread-block thread-block--focus';
focusWrap.append(renderThreadContext(focus, { onOpenPost: openPost }));
screen.append(focusWrap);
}
const descendantsWrap = document.createElement('div');
descendantsWrap.className = 'stack thread-block thread-block--replies';
const descendantsTitle = document.createElement('h3');
descendantsTitle.className = 'section-title';
descendantsTitle.textContent = `Ответы · ${Math.max(0, Number(focus?.repliesCount || descendants.length))}`;
descendantsWrap.append(descendantsTitle);
const comments = flattenDescendants(descendants);
const listWrap = document.createElement('div');
listWrap.className = 'thread-block thread-block--replies';
const listTitle = document.createElement('h3');
listTitle.className = 'thread-section-title';
listTitle.textContent = `Комментарии · ${comments.length}`;
listWrap.append(listTitle);
if (descendants.length) {
descendantsWrap.append(renderDescendants(descendants, handlers, nextNumber));
// Возврат к ответу после перехода по цитате
const returnBtn = document.createElement('button');
returnBtn.type = 'button';
returnBtn.className = 'thread-return';
returnBtn.hidden = true;
returnBtn.textContent = 'Вернуться к ответу';
let returnKey = '';
const highlight = (el) => {
screen.querySelectorAll('.thread-comment.is-highlight').forEach((x) => x.classList.remove('is-highlight'));
el?.classList.add('is-highlight');
};
returnBtn.addEventListener('click', () => {
const el = listWrap.querySelector(`[data-message-key="${CSS.escape(returnKey)}"]`);
el?.scrollIntoView({ block: 'center', behavior: 'smooth' });
highlight(el);
returnBtn.hidden = true;
});
const commentHandlers = {
...handlers,
jumpTo: (key, fromKey) => {
const el = listWrap.querySelector(`[data-message-key="${CSS.escape(key)}"]`);
if (!el) return;
el.scrollIntoView({ block: 'center', behavior: 'smooth' });
highlight(el);
returnKey = fromKey;
returnBtn.hidden = false;
},
setReplyTo: (node) => composerApi?.setReplyTo(node),
shareComment: (node) => openShareSheet({
title: 'Поделиться комментарием',
kicker: `${node.authorLogin} · комментарий`,
text: parseMessageAttachments(resolveNodeText(node)).text,
url: `${buildAbsoluteRouteUrl(buildThreadRouteFromTarget(focusTarget, selector))}#comment-${node?.messageRef?.blockNumber ?? ''}`,
}),
};
if (comments.length) {
comments.forEach(({ node, parent }) => {
try { listWrap.append(renderComment({ node, parent, focus, channelOwner, handlers: commentHandlers })); }
catch (error) { logThreadRuntimeError('render_comment', error); }
});
} else {
const empty = document.createElement('div');
empty.className = 'empty-note';
empty.textContent = 'Пока нет ответов. Начните обсуждение.';
descendantsWrap.append(empty);
empty.className = 'empty-note thread-empty';
empty.textContent = 'Пока нет комментариев. Можно начать разговор.';
listWrap.append(empty);
}
screen.append(listWrap, returnBtn);
if (ancestorsWrap) {
screen.append(ancestorsWrap);
const divider = document.createElement('div');
divider.className = 'thread-history-divider';
screen.append(divider);
let composerApi = null;
if (focus) {
composerApi = createThreadComposer({
draftKey: routeKey,
isAuthorized: state.session.isAuthorized,
onLogin: () => { state.authReturnHash = window.location.pathname || '/channels'; navigate('login-view'); },
onSend: async (text, replyTo) => handlers.onReply(replyTo ? buildTargetFromNode(replyTo) : focusTarget, text),
});
chrome?.setComposer(composerApi.root);
}
if (focusWrap) screen.append(focusWrap);
screen.append(descendantsWrap);
const focusWrap = screen.querySelector('.thread-block--focus');
trackTimer(applyPendingScroll(screen, routeKey, () => !disposed && seq === refreshSeq));
const hasPendingScroll = pendingThreadScroll.has(routeKey);
+61 -35
View File
@@ -16,8 +16,8 @@ import {
animatePress,
createSkeletonCard,
dayKey,
formatClockTime,
formatDayLabel,
formatPostStamp,
formatRelativeTime,
longPressFeel,
shareOrCopyLink,
@@ -644,7 +644,7 @@ function openChannelMetaDetailsModal({
: 'Не установлен';
const changedAtLabel = changedAtMs
? new Date(Number(changedAtMs)).toLocaleString('ru-RU')
: '—';
: '–';
const root = document.getElementById('modal-root');
root.innerHTML = `
<div class="modal" id="about-channel-modal">
@@ -658,7 +658,7 @@ function openChannelMetaDetailsModal({
<span>Дата</span><strong>${escapeHtml(changedAtLabel)}</strong>
<span>Владелец</span><strong>${escapeHtml(channel.ownerName || 'автор')}</strong>
<span>Системное имя</span><code>${escapeHtml(channel.name || 'channel')}</code>
<span>Название</span><strong>${escapeHtml(channel.displayTitle || channel.displayName || channel.name || '—')}</strong>
<span>Название</span><strong>${escapeHtml(channel.displayTitle || channel.displayName || channel.name || '–')}</strong>
<span>Описание</span><span>${escapeHtml(channel.description || 'Описание не задано.')}</span>
<span>Аватар</span><span>${escapeHtml(avatarState)}</span>
</div>
@@ -840,7 +840,7 @@ function openBlockchainDetailsModal(details, { isActive = () => true } = {}) {
<span>Номер записи</span><code>${escapeHtml(details.blockNumber)}</code>
<span>Хэш</span><code>${escapeHtml(details.blockHash)}</code>
<span>Тип</span><code>${escapeHtml(details.msgSubType)}</code>
<span>Время</span><code>${escapeHtml(details.createdAtMs ? new Date(Number(details.createdAtMs)).toLocaleString('ru-RU') : '—')}</code>
<span>Время</span><code>${escapeHtml(details.createdAtMs ? new Date(Number(details.createdAtMs)).toLocaleString('ru-RU') : '–')}</code>
<span>Public key</span><code>${escapeHtml(details.publicKey)}</code>
<span>Подпись</span><code>${escapeHtml(details.signature)}</code>
</div>
@@ -1079,7 +1079,7 @@ function openEntrypointHistoryModal({ channelTitle = '', posts = [], onSelect })
item.className = 'ui-button entrypoint-history-item';
item.innerHTML = `
<strong>${escapeHtml(post.timestampMs ? new Date(post.timestampMs).toLocaleString('ru-RU') : 'Без даты')}</strong>
<span>#${escapeHtml(post.localNumber || '—')}</span>
<span>#${escapeHtml(post.localNumber || '–')}</span>
<p>${escapeHtml(String(parsed.text || '').trim() || 'Без текста')}</p>
`;
item.addEventListener('click', () => {
@@ -1171,7 +1171,7 @@ function openRepostModal({ navigate, channels = [], onSubmit, isActive = () => t
if (textEl) textEl.focus();
}
function openAddMessageModal({ channelName, onSubmit, navigate, isActive = () => true }) {
function openAddMessageModal({ channelName, channelTitle = '', onSubmit, navigate, isActive = () => true }) {
const typeWrap = document.createElement('label');
typeWrap.className = 'channel-editor__type';
typeWrap.innerHTML = '<span class="sr-only">Тип сообщения</span>';
@@ -1188,7 +1188,8 @@ function openAddMessageModal({ channelName, onSubmit, navigate, isActive = () =>
id: 'channel-message-modal',
title: 'Новая запись',
submitLabel: 'Опубликовать',
placeholder: 'Напишите сообщение',
placeholder: 'Чем хотите поделиться?',
destination: channelTitle ? `В канал «${channelTitle}»` : '',
key: `channel-post:${channelName}`,
extraControl: typeWrap,
isActive,
@@ -1223,7 +1224,7 @@ function openMessageHistoryModal({ versions = [], title = 'История изм
const text = String(item?.text || '').trim() || 'удалено';
row.innerHTML = `
<strong>Версия ${index + 1}</strong>
<div class="meta-muted">${ts > 0 ? formatRelativeTime(ts) : '—'}</div>
<div class="meta-muted">${ts > 0 ? formatRelativeTime(ts) : '–'}</div>
<p class="channel-message-body">${text}</p>
`;
list.append(row);
@@ -1275,6 +1276,8 @@ function mapApiMessageToPost(message, selector, localNumber) {
primaryLikesCount: Number(message?.primaryLikesCount || 0),
shiningLikesCount: Number(message?.shiningLikesCount || 0),
repliesCount: Number(message?.repliesCount || 0),
// Кто недавно ответил — для миниатюр у счётчика обсуждения. Сервер пока не отдаёт (см. docs/UI-Design).
recentRepliers: Array.isArray(message?.recentRepliers) ? message.recentRepliers.slice(0, 2) : [],
ratingsCount: Number(message?.ratingsCount || 0),
timestampMs: resolveMessageTimestampMs(message),
messageRef,
@@ -1507,6 +1510,7 @@ async function loadFromApi(route, channelId) {
avaSha256: String(payload.channel?.avaSha256 || '').trim(),
avaSize: Number(payload.channel?.avaSize || 0),
metaUpdatedAtMs: Number(payload.channel?.metaUpdatedAtMs || 0),
subscribersCount: Number(payload.channel?.subscribersCount || 0),
ownerName: ownerLogin || 'неизвестно',
},
posts,
@@ -1862,7 +1866,7 @@ function renderPostCard(post, {
const timestamp = document.createElement('div');
timestamp.className = 'channel-message-time';
timestamp.textContent = post.timestampMs ? formatRelativeTime(post.timestampMs) : '—';
timestamp.textContent = post.timestampMs ? formatRelativeTime(post.timestampMs) : '–';
if (post.timestampMs) timestamp.title = new Date(post.timestampMs).toLocaleString('ru-RU');
if (versionsTotal > 1) {
const editedMarker = document.createElement('span');
@@ -2034,6 +2038,12 @@ function renderPostCard(post, {
<span class="channel-action-label">Обсуждение</span>
<span class="channel-action-counter">${post.repliesCount || ''}</span>
`;
if (post.recentRepliers.length) {
const faces = document.createElement('span');
faces.className = 'channel-action-faces';
post.recentRepliers.forEach((login) => faces.append(renderUserAvatar({ login, size: 'xs', className: 'channel-action-face' })));
discussionButton.append(faces);
}
setActionTitle(discussionButton, `Открыть обсуждение, ответов: ${post.repliesCount || 0}`);
discussionButton.addEventListener('click', (event) => {
event.stopPropagation();
@@ -2067,8 +2077,6 @@ function renderPostCard(post, {
// Rating/opinion action is intentionally hidden from UI for now.
// Backend/subtype/counters remain supported so the feature can be restored later.
actions.append(likeButton, discussionButton);
const shareButton = document.createElement('button');
shareButton.type = 'button';
shareButton.className = 'ui-button channel-action-item channel-action-share';
@@ -2084,8 +2092,9 @@ function renderPostCard(post, {
await onShare(route);
});
actions.append(shareButton);
menuItems.unshift({ label: 'Ответить', action: () => replyButton.click() });
// Порядок как в макете V4: лайк → поделиться → обсуждение; дата и «⋯» — справа
actions.append(likeButton, shareButton, discussionButton);
menuItems.unshift({ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => replyButton.click() });
if (post.msgSubType === MSG_SUBTYPE_TEXT_REPOST && post.targetRef?.blockchainName && Number.isFinite(post.targetRef?.blockNumber) && post.targetRef?.blockHash) {
const originalBtn = document.createElement('button');
originalBtn.type = 'button';
@@ -2127,7 +2136,7 @@ function renderPostCard(post, {
msgSubType: post.msgSubType,
}), { isActive });
});
menuItems.push({ label: 'Данные блокчейна', action: () => detailsButton.click() });
menuItems.push({ label: 'Данные публикации', iconHtml: iconHtml('info'), action: () => detailsButton.click() });
if (post.isOwnMessage) {
const editButton = document.createElement('button');
editButton.type = 'button';
@@ -2149,8 +2158,9 @@ function renderPostCard(post, {
onDelete: async () => onEdit(post.messageRef, '', { isDelete: true }),
});
});
menuItems.unshift({ label: 'Редактировать', action: () => editButton.click() });
menuItems.push({ label: 'Удалить', danger: true, action: async () => {
menuItems.unshift({ label: 'Редактировать', iconHtml: iconHtml('edit'), action: () => editButton.click() });
menuItems.push({ divider: true });
menuItems.push({ label: 'Удалить', danger: true, iconHtml: iconHtml('trash'), action: async () => {
if (!await confirmDialog({
title: 'Удалить сообщение?',
text: 'Сообщение скроется из ленты. Предыдущие версии останутся в блокчейне и в истории изменений.',
@@ -2164,7 +2174,7 @@ function renderPostCard(post, {
if (versionsTotal > 1) menuItems.push({ label: 'История изменений', action: () => openMessageHistoryModal({ versions: post.versions }) });
attachMessageMenu(card, headRow, menuItems);
if (isOwnerPost) {
if (post.timestampMs) timestamp.textContent = formatClockTime(post.timestampMs);
if (post.timestampMs) timestamp.textContent = formatPostStamp(post.timestampMs);
const meta = document.createElement('div');
meta.className = 'channel-message-meta';
const moreButton = headRow.querySelector('.channel-message-more');
@@ -2193,13 +2203,12 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
const actionButton = document.createElement('button');
actionButton.type = 'button';
actionButton.className = 'primary-btn channel-main-action';
actionButton.textContent = state.session.isAuthorized ? 'Подписаться на канал' : 'Войти и подписаться';
actionButton.innerHTML = `${iconHtml('bell')}<span>${state.session.isAuthorized ? 'Подписаться' : 'Войти и подписаться'}</span>`;
const addMessageButton = document.createElement('button');
addMessageButton.type = 'button';
addMessageButton.className = 'channel-compose-bar';
addMessageButton.setAttribute('aria-label', 'Написать в канал');
addMessageButton.innerHTML = `<span class="channel-compose-bar__text">Написать в канал…</span><span class="channel-compose-bar__icon" aria-hidden="true">${iconHtml('plus')}</span>`;
addMessageButton.className = 'channel-new-post';
addMessageButton.innerHTML = `${iconHtml('compose')}<span>Новая запись</span>`;
addMessageButton.addEventListener('click', (event) => {
animatePress(event.currentTarget);
handlers.onAddMessage();
@@ -2236,7 +2245,8 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
const itemDayKey = dayKey(item.timestampMs);
const startsNewDay = !!itemDayKey && itemDayKey !== lastDayKey;
if (startsNewDay) lastDayKey = itemDayKey;
if (startsNewDay && item.type !== 'meta') {
// В ленте канала дата стоит у каждой записи; плашки дней остаются только в дневнике
if (startsNewDay && item.type !== 'meta' && channelData.isDiary) {
const separator = document.createElement('div');
separator.className = 'channel-day-separator';
separator.innerHTML = `<span>${escapeHtml(formatDayLabel(item.timestampMs))}</span>`;
@@ -2300,7 +2310,11 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
composer.append(addMessageButton);
handlers.chrome?.setComposer(composer);
} else if (!channelData.isSubscribed && !isStoriesChannel(channelData.channel)) {
screen.append(actionButton, feed);
screen.append(feed);
const composer = document.createElement('div');
composer.className = 'channel-composer';
composer.append(actionButton);
handlers.chrome?.setComposer(composer);
} else {
screen.append(feed);
}
@@ -2412,17 +2426,18 @@ export function render({ navigate, route, chrome }) {
let activeChannelData = null;
let activeOpenEntrypointHistory = null;
let activeAddMessage = null;
const channelHeaderButton = document.createElement('button');
channelHeaderButton.type = 'button';
channelHeaderButton.className = 'icon-btn channel-header-route-btn app-topbar-title-action';
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
channelHeaderButton.className = 'topbar-identity channel-header-route-btn';
channelHeaderButton.innerHTML = '<span class="topbar-identity__text"><span class="topbar-identity__title">Канал</span><span class="topbar-identity__sub">Загрузка…</span></span>';
channelHeaderButton.disabled = true;
const header = createTopBar({
center: channelHeaderButton,
back: { onClick: () => navigate('channels-list') },
className: 'channel-view-topbar',
className: 'channel-view-topbar topbar--identity',
actions: [
{
label: '⋮',
@@ -2442,16 +2457,20 @@ export function render({ navigate, route, chrome }) {
const aboutRoute = makeShineChannelAboutRoute(routeArgs);
const donateRoute = makeShineChannelDonateRoute(routeArgs);
const items = [];
items.push({ label: 'О канале', action: () => { if (aboutRoute) navigate(aboutRoute); } });
items.push({ label: 'О канале', iconHtml: iconHtml('info'), action: () => { if (aboutRoute) navigate(aboutRoute); } });
if (apiData?.isOwnChannel && !apiData?.isDiary) {
items.push({ label: 'Новая запись', iconHtml: iconHtml('compose'), action: () => activeAddMessage?.() });
}
items.push({
label: 'Оглавление',
iconHtml: iconHtml('list'),
action: () => {
if (activeOpenEntrypointHistory) activeOpenEntrypointHistory();
else showToast('В этом канале пока нет оглавления');
},
});
if (!apiData?.isOwnChannel) {
items.push({ label: 'Поддержать автора', action: () => { if (donateRoute) navigate(donateRoute); } });
items.push({ label: 'Поддержать автора', iconHtml: iconHtml('gift'), action: () => { if (donateRoute) navigate(donateRoute); } });
}
if (!apiData?.isOwnChannel && !isStoriesChannel(apiData?.channel)) {
if (apiData?.isSubscribed) {
@@ -2868,15 +2887,21 @@ export function render({ navigate, route, chrome }) {
};
activeOpenEntrypointHistory = openEntrypointHistory;
if (channelHeaderButton) {
const ownerLabel = String(apiData?.channel?.ownerName || '').trim();
// Короткий адрес канала и число подписчиков; владелец и полный путь — в «О канале»
const slug = String(apiData?.channel?.name || '').trim();
const subs = Number(apiData?.channel?.subscribersCount || 0);
channelHeaderButton.replaceChildren();
const text = document.createElement('span');
text.className = 'topbar-identity__text';
const titleNode = document.createElement('span');
titleNode.className = 'channel-header-title';
titleNode.className = 'topbar-identity__title';
titleNode.textContent = titleLabel;
const ownerNode = document.createElement('span');
ownerNode.className = 'channel-header-owner';
ownerNode.textContent = ownerLabel ? `@${ownerLabel}` : 'О канале';
channelHeaderButton.append(titleNode, ownerNode);
const subNode = document.createElement('span');
subNode.className = 'topbar-identity__sub';
subNode.textContent = apiData?.isDiary ? 'Только вам' : [slug ? `@${slug}` : '', subs ? String(subs) : ''].filter(Boolean).join(' · ');
text.append(titleNode, subNode);
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
channelHeaderButton.disabled = false;
channelHeaderButton.onclick = (event) => {
animatePress(event.currentTarget);
@@ -2910,9 +2935,10 @@ export function render({ navigate, route, chrome }) {
restorePosition,
showStatus,
isActive: () => !disposed,
onAddMessage: () => {
onAddMessage: activeAddMessage = () => {
openAddMessageModal({
channelName: apiData?.channel?.name || '',
channelTitle: apiData?.channel?.displayTitle || '',
navigate,
isActive: () => !disposed,
onSubmit: async ({ text: bodyText, msgSubType }) => {
+2 -2
View File
@@ -934,7 +934,7 @@ function renderDemoFallback(container, navigate, error, onRetry, { localOnly = f
<p class="channel-row-message">${channel.messagePreview || 'Ждем ваших начинаний'}</p>
</div>
<div class="channel-row-controls">
<span class="channel-row-time">—</span>
<span class="channel-row-time">–</span>
</div>
`;
row.prepend(createChannelAvatar(channel));
@@ -1163,7 +1163,7 @@ export function render({ navigate, route, chrome }) {
className: 'topbar--root',
actions: [
{
label: '+',
icon: 'plus',
title: 'Создать канал',
ariaLabel: 'Создать канал',
className: 'channels-create-btn',
+22 -6
View File
@@ -1,3 +1,4 @@
import { iconHtml } from '../components/ui-icon.js';
import { createTopBar } from '../components/topbar.js';
import { createDropdownMenu } from '../components/dropdown-menu.js';
import { renderUserAvatar } from '../components/avatar-image.js';
@@ -98,18 +99,18 @@ function createChatHeaderParts(login, navigate) {
const identityButton = document.createElement('button');
identityButton.type = 'button';
identityButton.className = 'chat-header-peer-btn';
identityButton.className = 'topbar-identity chat-header-peer-btn';
identityButton.title = `Меню ${cleanLogin}`;
identityButton.setAttribute('aria-label', `Открыть меню пользователя ${cleanLogin}`);
const avatarSlot = document.createElement('span');
avatarSlot.className = 'chat-header-avatar-slot';
const textWrap = document.createElement('span');
textWrap.className = 'chat-header-peer-text';
textWrap.className = 'topbar-identity__text chat-header-peer-text';
const nameEl = document.createElement('span');
nameEl.className = 'chat-header-peer-name';
nameEl.className = 'topbar-identity__title chat-header-peer-name';
const metaEl = document.createElement('span');
metaEl.className = 'chat-header-peer-meta';
metaEl.className = 'topbar-identity__sub chat-header-peer-meta';
textWrap.append(nameEl, metaEl);
identityButton.append(avatarSlot, textWrap);
@@ -119,7 +120,9 @@ function createChatHeaderParts(login, navigate) {
const fullName = [firstName, lastName].filter(Boolean).join(' ');
nameEl.textContent = fullName || cleanLogin;
const relation = chatRelationLabel(currentPeer?.relationType);
metaEl.textContent = [fullName ? `@${cleanLogin}` : '', relation].filter(Boolean).join(' · ');
// Статус аккаунта, а не «в сети»: присутствие сервер не сообщает, выдумывать его нельзя
const shining = String(currentPeer?.shineStatus || '').toLowerCase() === 'shining' ? '✧ сияющий аккаунт' : '';
metaEl.textContent = [fullName ? `@${cleanLogin}` : '', shining, relation].filter(Boolean).join(' · ');
metaEl.hidden = !metaEl.textContent;
const avatar = renderUserAvatar({
login: cleanLogin,
@@ -768,6 +771,14 @@ function resolveDeliveryStatus(messages, msg) {
return '…';
}
// Статус сообщения — иконкой и словом для экранного чтения (цвет не единственный носитель смысла)
const DELIVERY_STATUS_VIEW = {
'✓✓': { icon: 'check-double', label: 'Прочитано' },
'✓': { icon: 'check', label: 'Отправлено' },
'!': { icon: 'alert', label: 'Не отправлено' },
'…': { icon: 'clock', label: 'Отправляется' },
};
function resolveDeliveryTone(messages, msg) {
if (resolveEffectiveReadState(messages, msg).isRead) return 'read';
const deliveryState = String(msg?.deliveryState || '').trim().toLowerCase();
@@ -1199,7 +1210,11 @@ function renderLog(
if (status) {
const statusNode = document.createElement('span');
statusNode.className = `bubble-status bubble-status--${resolveDeliveryTone(messages, msg)}`;
statusNode.textContent = status;
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);
}
@@ -1429,6 +1444,7 @@ export function render({ navigate, route, chrome }) {
const chatHeaderParts = createChatHeaderParts(chatId, navigate);
const chatHeader = createTopBar({
center: chatHeaderParts.center,
className: 'topbar--identity',
back: { label: '←', onClick: () => navigate('messages-list') },
actions: [
{
+3 -3
View File
@@ -63,9 +63,9 @@ export function render({navigate, chrome}) {
<div class="stack" style="gap:6px;">
<p class="meta-muted">пользователь выбирает ключи для передачи</p>
<p class="meta-muted">передать можно только существующие ключи</p>
<p class="meta-muted">если ключа нет — он недоступен</p>
<p class="meta-muted">blockchain key — можно передать или нет</p>
<p class="meta-muted">root key — только если существует</p>
<p class="meta-muted">если ключа нет – он недоступен</p>
<p class="meta-muted">blockchain key – можно передать или нет</p>
<p class="meta-muted">root key – только если существует</p>
<p class="meta-muted">client key передаётся всегда</p>
<p class="meta-muted">подключение происходит напрямую через QR</p>
<p class="meta-muted">сервер не используется</p>
+3 -3
View File
@@ -209,9 +209,9 @@ function showClientUpdateHelp() {
'Если UI не обновился:\n\n'
+ '1) Закройте вкладки с Сиянием.\n'
+ `2) Откройте chrome://settings/siteData и удалите данные для ${defaultServerAddress}.\n`
+ '3) Если приложение установлено как PWA — удалите его с устройства.\n'
+ '3) Если приложение установлено как PWA – удалите его с устройства.\n'
+ `4) Откройте ${defaultServerHttp} заново и выполните вход.\n`
+ '5) Если всё ещё старая версия — откройте в режиме инкогнито и проверьте версию в Настройки -> Версии.'
+ '5) Если всё ещё старая версия – откройте в режиме инкогнито и проверьте версию в Настройки -> Версии.'
);
}
@@ -315,7 +315,7 @@ export function render({navigate, chrome}) {
};
const syncPwaButtonLabel = () => {
if (isStandalonePwaMode()) {
setPwaLabel('Приложение установлено — проверить уведомления');
setPwaLabel('Приложение установлено – проверить уведомления');
return;
}
if (canInstallPwa()) {
+4 -14
View File
@@ -1,4 +1,5 @@
import { createTopBar } from '../components/topbar.js';
import { iconHtml } from '../components/ui-icon.js';
import {
authService,
authorizeSession,
@@ -58,7 +59,7 @@ function requestCardHtml(request) {
const shortCode = formatPairingShortCode(request?.shortCode || '');
const client = String(request?.requesterClientPlatform || 'unknown');
const requesterSessionType = Number(request?.requesterSessionType || 0);
const expiresText = request?.expiresAtMs ? formatRelativeTime(request.expiresAtMs) : '—';
const expiresText = request?.expiresAtMs ? formatRelativeTime(request.expiresAtMs) : '–';
const sessionOnly = requesterSessionType === SESSION_TYPE_WALLET;
const sessionKind = pairingSessionKindLabel(requesterSessionType);
return `
@@ -125,19 +126,8 @@ async function runPairingOpWithSessionRestore(runAction) {
function makePasswordToggleIcons() {
return {
eye: `
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M2.4 12s3.6-6.5 9.6-6.5S21.6 12 21.6 12s-3.6 6.5-9.6 6.5S2.4 12 2.4 12Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
<circle cx="12" cy="12" r="2.9" fill="none" stroke="currentColor" stroke-width="1.8"/>
</svg>
`,
eyeOff: `
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M3 4l18 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
<path d="M2.4 12s3.6-6.5 9.6-6.5c2.4 0 4.5.8 6.1 1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
<path d="M21.6 12s-3.6 6.5-9.6 6.5c-2.4 0-4.5-.8-6.1-1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
</svg>
`,
eye: iconHtml('eye', false, 'key-toggle-icon'),
eyeOff: iconHtml('eyeOff', false, 'key-toggle-icon'),
};
}
+64 -45
View File
@@ -10,14 +10,14 @@ import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '.
export const pageMeta = { id: 'entry-settings-view', title: 'Настройки входа', showAppChrome: false };
const SERVER_FIELDS = [
{ key: 'solanaServer', label: 'Адрес Solana сервера' },
{ key: 'solanaServer', label: 'Сервер Solana' },
{ key: 'shineServerLogin', label: 'Сервер Сияния' },
{ key: 'arweaveServer', label: 'Адрес сервера Arweave' },
{ key: 'arweaveServer', label: 'Сервер Arweave' },
];
export function render({ navigate }) {
const screen = document.createElement('section');
screen.className = 'stack';
screen.className = 'stack entry-settings';
const draft = {
language: state.entrySettings.language,
@@ -30,62 +30,79 @@ export function render({ navigate }) {
const timers = new Map();
let disposed = false;
const checks = [];
const body = document.createElement('div');
body.className = 'card stack';
body.className = 'entry-servers';
SERVER_FIELDS.forEach((field) => {
const block = document.createElement('div');
block.className = 'stack';
block.className = 'entry-server';
const head = document.createElement('div');
head.className = 'entry-server__head';
const title = document.createElement('label');
title.className = 'field-label';
title.htmlFor = `entry-${field.key}`;
title.textContent = field.label;
// Статус — он же кнопка повторной проверки.
const checkButton = document.createElement('button');
checkButton.className = 'text-btn entry-status';
checkButton.type = 'button';
const input = document.createElement('input');
input.className = 'input';
input.id = `entry-${field.key}`;
input.type = 'text';
input.autocapitalize = 'off';
input.spellcheck = false;
input.value = draft[field.key];
const controls = document.createElement('div');
controls.className = 'row wrap-row';
const checkButton = document.createElement('button');
checkButton.className = 'secondary-btn server-check-btn';
checkButton.type = 'button';
checkButton.textContent = 'Проверить';
const status = document.createElement('span');
status.className = 'status-line';
const hint = document.createElement('p');
hint.className = 'entry-server__hint';
const applyStatus = (value, exactAddress = '') => {
draft.statuses[field.key] = value;
checkButton.classList.remove('is-available', 'is-unavailable');
status.classList.remove('is-available', 'is-unavailable');
if (disposed) return;
if (value !== 'checking') draft.statuses[field.key] = value;
checkButton.classList.remove('is-available', 'is-unavailable', 'is-checking');
checkButton.disabled = false;
if (value === 'available') {
status.textContent = field.key === 'shineServerLogin' && exactAddress
? `Доступен: ${exactAddress}`
: 'Доступен';
checkButton.textContent = 'Доступен';
checkButton.classList.add('is-available');
status.classList.add('is-available');
} else if (value === 'unavailable') {
status.textContent = 'Недоступен';
checkButton.textContent = 'Недоступен';
checkButton.classList.add('is-unavailable');
status.classList.add('is-unavailable');
} else if (value === 'checking') {
checkButton.textContent = 'Проверка…';
checkButton.classList.add('is-checking');
checkButton.disabled = true;
} else {
status.textContent = field.key === 'shineServerLogin' && draft.shineServerHttp
? `Текущий адрес: ${draft.shineServerHttp}`
: 'Статус не проверен';
checkButton.textContent = 'Проверить';
}
checkButton.setAttribute('aria-label', `${field.label}: ${checkButton.textContent}. Проверить ещё раз`);
if (field.key === 'shineServerLogin') {
const address = exactAddress || draft.shineServerHttp;
hint.textContent = address || '';
hint.hidden = !address;
}
};
let checkSeq = 0;
const runCheck = async () => {
draft[field.key] = input.value.trim();
checkButton.disabled = true;
checkButton.textContent = 'Проверка...';
window.clearTimeout(timers.get(field.key));
// Результат устаревшей проверки (адрес успели поменять) не должен перезаписать новый.
const seq = ++checkSeq;
applyStatus('checking');
try {
if (field.key === 'shineServerLogin') {
const resolved = await resolveAndCheckShineServerLogin(input.value, draft.solanaServer);
if (seq !== checkSeq) return;
draft.shineServerHttp = resolved.httpBase;
draft.shineServer = resolved.wsUrl;
applyStatus(resolved.status, resolved.httpBase);
@@ -93,26 +110,29 @@ export function render({ navigate }) {
const next = await checkServerAvailabilityByKey(field.key, input.value, {
solanaEndpoint: draft.solanaServer,
});
if (seq !== checkSeq) return;
applyStatus(next);
}
} finally {
checkButton.disabled = false;
checkButton.textContent = 'Проверить';
} catch {
if (seq === checkSeq) applyStatus('unavailable');
}
};
applyStatus(draft.statuses[field.key]);
hint.hidden = field.key !== 'shineServerLogin' || !hint.textContent;
checks.push(runCheck);
checkButton.addEventListener('click', runCheck);
input.addEventListener('input', () => {
draft[field.key] = input.value;
checkSeq += 1;
applyStatus('idle');
window.clearTimeout(timers.get(field.key));
timers.set(field.key, window.setTimeout(() => {
void runCheck();
}, 3000));
});
input.addEventListener('blur', () => {
input.addEventListener('change', () => {
void runCheck();
});
input.addEventListener('keydown', (event) => {
@@ -122,17 +142,17 @@ export function render({ navigate }) {
}
});
controls.append(checkButton, status);
block.append(title, input, controls);
head.append(title, checkButton);
block.append(head, input, hint);
body.append(block);
});
const actions = document.createElement('div');
actions.className = 'auth-footer-actions';
actions.className = 'entry-settings__actions';
if (isLocalDemoAvailable()) {
const localDemoButton = document.createElement('button');
localDemoButton.className = 'secondary-btn preauth-local-demo-btn';
localDemoButton.className = 'secondary-btn';
localDemoButton.type = 'button';
localDemoButton.textContent = 'Открыть локальный тестовый режим';
localDemoButton.addEventListener('click', () => {
@@ -145,18 +165,12 @@ export function render({ navigate }) {
const serverUiButton = document.createElement('button');
serverUiButton.className = 'secondary-btn';
serverUiButton.type = 'button';
serverUiButton.textContent = 'Настроить свой сервер';
serverUiButton.textContent = 'Настроить свой сервер ↗';
serverUiButton.addEventListener('click', () => {
const url = new URL('server-ui.html', window.location.href);
window.open(url.toString(), '_blank', 'noopener');
});
const cancelButton = document.createElement('button');
cancelButton.className = 'secondary-btn';
cancelButton.type = 'button';
cancelButton.textContent = 'Отмена';
cancelButton.addEventListener('click', () => navigate('start-view'));
const saveButton = document.createElement('button');
saveButton.className = 'primary-btn';
saveButton.type = 'button';
@@ -170,7 +184,8 @@ export function render({ navigate }) {
}
});
actions.append(serverUiButton, cancelButton, saveButton);
actions.prepend(saveButton);
actions.append(serverUiButton);
screen.append(
createTopBar({
@@ -182,8 +197,12 @@ export function render({ navigate }) {
);
screen.cleanup = () => {
disposed = true;
timers.forEach((timerId) => window.clearTimeout(timerId));
};
// Серверы проверяются сразу — зелёный «Доступен» видно без лишних нажатий.
checks.forEach((check) => { void check(); });
return screen;
}
+105 -122
View File
@@ -1,3 +1,4 @@
import { createTopBar } from '../components/topbar.js';
import {
authService,
authorizeSession,
@@ -23,45 +24,16 @@ import { clearClientAuthData, saveEncryptedUserSecrets } from '../services/key-v
import { clearStoredMessages } from '../services/message-store.js';
import { toUserMessage } from '../services/ui-error-texts.js';
export const pageMeta = { id: 'login-other-device-view', title: 'Войти через другое устройство', showAppChrome: false };
function setStatus(statusEl, message, kind = 'info') {
statusEl.classList.toggle('is-unavailable', kind === 'error');
statusEl.classList.toggle('is-available', kind !== 'error');
statusEl.textContent = message;
statusEl.style.display = message ? '' : 'none';
}
function codeCardHtml() {
return `
<div class="card stack">
<p class="field-label">Код подключения</p>
<div id="pairing-short-code" style="font-size:34px; font-weight:700; letter-spacing:0.12em;">00 00 00 00 00</div>
<p class="meta-muted" id="pairing-status-hint">Покажите этот код на уже подключённом устройстве в разделе «Подключить по коду».</p>
<p class="meta-muted" id="pairing-online-hint"></p>
<p class="meta-muted" id="pairing-expire-hint"></p>
</div>
`;
}
export const pageMeta = { id: 'login-other-device-view', title: 'Вход с другого устройства', showAppChrome: false };
function formatRemaining(ms) {
const safe = Math.max(0, Math.floor(Number(ms || 0) / 1000));
const minutes = Math.floor(safe / 60);
const seconds = safe % 60;
return `${minutes} мин ${seconds} сек`;
}
function resetCodeCard(resultWrap, shortCodeEl, statusHintEl, onlineHintEl, expireHintEl) {
resultWrap.style.display = 'none';
shortCodeEl.textContent = formatPairingShortCode('');
statusHintEl.textContent = 'Покажите этот код на уже подключённом устройстве в разделе «Подключить по коду».';
onlineHintEl.textContent = '';
expireHintEl.textContent = '';
const safe = Math.max(0, Math.ceil(Number(ms || 0) / 1000));
return `${Math.floor(safe / 60)}:${String(safe % 60).padStart(2, '0')}`;
}
export function render({ navigate }) {
const screen = document.createElement('section');
screen.className = 'stack auth-screen auth-screen--other-device';
screen.className = 'stack pairing-login';
let pollTimer = 0;
let countdownTimer = 0;
let activePairingId = '';
@@ -71,67 +43,72 @@ export function render({ navigate }) {
clearAuthMessages();
const panel = document.createElement('section');
panel.className = 'login-panel login-panel--wide stack';
panel.innerHTML = `
<button class="login-panel-inline-back" type="button" id="login-other-device-back" aria-label="Назад">
<span aria-hidden="true">←</span>
<span>Войти через другое устройство</span>
</button>
const who = document.createElement('p');
who.className = 'pairing-who';
// Код и то, что с ним делать.
const codeBlock = document.createElement('div');
codeBlock.className = 'pairing-code-block';
codeBlock.innerHTML = `
<div class="pairing-code-card">
<p class="pairing-code-card__label">Код для входа</p>
<div class="pairing-code" id="pairing-short-code"></div>
<div class="pairing-timer" aria-live="off">
<div class="pairing-timer__bar"><span id="pairing-timer-fill"></span></div>
<span class="pairing-timer__text" id="pairing-timer-text"></span>
</div>
<p class="pairing-online" id="pairing-online"></p>
</div>
<ol class="pairing-steps">
<li>Откройте Сияние, где вы уже вошли</li>
<li>Настройки → Устройства</li>
<li>«Подключить по коду» – введите код</li>
</ol>
<p class="pairing-waiting"><span class="pairing-spinner" aria-hidden="true"></span>Ждём подтверждения…</p>
`;
panel.querySelector('#login-other-device-back')?.addEventListener('click', () => { void cancelActivePairingAndBack(); });
// Сообщение о ходе дела или об ошибке — вместо кода.
const notice = document.createElement('div');
notice.className = 'pairing-notice';
notice.setAttribute('role', 'status');
const noticeSpinner = document.createElement('span');
noticeSpinner.className = 'pairing-spinner';
noticeSpinner.setAttribute('aria-hidden', 'true');
const noticeText = document.createElement('p');
notice.append(noticeSpinner, noticeText);
const formCard = document.createElement('div');
formCard.className = 'card stack login-device-preparation';
formCard.innerHTML = `
<p class="auth-copy" id="pair-login-label"></p>
<input id="pair-login" type="hidden" value="" />
<input id="pair-use-password" type="checkbox" hidden />
<label class="stack" id="pair-password-wrap" style="display:none;">
<span class="field-label">Дополнительный пароль подключения</span>
<input class="input" id="pair-password" type="password" autocomplete="current-password" placeholder="Пароль, заданный на другом устройстве" />
</label>
<button class="primary-btn" type="button" id="pair-start-btn" style="display:none;">Получить код</button>
<p class="meta-muted" id="pair-mode-hint">Создаём код для входа…</p>
const passwordWrap = document.createElement('label');
passwordWrap.className = 'stack pairing-password';
passwordWrap.innerHTML = `
<span class="field-label">Пароль подключения</span>
<input class="input" type="password" autocomplete="current-password" placeholder="Задан на другом устройстве" />
`;
const status = document.createElement('p');
status.className = 'status-line is-unavailable';
status.style.display = 'none';
const startBtn = document.createElement('button');
startBtn.className = 'primary-btn';
startBtn.type = 'button';
startBtn.textContent = 'Получить код';
const resultWrap = document.createElement('div');
resultWrap.className = 'stack';
resultWrap.style.display = 'none';
resultWrap.innerHTML = codeCardHtml();
const loginInput = { value: String(state.loginDraft.login || '').trim() };
const usePasswordInput = { checked: false };
const passwordInput = passwordWrap.querySelector('input');
who.textContent = loginInput.value ? `Вход для @${loginInput.value}` : '';
const shortCodeEl = codeBlock.querySelector('#pairing-short-code');
const timerFillEl = codeBlock.querySelector('#pairing-timer-fill');
const timerTextEl = codeBlock.querySelector('#pairing-timer-text');
const onlineEl = codeBlock.querySelector('#pairing-online');
let activeStartedAtMs = 0;
const loginInput = formCard.querySelector('#pair-login');
const loginLabelEl = formCard.querySelector('#pair-login-label');
const usePasswordInput = formCard.querySelector('#pair-use-password');
const passwordInput = formCard.querySelector('#pair-password');
const startBtn = formCard.querySelector('#pair-start-btn');
const modeHintEl = formCard.querySelector('#pair-mode-hint');
loginInput.value = String(state.loginDraft.login || '').trim();
loginLabelEl.textContent = loginInput.value ? `Вход для @${loginInput.value}` : '';
const shortCodeEl = resultWrap.querySelector('#pairing-short-code');
const statusHintEl = resultWrap.querySelector('#pairing-status-hint');
const onlineHintEl = resultWrap.querySelector('#pairing-online-hint');
const expireHintEl = resultWrap.querySelector('#pairing-expire-hint');
const cancelBtn = document.createElement('button');
cancelBtn.className = 'ghost-btn';
cancelBtn.type = 'button';
cancelBtn.textContent = 'Отмена';
cancelBtn.style.display = 'none';
const syncPasswordUi = () => {
const usePassword = !!usePasswordInput.checked;
passwordInput.parentElement.style.display = usePassword ? '' : 'none';
startBtn.style.display = usePassword ? '' : 'none';
modeHintEl.textContent = usePassword
? 'На доверённом устройстве для входа по коду включён дополнительный пароль.'
: 'Код можно подтвердить на уже подключённом устройстве. Если оно сейчас не в сети, заявка будет ждать до истечения срока.';
if (!usePassword) passwordInput.value = '';
// Этапы: creating → code → approving; отдельно password (нужен пароль) и retry (истекло, отклонено, ошибка).
const showStage = (stage, message = '', { error = false, action = '' } = {}) => {
codeBlock.hidden = stage !== 'code';
passwordWrap.hidden = stage !== 'password';
notice.hidden = stage === 'code' || (stage === 'password' && !message);
noticeSpinner.hidden = !(stage === 'creating' || stage === 'approving');
noticeText.textContent = message;
notice.classList.toggle('is-error', error);
startBtn.hidden = !(stage === 'password' || stage === 'retry');
if (action) startBtn.textContent = action;
};
const stopPolling = () => {
@@ -156,18 +133,17 @@ export function render({ navigate }) {
activePairingId = '';
activeExpiresAtMs = 0;
startBtn.disabled = false;
startBtn.style.display = '';
startBtn.textContent = 'Получить новый код';
cancelBtn.style.display = 'none';
resetCodeCard(resultWrap, shortCodeEl, statusHintEl, onlineHintEl, expireHintEl);
setStatus(status, 'Время ожидания истекло. Получите новый код.', 'error');
showStage('retry', 'Время ожидания истекло', { error: true, action: 'Получить новый код' });
return;
}
expireHintEl.textContent = `Код действителен ещё ${formatRemaining(leftMs)}.`;
const totalMs = Math.max(1, activeExpiresAtMs - activeStartedAtMs);
timerFillEl.style.width = `${Math.min(100, (leftMs / totalMs) * 100).toFixed(1)}%`;
timerTextEl.textContent = formatRemaining(leftMs);
};
const startCountdown = (expiresAtMs) => {
activeExpiresAtMs = Number(expiresAtMs || 0);
activeStartedAtMs = Date.now();
stopCountdown();
updateCountdown();
countdownTimer = window.setInterval(updateCountdown, 1000);
@@ -178,8 +154,6 @@ export function render({ navigate }) {
stopCountdown();
activePairingId = '';
activeExpiresAtMs = 0;
cancelBtn.style.display = 'none';
resetCodeCard(resultWrap, shortCodeEl, statusHintEl, onlineHintEl, expireHintEl);
};
const finalizeAuthorizedLogin = async (keys, login) => {
@@ -255,7 +229,7 @@ export function render({ navigate }) {
}
if (stateValue === 'approved') {
stopCountdown();
setStatus(status, 'Заявка подтверждена. Подключаем устройство...', 'info');
showStage('approving', 'Вход подтверждён. Подключаем устройство…');
const decoded = await decryptPairingPayloadFromEnvelope(payload?.encryptedPayload, requesterMaterial);
const decodedType = String(decoded?.type || '');
if (decodedType === 'shine-esp-session-attach') {
@@ -271,45 +245,43 @@ export function render({ navigate }) {
if (stateValue === 'rejected') {
clearActivePairing();
startBtn.disabled = false;
setStatus(status, 'Подключение отклонено на доверенном устройстве.', 'error');
showStage('retry', 'Вход отклонён на другом устройстве', { error: true, action: 'Получить новый код' });
return;
}
if (stateValue === 'canceled') {
clearActivePairing();
startBtn.disabled = false;
setStatus(status, 'Ожидание подключения отменено.', 'error');
showStage('retry', 'Заявка отменена', { error: true, action: 'Получить новый код' });
return;
}
if (stateValue === 'expired') {
clearActivePairing();
startBtn.disabled = false;
setStatus(status, 'Время ожидания истекло. Получите новый код.', 'error');
showStage('retry', 'Время ожидания истекло', { error: true, action: 'Получить новый код' });
return;
}
schedulePoll();
} catch (error) {
stopPolling();
clearActivePairing();
startBtn.disabled = false;
const message = toUserMessage(error, 'Не удалось проверить статус pairing.');
const message = toUserMessage(error, 'Не удалось проверить, подтверждён ли вход.');
setAuthError(message);
setStatus(status, message, 'error');
showStage('retry', message, { error: true, action: 'Получить новый код' });
}
}, 2200);
};
usePasswordInput.addEventListener('change', syncPasswordUi);
syncPasswordUi();
startBtn.addEventListener('click', async () => {
const login = String(loginInput.value || '').trim();
const usePassword = !!usePasswordInput.checked;
const password = String(passwordInput.value || '');
if (!login) {
setStatus(status, 'Введите логин.', 'error');
navigate('login-view');
return;
}
if (usePassword && !password) {
setStatus(status, 'Введите пароль подключения.', 'error');
showStage('password', 'Введите пароль подключения', { error: true, action: 'Получить код' });
passwordInput.focus();
return;
}
@@ -317,8 +289,8 @@ export function render({ navigate }) {
setAuthBusy(true);
setAuthError('');
setAuthInfo('');
setStatus(status, 'Создаём код для входа…', 'info');
clearActivePairing();
showStage('creating', 'Создаём код для входа…');
try {
await authService.reconnect(state.entrySettings.shineServer);
@@ -346,29 +318,27 @@ export function render({ navigate }) {
}
shortCodeEl.textContent = formatPairingShortCode(payload?.shortCode || '');
statusHintEl.textContent = 'Откройте на доверенном устройстве: Настройки -> Устройства -> Подключить по коду.';
onlineHintEl.textContent = payload?.trustedSessionOnline
? 'Доверенное устройство сейчас в сети и может сразу принять заявку.'
: 'Доверенное устройство сейчас не в сети. Заявка будет ждать его подключения.';
resultWrap.style.display = '';
shortCodeEl.setAttribute('aria-label', `Код для входа: ${String(payload?.shortCode || '').split('').join(' ')}`);
const online = !!payload?.trustedSessionOnline;
onlineEl.textContent = online ? 'Устройство в сети' : 'Устройство не в сети – заявка подождёт';
onlineEl.classList.toggle('is-online', online);
showStage('code');
startCountdown(payload?.expiresAtMs);
state.loginDraft.login = login;
setStatus(status, 'Код создан. Ожидаем подтверждение на другом устройстве...', 'info');
schedulePoll();
} catch (error) {
startBtn.disabled = false;
if (String(error?.code || '').toUpperCase() === 'PAIRING_PASSWORD_INVALID' && !usePassword) {
usePasswordInput.checked = true;
syncPasswordUi();
modeHintEl.textContent = 'Для этого аккаунта включён дополнительный пароль подключения. Введите его, чтобы получить код.';
setStatus(status, 'Введите дополнительный пароль подключения.', 'info');
showStage('password', 'Для входа по коду на другом устройстве задан пароль подключения.', { action: 'Получить код' });
window.setTimeout(() => passwordInput.focus(), 0);
} else if (String(error?.code || '').toUpperCase() === 'PAIRING_PASSWORD_INVALID') {
showStage('password', 'Неверный пароль подключения', { error: true, action: 'Получить код' });
window.setTimeout(() => passwordInput.focus(), 0);
} else {
startBtn.style.display = '';
startBtn.textContent = 'Повторить';
const message = toUserMessage(error, 'Не удалось начать вход через другое устройство.');
setAuthError(message);
setStatus(status, message, 'error');
showStage('retry', message, { error: true, action: 'Повторить' });
}
} finally {
setAuthBusy(false);
@@ -400,8 +370,21 @@ export function render({ navigate }) {
}
};
panel.append(formCard, status, resultWrap);
screen.append(panel);
passwordInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') startBtn.click();
});
screen.append(
createTopBar({
title: 'Вход с другого устройства',
back: { label: '←', onClick: () => { void cancelActivePairingAndBack(); } },
}),
who,
codeBlock,
notice,
passwordWrap,
startBtn,
);
if (!String(loginInput.value || '').trim()) {
window.setTimeout(() => navigate('login-view'), 0);
+25 -15
View File
@@ -208,23 +208,33 @@ export function render({ navigate, chrome }) {
];
let reloadForFilter = () => {};
const filterRow = document.createElement('div');
filterRow.className = 'chip-row chip-row--bleed dm-filter-row';
filterRow.setAttribute('role', 'toolbar');
filterRow.className = 'tabs tabs--auto tabs--dense dm-filter-row';
filterRow.setAttribute('role', 'radiogroup');
filterRow.setAttribute('aria-label', 'Фильтр чатов');
const selectFilter = (value) => {
if (currentChatFilter === value) return;
currentChatFilter = value;
filterRow.querySelectorAll('.tab-btn').forEach((el) => el.setAttribute('aria-checked', String(el.dataset.filter === value)));
reloadForFilter();
};
CHAT_FILTERS.forEach(([value, label]) => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'chip';
chip.dataset.filter = value;
chip.textContent = label;
chip.setAttribute('aria-pressed', String(value === currentChatFilter));
chip.addEventListener('click', () => {
if (currentChatFilter === value) return;
currentChatFilter = value;
filterRow.querySelectorAll('.chip').forEach((el) => el.setAttribute('aria-pressed', String(el.dataset.filter === value)));
reloadForFilter();
});
filterRow.append(chip);
const button = document.createElement('button');
button.type = 'button';
button.className = 'tab-btn';
button.dataset.filter = value;
button.textContent = label;
button.setAttribute('role', 'radio');
button.setAttribute('aria-checked', String(value === currentChatFilter));
button.addEventListener('click', () => selectFilter(value));
filterRow.append(button);
});
filterRow.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
const index = CHAT_FILTERS.findIndex(([value]) => value === currentChatFilter);
const next = CHAT_FILTERS[(index + (event.key === 'ArrowRight' ? 1 : -1) + CHAT_FILTERS.length) % CHAT_FILTERS.length][0];
selectFilter(next);
filterRow.querySelector(`[data-filter="${next}"]`)?.focus();
event.preventDefault();
});
const head = createTopBar({
+1 -1
View File
@@ -935,7 +935,7 @@ export function render({ navigate, route, chrome } = {}) {
historyChip.disabled = x2Enabled;
historyChip.setAttribute('aria-disabled', x2Enabled ? 'true' : 'false');
historyChip.title = x2Enabled
? '«Друзья друзей» показывают отдельную карту — недавние временно не используются.'
? '«Друзья друзей» показывают отдельную карту – недавние временно не используются.'
: (historyDepth > 0
? `На карте остаются последние ${historyDepth} человека, через которых вы переходили. Нажмите, чтобы изменить.`
: 'Недавние выключены. Нажмите, чтобы на карте оставался предыдущий человек.');
+16 -16
View File
@@ -255,7 +255,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
const a11y = document.createElement('div');
a11y.className = 'fg-a11y';
a11y.setAttribute('role', 'region');
a11y.setAttribute('aria-label', 'Карта связей — список');
a11y.setAttribute('aria-label', 'Карта связей – список');
stage.append(edgesSvg, world, a11y);
ensureShineFilter(); // SVG-фильтр свечения «сияющих» (нужен до первой отрисовки узлов)
@@ -656,7 +656,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
const focus = nodes.find((n) => n.isFocus);
const tier1 = nodes.filter((n) => n.tier === 1 && !n.isFocus);
const rel = { family: 'семья', friend: 'друг', close_friend: 'близкий друг', business: 'бизнес', contact: 'контакт' };
const items = tier1.map((n) => `<li>${escapeHtml(n.name || n.login || String(n.id))}${n.shining ? ' — сияющий' : ''} (${rel[n.relationType] || 'связь'})</li>`).join('');
const items = tier1.map((n) => `<li>${escapeHtml(n.name || n.login || String(n.id))}${n.shining ? ' – сияющий' : ''} (${rel[n.relationType] || 'связь'})</li>`).join('');
a11y.innerHTML = `<p>Центр: ${escapeHtml(focus ? (focus.name || focus.login || '') : '')}. Связей 1-го уровня: ${tier1.length}.</p><ul>${items}</ul>`;
}
function escapeHtml(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])); }
@@ -696,7 +696,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
node.hidden = false;
node.bloom = false;
node.dotRadius = spec.isFocus ? 32 : (tier >= 3 ? 5 : (tier === 2 ? 16 : (spec.dotOnly ? 7 : 26)));
// обновляем классы элемента (роль/тип/свечение/уровень) — без пересоздания DOM
// обновляем классы элемента (роль/тип/свечение/уровень) – без пересоздания DOM
node.el.className = spec.dotOnly
? ['ui-button', 'fg-node', 'fg-dot', tier >= 3 ? 'is-tier3' : '', src.shining ? 'is-shine' : '', src.official ? 'is-official' : '', `is-${src.relationType || 'contact'}`].filter(Boolean).join(' ')
: ['ui-button', 'fg-node', spec.isFocus ? 'is-focus' : '', src.shining ? 'is-shine' : '', src.official ? 'is-official' : '', `is-${src.relationType || 'contact'}`, tier === 2 ? 'is-tier2' : '', tier >= 2 ? 'is-secondary' : '', src.common ? 'is-common' : ''].filter(Boolean).join(' ');
@@ -711,7 +711,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
// Ограничение ручного pan: карту можно свободно двигать, пока её видимая геометрия пересекает
// обе центральные оси viewport. На крайнем положении к центральной линии прижимается край
// крайнего аватара — полностью выбросить весь граф за экран больше нельзя.
// крайнего аватара – полностью выбросить весь граф за экран больше нельзя.
function clampCameraPosition(nextX, nextY) {
const visible = nodes.filter((n) => !n.hidden && (Number(n.opacity) || 0) > 0.02);
if (!visible.length) return { x: 0, y: 0 };
@@ -783,14 +783,14 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
n.el.style.transform =
`translate(calc(${n.x}px - 50%), calc(${n.y}px - 50%)) scale(${n.scale * ds})`;
n.el.style.opacity = String(n.opacity * (n.spotCur ?? 1)); // spotlight/глубина: затемнённые тусклее
// расфокус глубины (dive): фоновые узлы уходят в blur; чёткие — без фильтра (дёшево)
// расфокус глубины (dive): фоновые узлы уходят в blur; чёткие – без фильтра (дёшево)
n.el.style.filter = (n.depthBlur > 0.15 && n.opacity > 0.02) ? `blur(${n.depthBlur.toFixed(1)}px)` : '';
n.el.style.pointerEvents = n.hidden && n.opacity <= 0.01 ? 'none' : '';
}
}
// Глубина 2-3 уровней (только лаборатория): узлы tier≥2 не участвуют в физике. По умолчанию
// СКРЫТЫ (схлопнуты в родителя, opacity 0) — и «выплывают» вокруг родителя по мере его раскрытия
// СКРЫТЫ (схлопнуты в родителя, opacity 0) – и «выплывают» вокруг родителя по мере его раскрытия
// (parent.expandP: 0 скрыто → 1 выплыло). Так нет «каши»: видно только то, с чем взаимодействуешь.
function layoutDeep() {
if (!hasDeep) return;
@@ -820,13 +820,13 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
const pr = ORB_R * (p.scale || 1) * (p.depthScale || 1); // визуальный радиус родителя (world-единицы)
const cnt = childCountByParent.get(n.parentId) || 1;
const ringR = Math.max(baseR + pr, cnt * 13); // расталкивание: дети без наложений (клиренс + место)
const r = ringR * e; // при e=0 — в центре родителя, при 1 — на полной орбите
const r = ringR * e; // при e=0 – в центре родителя, при 1 – на полной орбите
// ВЕЕР «полукругом наружу»: раскрываем детей в сторону ОТ пути назад (от деда к родителю),
// чтобы они не перекрывали нить-крошку и родителя. Равномерно по индексу среди братьев.
const gp = nodeById.get(p.parentId);
const ox = p.x - (gp ? gp.x : 0);
const oy = p.y - (gp ? gp.y : 0);
const outward = (ox || oy) ? Math.atan2(oy, ox) : n.deepAngle; // направление наружу (фолбэк — старый угол)
const outward = (ox || oy) ? Math.atan2(oy, ox) : n.deepAngle; // направление наружу (фолбэк – старый угол)
const t = cnt > 1 ? ((n.sibIndex || 0) / (cnt - 1) - 0.5) : 0; // -0.5..0.5 по веера
const ang = outward + t * DEEP_FAN;
n.x = p.x + Math.cos(ang) * r;
@@ -834,7 +834,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
const baseOp = tier === 2 ? DEEP2_OPACITY : DEEP3_OPACITY;
// tier-3: точка-звезда (scale ~1, CSS фиксирует 9px) ИЛИ аватарка при LOD-апгрейде (мельче, 52px*0.42)
const baseSc = tier === 2 ? DEEP2_SCALE : (n.lod === 'full' ? 0.42 : 1);
// вложенность: tier-3 виден только когда виден его tier-2 родитель (он сам — глубокий)
// вложенность: tier-3 виден только когда виден его tier-2 родитель (он сам – глубокий)
const parentVis = p.tier >= 2 ? ((p.opacity || 0) > 0.04 ? 1 : 0) : 1;
n.opacity = baseOp * e * parentVis;
n.scale = baseSc * (0.3 + 0.7 * e); // лёгкий «поп» при выплывании
@@ -861,7 +861,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
return moving;
}
// Во время CSS-bloom (когда renderNodes не вызывается — узлы 1-го уровня анимирует компоновщик)
// Во время CSS-bloom (когда renderNodes не вызывается – узлы 1-го уровня анимирует компоновщик)
// отдельно позиционируем глубокие узлы из JS, чтобы они следовали за родителями.
function renderDeepNodes() {
if (!hasDeep) return;
@@ -875,14 +875,14 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
}
// LOD (level-of-detail): при сильном зуме (pinch/dive) видимые точки 3-го уровня дорисовываются как
// маленькие аватарки (лицо+имя), при отдалении — сворачиваются обратно в светящиеся точки.
// маленькие аватарки (лицо+имя), при отдалении – сворачиваются обратно в светящиеся точки.
// Пере-рендер DOM только при пересечении порога (редкое событие); ежекадровая проверка дешёвая.
function updateLod() {
if (!hasDeep) return;
for (const n of nodes) {
if (n.tier < 3) continue; // LOD касается только микрозвёзд 3-го уровня
const isFull = n.lod === 'full';
// гистерезис: апгрейд на UP, откат на DOWN — у промежуточного зума состояние «залипает» (без мигания)
// гистерезис: апгрейд на UP, откат на DOWN – у промежуточного зума состояние «залипает» (без мигания)
const threshold = isFull ? LOD_ZOOM_DOWN : LOD_ZOOM_UP;
const wantFull = zoom >= threshold && (n.opacity > 0.04); // апгрейдим только видимые
if (wantFull === isFull) continue;
@@ -986,8 +986,8 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
edgesSvg.innerHTML = '';
return;
}
// концы линий — строго по центрам узлов (намертво привязаны), изгиб даёт скорость.
// Z — зум камеры: SVG-слой отдельный (не масштабируется), поэтому координаты узлов умножаем на zoom.
// концы линий – строго по центрам узлов (намертво привязаны), изгиб даёт скорость.
// Z – зум камеры: SVG-слой отдельный (не масштабируется), поэтому координаты узлов умножаем на zoom.
const Z = zoom;
const tx = (n) => centerX + camX + n.x * Z;
const ty = (n) => centerY + camY + n.y * Z;
@@ -1007,14 +1007,14 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
const fx = centerX + camX + parent.x * Z;
const fy = centerY + camY + parent.y * Z;
// радиус контакта = реальный радиус сферы орба: полный орб = ORB_R (см. renderNodes pr=ORB_R*…),
// лёгкая точка (.fg-dot) = её dotRadius. Старое dotRadius у орбов (32/16) — легаси, давало разный зазор.
// лёгкая точка (.fg-dot) = её dotRadius. Старое dotRadius у орбов (32/16) – легаси, давало разный зазор.
const fr = (parent.dotOnly ? parent.dotRadius : ORB_R) * parent.scale * (parent.depthScale ?? 1) * Z;
const nx = tx(n);
const ny = ty(n);
if ((nx < -80 && fx < -80) || (nx > viewW + 80 && fx > viewW + 80)) continue;
if ((ny < -80 && fy < -80) || (ny > viewH + 80 && fy > viewH + 80)) continue;
// Эффект ПРОРАСТАНИЯ: новый узел во время разлёта (bloom) — линию тянем к его ФИНАЛЬНОЙ точке
// Эффект ПРОРАСТАНИЯ: новый узел во время разлёта (bloom) – линию тянем к его ФИНАЛЬНОЙ точке
// и раскрываем dashoffset'ом синхронно с разлётом (кончик трекает аватарку). Переезжающие/
// общие узлы и покой — линия идёт к ТЕКУЩЕЙ точке (просто следует за узлом, без dash).
const growing = cssBloom && cssBloomKind === 'bloom' && !n.isFocus && n.edgeGrow < 1;
+61 -98
View File
@@ -3,6 +3,8 @@ import { renderUserAvatar } from '../components/avatar-image.js';
import { authService, state } from '../state.js';
import { loadProfileSnapshot } from '../services/user-profile-params.js';
import { makeProfileRoute, makeShineMessageRoute } from '../services/shine-routes.js';
import { formatListTime } from '../services/channels-ux.js';
import { iconHtml } from '../components/ui-icon.js';
const CONNECTION_CLOSE_FRIEND = 10;
const CONNECTION_UNCLOSE_FRIEND = 11;
@@ -19,21 +21,21 @@ const profileSnapshotPending = new Map();
function connectionActionLabel(typeCode) {
switch (Number(typeCode)) {
case CONNECTION_CLOSE_FRIEND: return 'Добавил(а) вас в близкие друзья.';
case CONNECTION_UNCLOSE_FRIEND: return 'Удалил(а) вас из близких друзей.';
case CONNECTION_FRIEND: return 'Добавил(а) вас в друзья.';
case CONNECTION_UNFRIEND: return 'Удалил(а) вас из друзей.';
case CONNECTION_SHINE_CONFIRMED: return 'Подтвердил(а), что вы Сияющий.';
case CONNECTION_SHINE_UNCONFIRMED: return 'Снял(а) подтверждение «Сияющий».';
case CONNECTION_OFFICIAL_CONFIRMED: return 'Подтвердил(а) официальный статус аккаунта.';
case CONNECTION_OFFICIAL_UNCONFIRMED: return 'Снял(а) подтверждение официального статуса.';
default: return 'Изменил(а) связь с вами.';
case CONNECTION_CLOSE_FRIEND: return 'Добавил(а) вас в близкие друзья';
case CONNECTION_UNCLOSE_FRIEND: return 'Убрал(а) вас из близких друзей';
case CONNECTION_FRIEND: return 'Добавил(а) вас в друзья';
case CONNECTION_UNFRIEND: return 'Убрал(а) вас из друзей';
case CONNECTION_SHINE_CONFIRMED: return 'Подтвердил(а), что вы сияющий';
case CONNECTION_SHINE_UNCONFIRMED: return 'Снял(а) подтверждение «сияющий»';
case CONNECTION_OFFICIAL_CONFIRMED: return 'Подтвердил(а) официальный статус аккаунта';
case CONNECTION_OFFICIAL_UNCONFIRMED: return 'Снял(а) подтверждение официального статуса';
default: return 'Изменил(а) связь с вами';
}
}
function eventActionLabel(typeCode) {
if (Number(typeCode) === CONNECTION_UNFOLLOW) return 'Отписался(-ась) от вашего канала.';
return 'Подписался(-ась) на ваш канал.';
if (Number(typeCode) === CONNECTION_UNFOLLOW) return 'Отписался(-ась) от вашего канала';
return 'Подписался(-ась) на ваш канал';
}
export const pageMeta = { id: 'notifications-view', title: 'Уведомления' };
@@ -58,23 +60,6 @@ function normalizeItem(item) {
};
}
function formatRelativeTime(value) {
const ts = Number(value || 0);
if (!Number.isFinite(ts) || ts <= 0) return '';
const diffMs = Math.max(0, Date.now() - ts);
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
const week = 7 * day;
if (diffMs < minute) return 'сейчас';
if (diffMs < hour) return `${Math.max(1, Math.floor(diffMs / minute))} мин.`;
if (diffMs < day) return `${Math.max(1, Math.floor(diffMs / hour))} ч.`;
if (diffMs < week) return `${Math.max(1, Math.floor(diffMs / day))} дн.`;
return `${Math.max(1, Math.floor(diffMs / week))} нед.`;
}
function profileField(snapshot, key) {
const row = (Array.isArray(snapshot?.fields) ? snapshot.fields : [])
.find((field) => String(field?.key || '') === key);
@@ -153,7 +138,7 @@ async function enrichItem(item, activeTab) {
function renderEmpty(activeTab) {
const card = document.createElement('article');
card.className = 'card stack notification-empty-state';
card.className = 'stack notification-empty-state';
const title = document.createElement('strong');
title.textContent = activeTab === 'events' ? 'Пока нет событий' : activeTab === 'connections' ? 'Пока нет связей' : 'Пока нет ответов';
const text = document.createElement('p');
@@ -163,72 +148,50 @@ function renderEmpty(activeTab) {
return card;
}
function renderIdentity(item) {
function renderAvatar(item) {
const profile = item.profile;
const firstName = profileField(profile, 'first_name');
const lastName = profileField(profile, 'last_name');
const fullName = [firstName, lastName].filter(Boolean).join(' ') || item.sourceLogin || 'Пользователь';
const avatar = profile?.avatar?.txId
? {
ar: String(profile.avatar.txId || '').trim(),
sha256Hex: String(profile.avatar.sha256Hex || '').trim().toLowerCase(),
}
: null;
const header = document.createElement('div');
header.className = 'notification-identity';
header.append(renderUserAvatar({
return renderUserAvatar({
login: item.sourceLogin || 'unknown',
firstName,
lastName,
firstName: profileField(profile, 'first_name'),
lastName: profileField(profile, 'last_name'),
avatar,
size: 'md',
className: 'notification-avatar',
}));
});
}
const text = document.createElement('div');
text.className = 'notification-identity-text';
const primary = document.createElement('div');
primary.className = 'notification-identity-primary';
// Строка как в списке чатов: имя и время, ниже – что произошло и текст ответа.
function renderHead(item) {
const profile = item.profile;
const fullName = [profileField(profile, 'first_name'), profileField(profile, 'last_name')].filter(Boolean).join(' ')
|| item.sourceLogin || 'Пользователь';
const head = document.createElement('div');
head.className = 'notification-card__head';
const name = document.createElement('strong');
name.className = 'notification-person-name';
name.className = 'notification-card__name';
name.textContent = fullName;
primary.append(name);
const login = String(item.sourceLogin || '').trim();
if (login) {
const loginEl = document.createElement('span');
loginEl.className = 'notification-login';
loginEl.textContent = `@${login}`;
primary.append(loginEl);
}
const relative = formatRelativeTime(item.createdAtMs);
if (relative) {
const separator = document.createElement('span');
separator.className = 'notification-time-separator';
separator.textContent = '·';
const time = document.createElement('span');
time.className = 'notification-time';
time.textContent = relative;
primary.append(separator, time);
}
text.append(primary);
header.append(text);
return header;
head.append(name);
const time = document.createElement('span');
time.className = 'notification-card__time';
time.textContent = formatListTime(item.createdAtMs);
head.append(time);
return head;
}
function renderEngagement(engagement) {
if (!engagement) return null;
const stats = [
{ key: 'likesCount', icon: '♥', label: 'Лайки' },
{ key: 'repliesCount', icon: '💬', label: 'Ответы' },
{ key: 'ratingsCount', icon: '★', label: 'Оценки' },
{ key: 'repostsCount', icon: '↻', label: 'Репосты' },
{ key: 'sharesCount', icon: '↗', label: 'Отправки' },
{ key: 'likesCount', icon: 'heart', label: 'Лайки' },
{ key: 'repliesCount', icon: 'message', label: 'Ответы' },
{ key: 'repostsCount', icon: 'refresh', label: 'Репосты' },
{ key: 'sharesCount', icon: 'forward', label: 'Отправки' },
].filter(({ key }) => Number(engagement[key] || 0) > 0);
if (!stats.length) return null;
@@ -243,7 +206,7 @@ function renderEngagement(engagement) {
const iconEl = document.createElement('span');
iconEl.className = 'notification-engagement-icon';
iconEl.setAttribute('aria-hidden', 'true');
iconEl.textContent = icon;
iconEl.innerHTML = iconHtml(icon);
const countEl = document.createElement('span');
countEl.className = 'notification-engagement-count';
@@ -289,31 +252,31 @@ function bindNotificationNavigation(row, routePath, navigate) {
function renderItem(item, activeTab, navigate) {
const row = document.createElement('article');
row.className = 'card stack notification-card';
row.className = 'notification-card';
bindNotificationNavigation(row, notificationRoute(item, activeTab), navigate);
row.append(renderIdentity(item));
const action = document.createElement('p');
action.className = 'notification-action';
if (activeTab === 'connections') {
action.textContent = connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType);
} else if (activeTab === 'events') {
action.textContent = eventActionLabel(item.sourceMsgSubType, item);
} else {
action.textContent = 'Ответил(а) на ваше сообщение.';
}
row.append(action);
const body = document.createElement('div');
body.className = 'notification-card__body';
body.append(renderHead(item));
if (activeTab === 'replies') {
const body = document.createElement('p');
body.className = 'notification-content';
body.textContent = item.sourceText || 'Ответ без текста.';
row.append(body);
// Во вкладке «Ответы» всё – ответы: подпись «ответил(а)» не нужна, сразу текст.
const text = document.createElement('p');
text.className = 'notification-card__text';
text.textContent = item.sourceText || 'Ответ без текста';
body.append(text);
const engagement = renderEngagement(item.engagement);
if (engagement) row.append(engagement);
if (engagement) body.append(engagement);
} else {
const action = document.createElement('p');
action.className = 'notification-card__action';
action.textContent = activeTab === 'connections'
? connectionActionLabel(item.connectionTypeCode ?? item.sourceMsgSubType)
: eventActionLabel(item.sourceMsgSubType, item);
body.append(action);
}
row.append(renderAvatar(item), body);
return row;
}
@@ -333,7 +296,7 @@ export function render({ navigate, chrome } = {}) {
screen.append(tabs);
const list = document.createElement('div');
list.className = 'stack notifications-list';
list.className = 'notifications-list';
let payloadCache = null;
let requestSeq = 0;
let observer = null;
@@ -407,14 +370,14 @@ export function render({ navigate, chrome } = {}) {
const items=await Promise.all(base.map(x=>enrichItem(x,tab)));
const unread=items.filter(x=>x.createdAtMs>seenAt); const old=items.filter(x=>x.createdAtMs<=seenAt);
const nodes=[];
const groupTitle=(text)=>{const el=document.createElement('h2');el.className='notification-group-title';el.textContent=text;return el;};
if(unread.length) nodes.push(groupTitle(`Новые · ${unread.length}`));
unread.forEach(x=>{const n=renderItem(x,tab,navigate);n.classList.add('notification-card--new');n.dataset.createdAtMs=String(x.createdAtMs);nodes.push(n);});
let divider=null;
if(unread.length){divider=document.createElement('div');divider.className='notification-new-divider';divider.textContent=`НОВЫЕ · ${unread.length}`;nodes.push(divider);}
if(unread.length && old.length) nodes.push(groupTitle('Ранее'));
old.forEach(x=>nodes.push(renderItem(x,tab,navigate))); list.replaceChildren(...nodes);
if(unread.length && 'IntersectionObserver' in window){
observer=new IntersectionObserver(entries=>{ entries.forEach(e=>{ if(e.isIntersecting && e.intersectionRatio>=0.5){ const ts=Number(e.target.dataset.createdAtMs||0); if(ts>0){e.target.classList.remove('notification-card--new');scheduleSeen(tab,ts);} } }); },{threshold:[0.5]});
list.querySelectorAll('.notification-card--new').forEach(n=>observer.observe(n));
requestAnimationFrame(()=>divider?.scrollIntoView({block:'end'}));
}
}
+1 -1
View File
@@ -709,7 +709,7 @@ export function render({ navigate, chrome }) {
});
if (entered === null) return;
if (String(entered).length > Number(field.maxLength || 300)) {
window.alert(`Максимальная длина поля «${field.label}» — ${Number(field.maxLength || 300)} символов.`);
window.alert(`Максимальная длина поля «${field.label}» – ${Number(field.maxLength || 300)} символов.`);
return;
}
+2 -2
View File
@@ -23,7 +23,7 @@ function vapidBase64ToUint8Array(base64String) {
function formatTs(ts) {
const num = Number(ts);
if (!Number.isFinite(num) || num <= 0) return '—';
if (!Number.isFinite(num) || num <= 0) return '–';
try {
return new Date(num).toLocaleString('ru-RU');
} catch {
@@ -100,7 +100,7 @@ function rowEl(label, value, tone) {
const right = document.createElement('span');
right.className = 'pwa-diag-value';
right.textContent = String(value || '—');
right.textContent = String(value || '–');
const indicator = document.createElement('span');
indicator.className = `pwa-diag-indicator is-${tone || 'neutral'}`;
+31 -46
View File
@@ -1,4 +1,5 @@
import { createTopBar } from '../components/topbar.js';
import { iconHtml } from '../components/ui-icon.js';
import { authService, clearAuthMessages, resetRegistrationFlow, state } from '../state.js';
import { toUserMessage } from '../services/ui-error-texts.js';
import {
@@ -31,19 +32,8 @@ function normalizeLoginForTemporaryUiGuard(login) {
function makePasswordToggleIcons() {
return {
eye: `
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M2.4 12s3.6-6.5 9.6-6.5S21.6 12 21.6 12s-3.6 6.5-9.6 6.5S2.4 12 2.4 12Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
<circle cx="12" cy="12" r="2.9" fill="none" stroke="currentColor" stroke-width="1.8"/>
</svg>
`,
eyeOff: `
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M3 4l18 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
<path d="M2.4 12s3.6-6.5 9.6-6.5c2.4 0 4.5.8 6.1 1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
<path d="M21.6 12s-3.6 6.5-9.6 6.5c-2.4 0-4.5-.8-6.1-1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
</svg>
`,
eye: iconHtml('eye', false, 'key-toggle-icon'),
eyeOff: iconHtml('eyeOff', false, 'key-toggle-icon'),
};
}
@@ -97,9 +87,10 @@ export function render({ navigate }) {
passwordInputRow.className = 'inline-input-row';
passwordInputRow.append(passwordInput, passwordToggleButton);
const statusText = document.createElement('p');
// Строка под логином всегда занимает место — сообщения не сдвигают форму.
const statusText = document.createElement('span');
statusText.className = 'status-line registration-login-status';
statusText.style.display = 'none';
statusText.setAttribute('aria-live', 'polite');
const formError = document.createElement('p');
formError.className = 'status-line is-unavailable';
@@ -135,10 +126,24 @@ export function render({ navigate }) {
passwordLengthText.textContent = `Символов в пароле: ${getCurrentPassword().length}`;
}
function setStatusMessage(message, kind = '') {
function setStatusMessage(message, kind = '', details = '') {
statusText.textContent = message;
statusText.title = details || message;
statusText.className = kind ? `status-line registration-login-status ${kind}` : 'status-line registration-login-status';
statusText.style.display = message ? '' : 'none';
}
function showCheckedLoginStatus(isFree, className) {
if (!isFree) {
setStatusMessage('Логин уже занят', 'is-unavailable');
} else if (className === 'free') {
setStatusMessage('Логин свободен', 'is-available');
} else if (className === 'premium') {
setStatusMessage('Премиум-логин – покупка через DAO', 'is-unavailable');
} else if (className === 'company') {
setStatusMessage('Логин бренда – нужно согласование', 'is-unavailable');
} else {
setStatusMessage('Не подходит для обычной регистрации', 'is-unavailable');
}
}
function resetLoginCheckState() {
@@ -186,34 +191,24 @@ export function render({ navigate }) {
const normalizedLogin = normalizeLoginForTemporaryUiGuard(login);
if (!normalizedLogin) {
setStatusMessage('Логин содержит недопустимые символы или имеет неверную длину ❌', 'is-unavailable');
setStatusMessage('Только латиница, цифры и _, до 20 символов', 'is-unavailable');
formError.style.display = 'none';
return false;
}
if (normalizedLogin.length < MIN_REGISTRATION_LOGIN_LENGTH) {
setStatusMessage(`Логин должен быть не короче ${MIN_REGISTRATION_LOGIN_LENGTH} символов ❌`, 'is-unavailable');
setStatusMessage(`Не короче ${MIN_REGISTRATION_LOGIN_LENGTH} символов`, 'is-unavailable');
formError.style.display = 'none';
return false;
}
if (login === lastCheckedLogin) {
if (!lastCheckedFree) {
setStatusMessage('Логин уже занят ❌', 'is-unavailable');
} else if (lastCheckedClassName === 'free') {
setStatusMessage('Логин свободен ✅', 'is-available');
} else if (lastCheckedClassName === 'premium') {
setStatusMessage('Логин свободен, но это премиум-логин (покупка через DAO) ❌', 'is-unavailable');
} else if (lastCheckedClassName === 'company') {
setStatusMessage('Логин свободен, но относится к компании/бренду (отдельное согласование) ❌', 'is-unavailable');
} else {
setStatusMessage('Логин нельзя использовать для обычной регистрации ❌', 'is-unavailable');
}
showCheckedLoginStatus(lastCheckedFree, lastCheckedClassName);
formError.style.display = 'none';
return lastCheckedFree && lastCheckedClassName === 'free';
}
setStatusMessage('Проверяем логин...');
setStatusMessage('Проверяем логин…', 'is-checking');
try {
const check = await checkLoginExistsOnSolana({
login,
@@ -237,28 +232,18 @@ export function render({ navigate }) {
lastCheckedLogin = login;
lastCheckedFree = isFree;
lastCheckedClassName = className;
if (!isFree) {
setStatusMessage('Логин уже занят ❌', 'is-unavailable');
} else if (className === 'free') {
setStatusMessage('Логин свободен ✅', 'is-available');
} else if (className === 'premium') {
setStatusMessage('Логин свободен, но это премиум-логин (покупка через DAO) ❌', 'is-unavailable');
} else if (className === 'company') {
setStatusMessage('Логин свободен, но относится к компании/бренду (отдельное согласование) ❌', 'is-unavailable');
} else {
setStatusMessage('Логин нельзя использовать для обычной регистрации ❌', 'is-unavailable');
}
showCheckedLoginStatus(isFree, className);
formError.style.display = 'none';
return isFree && className === 'free';
} catch (error) {
if (runId !== loginCheckRunId) return false;
if (isSolanaRpcUnavailableError(error)) {
setStatusMessage('Нет связи с сервером Solana. Попробуйте ещё раз позже.', 'is-unavailable');
setStatusMessage('Нет связи с Solana – попробуйте позже', 'is-unavailable');
return false;
}
const base = toUserMessage(error, 'Не удалось проверить логин');
const details = formatSolanaErrorDetails(error);
setStatusMessage(`${base}. Детали: ${details}`, 'is-unavailable');
setStatusMessage(base, 'is-unavailable', `${base}. Детали: ${details}`);
return false;
}
}
@@ -313,8 +298,8 @@ export function render({ navigate }) {
const passwordLabel = document.createElement('label');
passwordLabel.className = 'stack registration-password-single';
passwordLabel.innerHTML = '<span class="field-label">Пароль</span>';
form.append(loginField, statusText, passwordLabel);
loginField.append(loginInput);
form.append(loginField, passwordLabel);
loginField.append(loginInput, statusText);
passwordLabel.append(passwordInputRow);
form.append(passwordLengthText, formError, faqButton);
actions.innerHTML = '';
@@ -115,11 +115,11 @@ export function render({ navigate }) {
rootSep.textContent = 'Root key (recovery)';
card.append(rootSep);
card.append(makePublicField({
label: 'Root / recovery — публичный (base58)',
label: 'Root / recovery – публичный (base58)',
value: bytesToBase58(base64ToBytes(keyBundle.rootPair.publicKeyB64)),
}));
card.append(makeSecretField({
label: 'Root / recovery — приватный (seed base58, 32 байта)',
label: 'Root / recovery – приватный (seed base58, 32 байта)',
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.rootPair.privatePkcs8B64)),
}));
@@ -129,11 +129,11 @@ export function render({ navigate }) {
bchSep.textContent = 'Blockchain key';
card.append(bchSep);
card.append(makePublicField({
label: 'Blockchain — публичный (base58)',
label: 'Blockchain – публичный (base58)',
value: bytesToBase58(base64ToBytes(keyBundle.blockchainPair.publicKeyB64)),
}));
card.append(makeSecretField({
label: 'Blockchain — приватный (seed base58, 32 байта)',
label: 'Blockchain – приватный (seed base58, 32 байта)',
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.blockchainPair.privatePkcs8B64)),
}));
@@ -143,11 +143,11 @@ export function render({ navigate }) {
devSep.textContent = 'Client key (= Solana wallet)';
card.append(devSep);
card.append(makePublicField({
label: 'Client — публичный (base58)',
label: 'Client – публичный (base58)',
value: bytesToBase58(base64ToBytes(keyBundle.clientPair.publicKeyB64)),
}));
card.append(makeSecretField({
label: 'Client — приватный (seed base58, 32 байта)',
label: 'Client – приватный (seed base58, 32 байта)',
value: bytesToBase58(extractSeed32FromPkcs8B64(keyBundle.clientPair.privatePkcs8B64)),
}));
}
+42 -54
View File
@@ -18,47 +18,44 @@ const EMPTY_PASSWORD_WORDS = Array.from({ length: 12 }, () => '');
export function render({ navigate }) {
const screen = document.createElement('section');
screen.className = 'stack';
screen.className = 'stack keys-screen';
const isLoginFlow = state.registrationDraft.flowType === 'login';
const normalizedLogin = (state.registrationDraft.login || '').trim();
const displayLogin = normalizedLogin || '@new.user';
const card = document.createElement('div');
card.className = 'card stack';
const title = document.createElement('p');
title.className = 'auth-copy';
title.textContent = isLoginFlow
? `Вход выполнен для логина ${displayLogin}.`
: `Отлично, логин ${displayLogin} зарегистрирован.`;
const displayLogin = normalizedLogin ? `@${normalizedLogin.replace(/^@/, '')}` : '@new.user';
const lead = document.createElement('div');
lead.className = 'keys-lead';
const title = document.createElement('h1');
title.className = 'keys-lead__title';
title.textContent = isLoginFlow ? `Вы вошли как ${displayLogin}` : `${displayLogin} зарегистрирован`;
const question = document.createElement('p');
question.className = 'auth-copy';
question.textContent = 'Какие ключи сохранить в зашифрованном контейнере IndexedDB?';
const nextStep = document.createElement('p');
nextStep.className = 'meta-muted';
nextStep.textContent = 'После сохранения откроется профиль. Для проверки откройте вкладку «Каналы».';
question.className = 'keys-lead__text';
question.textContent = 'Какие ключи хранить на этом устройстве?';
const questionHint = document.createElement('p');
questionHint.className = 'keys-lead__text';
questionHint.textContent = 'Они хранятся в зашифрованном виде.';
lead.append(title, question, questionHint);
const status = document.createElement('p');
status.className = 'status-line is-unavailable';
status.style.display = 'none';
const createKeyInfo = (toggle, titleText, descriptionText) => {
const wrap = document.createElement('div');
wrap.className = 'key-storage-option stack';
const createKeyRow = (toggle, titleText, descriptionText) => {
const row = document.createElement('label');
row.className = 'checkbox-row';
row.append(toggle, document.createTextNode(titleText));
const description = document.createElement('p');
description.className = 'meta-muted key-storage-option__description';
row.className = 'keys-row';
const text = document.createElement('span');
text.className = 'keys-row__text';
const name = document.createElement('span');
name.className = 'keys-row__title';
name.textContent = titleText;
const description = document.createElement('span');
description.className = 'keys-row__hint';
description.textContent = descriptionText;
wrap.append(row, description);
return wrap;
text.append(name, description);
toggle.className = 'switch';
row.append(text, toggle);
return row;
};
const rootToggle = document.createElement('input');
@@ -74,35 +71,23 @@ export function render({ navigate }) {
deviceToggle.checked = true;
deviceToggle.disabled = true;
const rootRow = createKeyInfo(
rootToggle,
'Ключ root',
'Главный ключ аккаунта. Нужен для смены пароля, восстановления доступа и важных основных настроек.',
);
const blockchainRow = createKeyInfo(
blockchainToggle,
'Ключ blockchain',
'Используется для подписи ваших действий и записей в блокчейне Сияния.',
);
const deviceRow = createKeyInfo(
deviceToggle,
'Client key (всегда)',
'Ключ этого устройства. Нужен для обычного входа, авторизации сессии и работы приложения на телефоне.',
const list = document.createElement('div');
list.className = 'keys-list';
list.append(
createKeyRow(rootToggle, 'Главный ключ', 'Смена пароля, восстановление доступа, важные настройки'),
createKeyRow(blockchainToggle, 'Ключ публикаций', 'Подписывает ваши записи и действия'),
createKeyRow(deviceToggle, 'Ключ устройства', 'Вход с этого устройства – нужен всегда'),
);
const simpleNote = document.createElement('p');
simpleNote.className = 'key-storage-note key-storage-note--strong';
simpleNote.textContent = 'Если вы не особо понимаете, о чём идёт речь, и не хотите особо заморачиваться с ключами, можете просто сохранить все ключи на телефоне.';
card.append(title, question, nextStep, rootRow, blockchainRow, deviceRow, simpleNote, status);
simpleNote.className = 'keys-note';
simpleNote.textContent = 'Не уверены – оставьте все включёнными.';
const actions = document.createElement('div');
actions.className = 'auth-footer-actions';
actions.className = 'keys-actions';
const cancelButton = document.createElement('button');
cancelButton.className = 'ghost-btn';
cancelButton.className = 'secondary-btn';
cancelButton.type = 'button';
cancelButton.textContent = 'Отмена';
cancelButton.addEventListener('click', async () => {
@@ -118,7 +103,7 @@ export function render({ navigate }) {
const okButton = document.createElement('button');
okButton.className = 'primary-btn';
okButton.type = 'button';
okButton.textContent = 'OK';
okButton.textContent = 'Готово';
okButton.addEventListener('click', async () => {
status.style.display = 'none';
try {
@@ -190,7 +175,7 @@ export function render({ navigate }) {
}
});
actions.append(cancelButton, okButton);
actions.append(okButton, cancelButton);
screen.append(
createTopBar({
@@ -208,7 +193,10 @@ export function render({ navigate }) {
},
},
}),
card,
lead,
list,
simpleNote,
status,
actions,
);
+21 -15
View File
@@ -1,4 +1,5 @@
import { createTopBar } from '../components/topbar.js';
import { iconHtml } from '../components/ui-icon.js';
import {
authService,
authorizeSession,
@@ -202,15 +203,27 @@ export function render({ navigate }) {
balanceValue.textContent = `${formatSol(parseBalanceSol(state.registrationPayment.balanceSOL), 6)} SOL`;
const refreshButton = document.createElement('button');
refreshButton.className = 'square-btn';
refreshButton.className = 'icon-btn payment-refresh-btn';
refreshButton.type = 'button';
refreshButton.textContent = '↻';
refreshButton.title = 'Обновить';
refreshButton.innerHTML = iconHtml('refresh');
refreshButton.title = 'Обновить баланс';
refreshButton.setAttribute('aria-label', 'Обновить баланс');
// Коротко и по-человечески; технические подробности — во всплывающей подсказке.
const showWalletError = (error, fallback) => {
status.className = 'status-line is-unavailable';
status.textContent = error?.code === 'NO_KEYS'
? 'Не хватает данных регистрации. Вернитесь назад и нажмите «Далее».'
: fallback;
status.title = error?.message || '';
status.style.display = '';
};
const refreshBalance = async ({ showError = true, addressOverride = '' } = {}) => {
const address = String(addressOverride || walletValue.value || '').trim();
if (!address) return null;
refreshButton.disabled = true;
refreshButton.classList.add('is-loading');
try {
const balance = await getBalanceSol({
endpoint: state.entrySettings.solanaServer,
@@ -220,20 +233,17 @@ export function render({ navigate }) {
balanceValue.textContent = `${formatSol(balance.sol, 6)} SOL`;
return Number(balance.sol) || 0;
} catch (error) {
if (showError) {
status.className = 'status-line is-unavailable';
status.textContent = `Не удалось обновить баланс: ${error?.message || 'unknown'}`;
status.style.display = '';
}
if (showError) showWalletError(error, 'Не удалось обновить баланс. Проверьте связь и попробуйте ещё раз.');
return null;
} finally {
refreshButton.disabled = false;
refreshButton.classList.remove('is-loading');
}
};
const deriveUserWalletAddress = async () => {
const keyBundle = state.registrationDraft.preGeneratedKeyBundle;
if (!keyBundle) throw new Error('Ключи ещё не сгенерированы. Вернитесь на предыдущий шаг.');
if (!keyBundle) throw Object.assign(new Error('Ключи ещё не сгенерированы'), { code: 'NO_KEYS' });
const { publicKeyB64 } = keyBundle.clientPair;
const raw = atob(publicKeyB64);
const bytes = new Uint8Array(raw.length);
@@ -261,9 +271,7 @@ export function render({ navigate }) {
await deriveUserWalletAddress();
navigate('topup-view');
} catch (error) {
status.className = 'status-line is-unavailable';
status.textContent = `Не удалось подготовить кошелёк: ${error?.message || 'unknown'}`;
status.style.display = '';
showWalletError(error, 'Не удалось подготовить кошелёк. Попробуйте ещё раз.');
}
});
@@ -386,9 +394,7 @@ export function render({ navigate }) {
const walletAddress = await deriveUserWalletAddress();
await refreshBalance({ addressOverride: walletAddress });
} catch (error) {
status.className = 'status-line is-unavailable';
status.textContent = `Не удалось подготовить client.key: ${error?.message || 'unknown'}`;
status.style.display = '';
showWalletError(error, 'Не удалось показать кошелёк. Попробуйте открыть экран ещё раз.');
}
})();
+15 -20
View File
@@ -34,26 +34,21 @@ export function render({navigate, chrome}) {
screen.className = 'stack';
let isDisposed = false;
chrome?.setTopbar(createTopBar({
title: 'Настройки',
back: { label: '←', onClick: () => navigate('profile-view') },
}));
const topbar = createTopBar({
title: 'Настройки',
back: { label: '←', onClick: () => navigate('profile-view') },
});
chrome?.setTopbar(topbar);
const logoButton = document.createElement('button');
logoButton.type = 'button';
logoButton.className = 'settings-shine-logo-button';
logoButton.setAttribute('aria-label', 'Логотип Сияния');
logoButton.title = 'SHiNE';
logoButton.innerHTML = '<img class="settings-shine-logo" src="/img/shine-logo-transparent-final_big.png" alt="SHiNE" />';
let logoTapCount = 0;
let lastLogoTapAt = 0;
logoButton.addEventListener('click', () => {
// Скрытый вход в «Дополнительные настройки»: пять быстрых нажатий на заголовок.
let titleTapCount = 0;
let lastTitleTapAt = 0;
topbar.querySelector('.topbar__title')?.addEventListener('click', () => {
const now = Date.now();
logoTapCount = now - lastLogoTapAt <= 900 ? logoTapCount + 1 : 1;
lastLogoTapAt = now;
if (logoTapCount < 5) return;
logoTapCount = 0;
titleTapCount = now - lastTitleTapAt <= 900 ? titleTapCount + 1 : 1;
lastTitleTapAt = now;
if (titleTapCount < 5) return;
titleTapCount = 0;
navigate('advanced-settings-view');
});
@@ -68,7 +63,7 @@ export function render({navigate, chrome}) {
<button type="button" class="tab-btn" role="radio" data-mode="light">День</button>
<button type="button" class="tab-btn" role="radio" data-mode="dark">Ночь</button>
</div>
<span class="meta-muted">«Авто» — как на устройстве.</span>
<span class="meta-muted">«Авто» – как на устройстве.</span>
<button type="button" class="secondary-btn settings-theme-editor" id="settings-theme-editor">Настроить цвета</button>
</div>
<div class="nav-list">
@@ -137,7 +132,7 @@ export function render({navigate, chrome}) {
}
});
screen.append(logoButton, card);
screen.append(card);
if (isDeveloperToolsEnabled()) {
const versionCard = document.createElement('div');
+3 -13
View File
@@ -1,4 +1,5 @@
import { createTopBar } from '../components/topbar.js';
import { iconHtml } from '../components/ui-icon.js';
import { state } from '../state.js';
import { bytesToBase58 } from '../services/crypto-utils.js';
import { extractSeed32FromPkcs8B64 } from '../services/client-key-utils.js';
@@ -37,19 +38,8 @@ export function render({navigate, chrome}) {
const renderField = (id, label, hint = '') => {
const row = document.createElement('div');
row.className = 'key-card stack';
const eyeIcon = `
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M2.4 12s3.6-6.5 9.6-6.5S21.6 12 21.6 12s-3.6 6.5-9.6 6.5S2.4 12 2.4 12Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
<circle cx="12" cy="12" r="2.9" fill="none" stroke="currentColor" stroke-width="1.8"/>
</svg>
`;
const eyeOffIcon = `
<svg class="key-toggle-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<path d="M3 4l18 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
<path d="M2.4 12s3.6-6.5 9.6-6.5c2.4 0 4.5.8 6.1 1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
<path d="M21.6 12s-3.6 6.5-9.6 6.5c-2.4 0-4.5-.8-6.1-1.9" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>
</svg>
`;
const eyeIcon = iconHtml('eye', false, 'key-toggle-icon');
const eyeOffIcon = iconHtml('eyeOff', false, 'key-toggle-icon');
row.innerHTML = `
<div class="row">
<span class="field-label">${label}${hint ? `<small class="key-card__hint">${hint}</small>` : ''}</span>
+3 -3
View File
@@ -36,7 +36,7 @@ function classifyResult(result) {
function shortenText(value, max = 140) {
const text = String(value || '').trim();
if (!text) return '—';
if (!text) return '–';
return text.length > max ? `${text.slice(0, max)}...` : text;
}
@@ -124,7 +124,7 @@ function makeResultCard(endpoint) {
const details = document.createElement('div');
details.className = 'meta-muted solana-rpc-details';
details.textContent = '—';
details.textContent = '–';
meta.append(statusLine, details);
card.append(head, endpointLine, meta);
@@ -185,7 +185,7 @@ export function render({navigate, chrome}) {
ui.badge.className = 'badge alt solana-rpc-badge';
ui.badge.textContent = 'Ожидает проверки';
ui.statusLine.textContent = 'Ещё не проверяли.';
ui.details.textContent = '—';
ui.details.textContent = '–';
});
};
+3 -3
View File
@@ -59,11 +59,11 @@ export function render({navigate, chrome}) {
const economyPdaLine = document.createElement('p');
economyPdaLine.className = 'meta-muted';
economyPdaLine.textContent = 'PDA economy config: —';
economyPdaLine.textContent = 'PDA economy config: –';
const txLine = document.createElement('p');
txLine.className = 'meta-muted';
txLine.textContent = 'TX: —';
txLine.textContent = 'TX: –';
const connectBtn = document.createElement('button');
connectBtn.className = 'text-btn';
@@ -111,7 +111,7 @@ export function render({navigate, chrome}) {
if (!provider || !walletPubkey || !economyPda) return;
initBtn.disabled = true;
status.textContent = 'Отправка транзакции...';
txLine.textContent = 'TX: —';
txLine.textContent = 'TX: –';
try {
const solana = await loadSolanaLib();
const connection = new solana.Connection(String(state.entrySettings.solanaServer || ''), 'confirmed');
+6 -1
View File
@@ -1,4 +1,5 @@
import { clearStartHint } from '../state.js';
import { createShineWordmark } from '../components/shine-wordmark.js';
export const pageMeta = { id: 'start-view', title: 'Старт', showAppChrome: false };
@@ -10,6 +11,10 @@ export function render({ navigate }) {
const logoWrap = document.createElement('div');
logoWrap.className = 'auth-logo-wrap';
// Сияние каждый раз начинается с новой фазы (периоды — как в preauth.css).
[83, 7.3, 127, 11.9].forEach((period, i) => {
logoWrap.style.setProperty(`--halo-phase-${i + 1}`, `${(-Math.random() * period).toFixed(2)}s`);
});
const logo = document.createElement('img');
logo.className = 'auth-logo';
@@ -19,7 +24,7 @@ export function render({ navigate }) {
const title = document.createElement('h1');
title.className = 'auth-brand';
title.textContent = 'Сияние';
title.append(createShineWordmark());
const actions = document.createElement('div');
actions.className = 'auth-actions shine-actions';
+57 -57
View File
@@ -1078,8 +1078,8 @@ export function render({navigate, chrome}) {
const currentCoef = formatPpmCoefText(currentCore.coef.coefPpm);
const usdRaw = String(amountInput.value || '').trim().replace(',', '.');
let amountUsdCents = 0n;
let amountSol = '—';
let maxPaySol = '—';
let amountSol = '–';
let maxPaySol = '–';
let canBuy = true;
try {
const asNumber = Number(usdRaw);
@@ -1324,26 +1324,26 @@ export function render({navigate, chrome}) {
limitLabel.textContent = 'Лимит блокчейна';
const limitValue = document.createElement('h2');
limitValue.style.fontSize = '26px';
limitValue.textContent = '— KB';
limitValue.textContent = '– KB';
const usedLabel = document.createElement('p');
usedLabel.className = 'meta-muted';
usedLabel.textContent = 'Израсходовано (фактически на сервере)';
const usedValue = document.createElement('h2');
usedValue.style.fontSize = '26px';
usedValue.textContent = '— KB';
usedValue.textContent = '– KB';
const leftLabel = document.createElement('p');
leftLabel.className = 'meta-muted';
leftLabel.textContent = 'Осталось';
const leftValue = document.createElement('h2');
leftValue.style.fontSize = '30px';
leftValue.textContent = '— KB';
leftValue.textContent = '– KB';
const pdaLabel = document.createElement('p');
pdaLabel.className = 'meta-muted';
pdaLabel.style.wordBreak = 'break-all';
pdaLabel.textContent = 'PDA: —';
pdaLabel.textContent = 'PDA: –';
const endpointLabel = document.createElement('p');
endpointLabel.className = 'meta-muted';
@@ -1351,22 +1351,22 @@ export function render({navigate, chrome}) {
const updatedLabel = document.createElement('p');
updatedLabel.className = 'meta-muted';
updatedLabel.textContent = 'Обновлено: —';
updatedLabel.textContent = 'Обновлено: –';
const serverTitle = document.createElement('h3');
serverTitle.style.margin = '14px 0 0';
serverTitle.textContent = 'Фактическое состояние на сервере';
const serverSizeLabel = document.createElement('p');
serverSizeLabel.className = 'meta-muted';
serverSizeLabel.textContent = 'Размер цепочки: —';
serverSizeLabel.textContent = 'Размер цепочки: –';
const serverLastLabel = document.createElement('p');
serverLastLabel.className = 'meta-muted';
serverLastLabel.textContent = 'Крайний блок: —';
serverLastLabel.textContent = 'Крайний блок: –';
const serverLastHashLabel = document.createElement('p');
serverLastHashLabel.className = 'meta-muted';
serverLastHashLabel.style.wordBreak = 'break-all';
serverLastHashLabel.style.fontSize = '11px';
serverLastHashLabel.textContent = 'Hash: —';
serverLastHashLabel.textContent = 'Hash: –';
card.append(
limitLabel,
@@ -1420,7 +1420,7 @@ export function render({navigate, chrome}) {
serverSizeLabel.textContent = `Размер цепочки: ${formatKbFromBytes(serverState.sizeBytes)}`;
serverLastLabel.textContent = `Крайний блок: ${serverState.lastNumber}`;
serverLastHashLabel.textContent = `Hash: ${serverState.lastHash || '—'}`;
serverLastHashLabel.textContent = `Hash: ${serverState.lastHash || '–'}`;
setStatus('Данные лимита и состояния блокчейна обновлены.');
} catch (error) {
@@ -1503,8 +1503,8 @@ export function render({navigate, chrome}) {
publicationStatus.className = 'card stack';
publicationStatus.innerHTML = `
<h3 style="margin:0;">Статус публикации</h3>
<p class="meta-muted" id="publish-status-main">—</p>
<p class="meta-muted" id="publish-status-local">—</p>
<p class="meta-muted" id="publish-status-main">–</p>
<p class="meta-muted" id="publish-status-local">–</p>
`;
const publicationMainEl = publicationStatus.querySelector('#publish-status-main');
const publicationLocalEl = publicationStatus.querySelector('#publish-status-local');
@@ -1513,13 +1513,13 @@ export function render({navigate, chrome}) {
pdaCard.className = 'card stack';
pdaCard.innerHTML = `
<h3 style="margin:0;">Что закреплено в PDA</h3>
<p class="meta-muted" id="pda-name">Блокчейн: —</p>
<p class="meta-muted" id="pda-address" style="word-break:break-all;">PDA: —</p>
<p class="meta-muted" id="pda-last">Крайний блок: —</p>
<p class="meta-muted" id="pda-hash" style="word-break:break-all; font-size:11px;">Hash: —</p>
<p class="meta-muted" id="pda-used">Размер: —</p>
<p class="meta-muted" id="pda-limit">Лимит: —</p>
<p class="meta-muted" id="pda-arweave" style="word-break:break-all;">Arweave tx: —</p>
<p class="meta-muted" id="pda-name">Блокчейн: –</p>
<p class="meta-muted" id="pda-address" style="word-break:break-all;">PDA: –</p>
<p class="meta-muted" id="pda-last">Крайний блок: –</p>
<p class="meta-muted" id="pda-hash" style="word-break:break-all; font-size:11px;">Hash: –</p>
<p class="meta-muted" id="pda-used">Размер: –</p>
<p class="meta-muted" id="pda-limit">Лимит: –</p>
<p class="meta-muted" id="pda-arweave" style="word-break:break-all;">Arweave tx: –</p>
<a class="text-btn" id="pda-arweave-link" href="#" target="_blank" rel="noreferrer noopener" style="pointer-events:none; opacity:.55; padding:0;">Открыть Arweave</a>
`;
@@ -1527,25 +1527,25 @@ export function render({navigate, chrome}) {
serverCard.className = 'card stack';
serverCard.innerHTML = `
<h3 style="margin:0;">Что реально на сервере</h3>
<p class="meta-muted" id="server-name">Блокчейн: —</p>
<p class="meta-muted" id="server-last">Крайний блок: —</p>
<p class="meta-muted" id="server-hash" style="word-break:break-all; font-size:11px;">Hash: —</p>
<p class="meta-muted" id="server-size">Размер: —</p>
<p class="meta-muted" id="server-updated">Обновлено: —</p>
<p class="meta-muted" id="server-name">Блокчейн: –</p>
<p class="meta-muted" id="server-last">Крайний блок: –</p>
<p class="meta-muted" id="server-hash" style="word-break:break-all; font-size:11px;">Hash: –</p>
<p class="meta-muted" id="server-size">Размер: –</p>
<p class="meta-muted" id="server-updated">Обновлено: –</p>
`;
const localCard = document.createElement('div');
localCard.className = 'card stack';
localCard.innerHTML = `
<h3 style="margin:0;">Локальный слепок в этом браузере</h3>
<p class="meta-muted" id="local-state">Слепок: —</p>
<p class="meta-muted" id="local-transport">Способ: —</p>
<p class="meta-muted" id="local-last">Крайний блок: —</p>
<p class="meta-muted" id="local-hash" style="word-break:break-all; font-size:11px;">Hash: —</p>
<p class="meta-muted" id="local-size">Размер: —</p>
<p class="meta-muted" id="local-arweave" style="word-break:break-all;">Arweave tx: —</p>
<p class="meta-muted" id="local-created">Создан: —</p>
<p class="meta-muted" id="local-solana">Solana: —</p>
<p class="meta-muted" id="local-state">Слепок: –</p>
<p class="meta-muted" id="local-transport">Способ: –</p>
<p class="meta-muted" id="local-last">Крайний блок: –</p>
<p class="meta-muted" id="local-hash" style="word-break:break-all; font-size:11px;">Hash: –</p>
<p class="meta-muted" id="local-size">Размер: –</p>
<p class="meta-muted" id="local-arweave" style="word-break:break-all;">Arweave tx: –</p>
<p class="meta-muted" id="local-created">Создан: –</p>
<p class="meta-muted" id="local-solana">Solana: –</p>
`;
const actions = document.createElement('div');
@@ -1631,13 +1631,13 @@ export function render({navigate, chrome}) {
}
publicationLocalEl.textContent = localStatusText;
pdaNameEl.textContent = `Блокчейн: ${usage.blockchainName || '—'}`;
pdaAddressEl.textContent = `PDA: ${usage.userPda || '—'}`;
pdaNameEl.textContent = `Блокчейн: ${usage.blockchainName || '–'}`;
pdaAddressEl.textContent = `PDA: ${usage.userPda || '–'}`;
pdaLastEl.textContent = `Крайний блок: ${usage.lastBlockNumber}`;
pdaHashEl.textContent = `Hash: ${usage.lastBlockHashHex || '—'}`;
pdaHashEl.textContent = `Hash: ${usage.lastBlockHashHex || '–'}`;
pdaUsedEl.textContent = `Размер: ${formatBytesRu(usage.usedBytes)} байт`;
pdaLimitEl.textContent = `Лимит: ${formatBytesRu(usage.paidLimitBytes)} байт`;
pdaArweaveEl.textContent = `Arweave tx: ${usage.arweaveTxId || '—'}`;
pdaArweaveEl.textContent = `Arweave tx: ${usage.arweaveTxId || '–'}`;
if (usage.arweaveTxId) {
pdaArweaveLinkEl.href = buildArweaveDataUrl({ gateway: state.entrySettings.arweaveServer, txId: usage.arweaveTxId });
pdaArweaveLinkEl.style.pointerEvents = 'auto';
@@ -1648,32 +1648,32 @@ export function render({navigate, chrome}) {
pdaArweaveLinkEl.style.opacity = '.55';
}
serverNameEl.textContent = `Блокчейн: ${serverState.blockchainName || usage.blockchainName || '—'}`;
serverNameEl.textContent = `Блокчейн: ${serverState.blockchainName || usage.blockchainName || '–'}`;
serverLastEl.textContent = `Крайний блок: ${serverState.lastNumber}`;
serverHashEl.textContent = `Hash: ${serverState.lastHash || '—'}`;
serverHashEl.textContent = `Hash: ${serverState.lastHash || '–'}`;
serverSizeEl.textContent = `Размер: ${formatBytesRu(serverState.sizeBytes)} байт`;
serverUpdatedEl.textContent = `Обновлено: ${nowRu()}`;
if (localSnapshot?.txId) {
localStateEl.textContent = `Слепок: ${String(localSnapshot.txId || '') === String(usage.arweaveTxId || '') ? 'закреплён' : 'есть, но не закреплён в Solana'}`;
localTransportEl.textContent = `Способ: ${localSnapshot.uploadTransport === 'turbo' ? 'Turbo' : (localSnapshot.uploadTransport === 'arweave' ? 'Arweave' : '—')}`;
localLastEl.textContent = `Крайний блок: ${localSnapshot.lastBlockNumber ?? '—'}`;
localHashEl.textContent = `Hash: ${localSnapshot.lastBlockHash || '—'}`;
localTransportEl.textContent = `Способ: ${localSnapshot.uploadTransport === 'turbo' ? 'Turbo' : (localSnapshot.uploadTransport === 'arweave' ? 'Arweave' : '–')}`;
localLastEl.textContent = `Крайний блок: ${localSnapshot.lastBlockNumber ?? '–'}`;
localHashEl.textContent = `Hash: ${localSnapshot.lastBlockHash || '–'}`;
localSizeEl.textContent = `Размер: ${formatBytesRu(localSnapshot.usedBytes || 0)} байт`;
localArweaveEl.textContent = `Arweave tx: ${localSnapshot.txId}`;
localCreatedEl.textContent = `Создан: ${localSnapshot.uploadedAtMs ? new Date(localSnapshot.uploadedAtMs).toLocaleString('ru-RU') : '—'}`;
localCreatedEl.textContent = `Создан: ${localSnapshot.uploadedAtMs ? new Date(localSnapshot.uploadedAtMs).toLocaleString('ru-RU') : '–'}`;
localSolanaEl.textContent = localSnapshot.solanaUpdatedAtMs
? `Solana обновлена: ${new Date(localSnapshot.solanaUpdatedAtMs).toLocaleString('ru-RU')}`
: 'Solana: слепок ещё не закреплён';
} else {
localStateEl.textContent = 'Слепок: отсутствует';
localTransportEl.textContent = 'Способ: —';
localLastEl.textContent = 'Крайний блок: —';
localHashEl.textContent = 'Hash: —';
localSizeEl.textContent = 'Размер: —';
localArweaveEl.textContent = 'Arweave tx: —';
localCreatedEl.textContent = 'Создан: —';
localSolanaEl.textContent = 'Solana: —';
localTransportEl.textContent = 'Способ: –';
localLastEl.textContent = 'Крайний блок: –';
localHashEl.textContent = 'Hash: –';
localSizeEl.textContent = 'Размер: –';
localArweaveEl.textContent = 'Arweave tx: –';
localCreatedEl.textContent = 'Создан: –';
localSolanaEl.textContent = 'Solana: –';
}
publishBtn.disabled = !localSnapshot?.txId || !localMatchesServer || String(localSnapshot.txId || '') === String(usage.arweaveTxId || '');
@@ -1854,10 +1854,10 @@ export function render({navigate, chrome}) {
balanceLabel.textContent = 'Баланс (Solana)';
const balanceValue = document.createElement('h2');
balanceValue.style.fontSize = '30px';
balanceValue.textContent = '— SOL';
balanceValue.textContent = '– SOL';
const updatedLabel = document.createElement('p');
updatedLabel.className = 'meta-muted';
updatedLabel.textContent = 'Обновлено: —';
updatedLabel.textContent = 'Обновлено: –';
const endpointLabel = document.createElement('p');
endpointLabel.className = 'meta-muted';
endpointLabel.textContent = `RPC: ${state.entrySettings.solanaServer}`;
@@ -1868,7 +1868,7 @@ export function render({navigate, chrome}) {
addressCard.style.padding = '10px';
addressCard.innerHTML = `
<p class="meta-muted" style="margin-bottom:6px;">Публичный адрес (client.key)</p>
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">—</p>
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">–</p>
`;
const addressEl = addressCard.querySelector('#wallet-address-value');
@@ -2000,10 +2000,10 @@ export function render({navigate, chrome}) {
balanceLabel.textContent = 'Баланс (Arweave)';
const balanceValue = document.createElement('h2');
balanceValue.style.fontSize = '30px';
balanceValue.textContent = '— AR';
balanceValue.textContent = '– AR';
const updatedLabel = document.createElement('p');
updatedLabel.className = 'meta-muted';
updatedLabel.textContent = 'Обновлено: —';
updatedLabel.textContent = 'Обновлено: –';
const gatewayLabel = document.createElement('p');
gatewayLabel.className = 'meta-muted';
gatewayLabel.textContent = `Gateway: ${state.entrySettings.arweaveServer}`;
@@ -2014,7 +2014,7 @@ export function render({navigate, chrome}) {
addressCard.style.padding = '10px';
addressCard.innerHTML = `
<p class="meta-muted" style="margin-bottom:6px;">Публичный адрес Arweave (SAWD-v1)</p>
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">—</p>
<p style="font-size:13px; line-height:1.4; word-break:break-all;" id="wallet-address-value">–</p>
`;
const addressEl = addressCard.querySelector('#wallet-address-value');
@@ -2133,7 +2133,7 @@ export function render({navigate, chrome}) {
if (!text) return;
if (text.includes('впервые получаем Arweave-кошелёк')) {
wasFirstTimeGeneration = true;
setStatus('Подождите — ваш Arweave-ключ вычисляется из client key. Это происходит только один раз, потом будет мгновенно.');
setStatus('Подождите – ваш Arweave-ключ вычисляется из client key. Это происходит только один раз, потом будет мгновенно.');
return;
}
setStatus(text);