SHA256
Обновить кошельки и мелкие детали UI
This commit is contained in:
@@ -108,6 +108,7 @@ import * as clientSessionView from './pages/device-session-view.js?v=20260613143
|
||||
import * as languageView from './pages/language-view.js';
|
||||
import * as appearanceView from './pages/appearance-view.js';
|
||||
import * as notificationSettingsView from './pages/notification-settings-view.js';
|
||||
import * as applicationSettingsView from './pages/application-settings-view.js';
|
||||
import * as appLogView from './pages/app-log-view.js';
|
||||
import * as pwaDiagnosticsView from './pages/pwa-diagnostics-view.js';
|
||||
import * as solanaUsersInitView from './pages/solana-users-init-view.js';
|
||||
@@ -192,6 +193,7 @@ const routes = {
|
||||
'language-view': languageView,
|
||||
'appearance-view': appearanceView,
|
||||
'notification-settings-view': notificationSettingsView,
|
||||
'application-settings-view': applicationSettingsView,
|
||||
'app-log-view': appLogView,
|
||||
'pwa-diagnostics-view': pwaDiagnosticsView,
|
||||
'solana-users-init-view': solanaUsersInitView,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
import { confirmDialog } from './confirm-dialog.js';
|
||||
import { confirmPublicHistoryAction } from '../services/public-history-consent.js';
|
||||
import { markArweaveAttachmentPlaced } from './arweave-attachment-manager.js';
|
||||
import { openChannelAttachmentManager } from './channel-attachment-manager.js';
|
||||
import { composeMessageWithAttachments, MAX_MESSAGE_ATTACHMENTS } from '../services/attachment-format.js';
|
||||
@@ -340,7 +340,7 @@ export function openChannelEditor({
|
||||
submitButton.textContent = 'Отправляем…';
|
||||
sync();
|
||||
try {
|
||||
const accepted = await confirmDialog({
|
||||
const accepted = await confirmPublicHistoryAction({
|
||||
title: 'Записать в публичную историю?',
|
||||
aboveEditor: true,
|
||||
text: 'Эта публикация, ответ или изменение будут записаны в блокчейн. Запись может сохраняться постоянно, включая историю правок и удаления. Если передумали, выберите «Вернуться к черновику».',
|
||||
|
||||
@@ -6,6 +6,7 @@ export function confirmDialog({
|
||||
cancelLabel = 'Отмена',
|
||||
danger = false,
|
||||
aboveEditor = false,
|
||||
rememberChoice = null,
|
||||
} = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const opener = document.activeElement;
|
||||
@@ -25,6 +26,17 @@ export function confirmDialog({
|
||||
const textEl = modal.querySelector('.confirm-dialog__text');
|
||||
textEl.textContent = text;
|
||||
textEl.hidden = !text;
|
||||
let rememberCheckbox = null;
|
||||
if (rememberChoice?.label) {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'confirm-dialog__remember';
|
||||
rememberCheckbox = document.createElement('input');
|
||||
rememberCheckbox.type = 'checkbox';
|
||||
const explanation = document.createElement('span');
|
||||
explanation.textContent = rememberChoice.label;
|
||||
label.append(rememberCheckbox, explanation);
|
||||
modal.querySelector('.form-actions-grid').before(label);
|
||||
}
|
||||
modal.querySelector('[data-answer="no"]').textContent = cancelLabel;
|
||||
modal.querySelector('[data-answer="yes"]').textContent = confirmLabel;
|
||||
|
||||
@@ -32,6 +44,7 @@ export function confirmDialog({
|
||||
document.removeEventListener('keydown', onKeydown, true);
|
||||
modal.remove();
|
||||
opener?.focus?.();
|
||||
if (answer && rememberCheckbox?.checked) rememberChoice?.onConfirm?.();
|
||||
resolve(answer);
|
||||
};
|
||||
const onKeydown = (event) => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getShowPublicHistoryWarning, setShowPublicHistoryWarning, PUBLIC_HISTORY_REMEMBER_LABEL } from '../services/public-history-consent.js';
|
||||
import { openSheet } from './sheet.js';
|
||||
|
||||
function safeCount(raw, maximum = Infinity) {
|
||||
@@ -6,7 +7,17 @@ function safeCount(raw, maximum = Infinity) {
|
||||
}
|
||||
|
||||
// Значения счётчиков получены от сервера, это не криптографическая аттестация личности.
|
||||
export function confirmLikeAction({ liked = false, counts = {}, onViewList = null } = {}) {
|
||||
export function confirmLikeAction(options = {}) {
|
||||
if (!getShowPublicHistoryWarning()) return Promise.resolve(true);
|
||||
return openLikeSheet(options);
|
||||
}
|
||||
|
||||
// Просмотр счётчиков не является действием в блокчейне и не спрашивает согласие.
|
||||
export function showLikeStatistics({ counts = {}, onViewList = null } = {}) {
|
||||
return openLikeSheet({ counts, onViewList, readOnly: true });
|
||||
}
|
||||
|
||||
function openLikeSheet({ liked = false, counts = {}, onViewList = null, readOnly = false } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let accepted = false;
|
||||
const all = safeCount(counts.all ?? counts.likesCount);
|
||||
@@ -43,20 +54,30 @@ export function confirmLikeAction({ liked = false, counts = {}, onViewList = nul
|
||||
const warning = document.createElement('p');
|
||||
warning.className = 'meta-muted';
|
||||
warning.textContent = 'Добавление и отмена лайка создают записи в публичной истории блокчейна. Даже отменённый лайк может остаться в истории.';
|
||||
const rememberLabel = document.createElement('label');
|
||||
rememberLabel.className = 'confirm-dialog__remember';
|
||||
const remember = document.createElement('input');
|
||||
remember.type = 'checkbox';
|
||||
const rememberText = document.createElement('span');
|
||||
rememberText.textContent = PUBLIC_HISTORY_REMEMBER_LABEL;
|
||||
rememberLabel.append(remember, rememberText);
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'form-actions-grid';
|
||||
const cancel = document.createElement('button');
|
||||
cancel.type = 'button';
|
||||
cancel.className = 'secondary-btn';
|
||||
cancel.textContent = 'Не менять';
|
||||
cancel.textContent = readOnly ? 'Закрыть' : 'Не менять';
|
||||
const confirm = document.createElement('button');
|
||||
confirm.type = 'button';
|
||||
confirm.className = 'primary-btn';
|
||||
confirm.textContent = liked ? 'Убрать мой лайк' : 'Добавить мой лайк';
|
||||
actions.append(cancel, confirm);
|
||||
body.append(intro, grid, warning, actions);
|
||||
if (readOnly) actions.append(cancel);
|
||||
else actions.append(cancel, confirm);
|
||||
body.append(intro, grid);
|
||||
if (!readOnly) body.append(warning, rememberLabel);
|
||||
body.append(actions);
|
||||
const sheet = openSheet({ title: 'Лайки', className: 'like-consent-sheet', content: body, onClose: () => resolve(accepted) });
|
||||
cancel.addEventListener('click', () => sheet.close());
|
||||
confirm.addEventListener('click', () => { accepted = true; sheet.close(); });
|
||||
confirm.addEventListener('click', () => { if (remember.checked) setShowPublicHistoryWarning(false); accepted = true; sheet.close(); });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { iconHtml } from './ui-icon.js';
|
||||
|
||||
/** The password is intentionally visible initially on both auth screens. */
|
||||
export function createVisiblePasswordField(input) {
|
||||
input.type = 'text';
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'auth-password-field';
|
||||
const toggle = document.createElement('button');
|
||||
toggle.type = 'button';
|
||||
toggle.className = 'auth-password-field__toggle';
|
||||
function updateToggle() {
|
||||
const visible = input.type !== 'password';
|
||||
toggle.innerHTML = iconHtml(visible ? 'eyeOff' : 'eye', false, 'key-toggle-icon');
|
||||
toggle.setAttribute('aria-label', visible ? 'Скрыть пароль' : 'Показать пароль');
|
||||
toggle.setAttribute('title', visible ? 'Скрыть пароль' : 'Показать пароль');
|
||||
toggle.setAttribute('aria-pressed', String(!visible));
|
||||
}
|
||||
toggle.addEventListener('click', () => {
|
||||
const start = input.selectionStart;
|
||||
const end = input.selectionEnd;
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
updateToggle();
|
||||
input.focus();
|
||||
try { if (start !== null && end !== null) input.setSelectionRange(start, end); } catch { /* unsupported input method */ }
|
||||
});
|
||||
updateToggle();
|
||||
wrap.append(input, toggle);
|
||||
return wrap;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { getShowPublicHistoryWarning, setShowPublicHistoryWarning } from '../services/public-history-consent.js';
|
||||
|
||||
export const pageMeta = { id: 'application-settings-view', title: 'Настройки приложения' };
|
||||
|
||||
export function render({ navigate, chrome }) {
|
||||
const screen = document.createElement('section');
|
||||
screen.className = 'stack';
|
||||
chrome?.setTopbar(createTopBar({
|
||||
title: 'Настройки приложения',
|
||||
back: { label: '←', onClick: () => navigate('settings-view') },
|
||||
}));
|
||||
const section = document.createElement('div');
|
||||
section.className = 'nav-list';
|
||||
const row = document.createElement('label');
|
||||
row.className = 'nav-row nav-row--switch';
|
||||
row.innerHTML = `
|
||||
<span class="nav-row__text">
|
||||
<span class="nav-row__label">Показывать предупреждение о публичных записях</span>
|
||||
<span class="nav-row__hint">Сообщения, лайки и другие публичные действия могут сохраняться в блокчейне навсегда. Настройка действует для этого аккаунта на этом устройстве.</span>
|
||||
</span>
|
||||
<input class="switch" type="checkbox" />
|
||||
`;
|
||||
const input = row.querySelector('input');
|
||||
input.checked = getShowPublicHistoryWarning();
|
||||
input.addEventListener('change', () => setShowPublicHistoryWarning(input.checked));
|
||||
section.append(row);
|
||||
screen.append(section);
|
||||
return screen;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { confirmLikeAction } from '../components/like-action-sheet.js';
|
||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { consumeReplyEditorOnOpen, rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
import { attachMessageMenu } from '../components/message-menu.js';
|
||||
@@ -839,7 +839,6 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
likeButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('heart', isLiked)}</span>
|
||||
<span class="channel-action-label">${isPending ? 'Лайк...' : 'Лайк'}</span>
|
||||
<span class="channel-action-counter">${Number(likes) > 0 ? likes : ''}</span>
|
||||
`;
|
||||
likeButton.setAttribute('aria-pressed', String(isLiked));
|
||||
setActionTitle(likeButton, isPending ? 'Лайк…' : `${isLiked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${likes}`);
|
||||
@@ -864,6 +863,16 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
}
|
||||
});
|
||||
|
||||
const likesStatsButton = document.createElement('button');
|
||||
likesStatsButton.type = 'button';
|
||||
likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats';
|
||||
likesStatsButton.textContent = String(Number(likes) || '');
|
||||
likesStatsButton.setAttribute('aria-label', `Посмотреть статистику лайков: ${likes}`);
|
||||
likesStatsButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
void showLikeStatistics({ counts: node });
|
||||
});
|
||||
|
||||
const replyButton = document.createElement('button');
|
||||
replyButton.type = 'button';
|
||||
replyButton.className = 'ui-button channel-action-item thread-reply-btn';
|
||||
@@ -941,8 +950,8 @@ function renderNodeCard(node, heading, handlers, localNumber, { focusPost = fals
|
||||
if (!REPOSTS_ENABLED) { notifyRepostSoon(); return; }
|
||||
void handlers.onRepost?.(target);
|
||||
});
|
||||
if (threadsLayout) actions.append(likeButton, discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, shareButton, discussionButton);
|
||||
if (threadsLayout) actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, ...(likes > 0 ? [likesStatsButton] : []), shareButton, discussionButton);
|
||||
menuItems.unshift({ label: 'Ответить', iconHtml: iconHtml('reply'), action: () => replyButton.click() });
|
||||
// Те же действия, что у ответов в обсуждении.
|
||||
menuItems.splice(1, 0, { label: 'Скопировать текст', iconHtml: iconHtml('copy'), action: async () => {
|
||||
@@ -1171,7 +1180,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
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.innerHTML = `${iconHtml('heart', liked)}`;
|
||||
like.setAttribute('aria-pressed', String(liked));
|
||||
like.setAttribute('aria-label', `${liked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${likes}`);
|
||||
like.addEventListener('click', async () => {
|
||||
@@ -1181,6 +1190,13 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
finally { if (like.isConnected) like.disabled = false; }
|
||||
});
|
||||
|
||||
const commentLikeStats = document.createElement('button');
|
||||
commentLikeStats.type = 'button';
|
||||
commentLikeStats.className = 'channel-action-item thread-comment__like-count';
|
||||
commentLikeStats.textContent = String(likes || '');
|
||||
commentLikeStats.setAttribute('aria-label', `Статистика лайков: ${likes}`);
|
||||
commentLikeStats.addEventListener('click', () => { void showLikeStatistics({ counts: node }); });
|
||||
|
||||
const replies = replyCountOf(node);
|
||||
const reply = document.createElement('button');
|
||||
reply.type = 'button';
|
||||
@@ -1238,7 +1254,7 @@ function renderComment({ node, parent, focus, channelOwner, handlers, nested = f
|
||||
repost.addEventListener('click', () => (REPOSTS_ENABLED ? handlers.onRepost?.(target) : notifyRepostSoon()));
|
||||
|
||||
// Ряд действий как у записи канала: лайк, ответы, репост, поделиться.
|
||||
actions.append(like, reply, repost, share);
|
||||
actions.append(like, ...(likes > 0 ? [commentLikeStats] : []), reply, repost, share);
|
||||
main.append(actions);
|
||||
item.append(who, main);
|
||||
// Как в Threads: нажатие на ответ открывает его обсуждение (кнопки, ссылки и вложения работают сами по себе).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { appendShineMessageLinks } from '../services/shine-message-links.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { confirmLikeAction } from '../components/like-action-sheet.js';
|
||||
import { confirmLikeAction, showLikeStatistics } from '../components/like-action-sheet.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||||
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
|
||||
@@ -2014,7 +2014,6 @@ function renderPostCard(post, {
|
||||
likeButton.innerHTML = `
|
||||
<span class="channel-action-icon" aria-hidden="true">${iconHtml('heart', isLiked)}</span>
|
||||
<span class="channel-action-label">${isPending ? 'Лайк...' : 'Лайк'}</span>
|
||||
<span class="channel-action-counter">${post.likesCount || ''}</span>
|
||||
`;
|
||||
likeButton.setAttribute('aria-pressed', String(isLiked));
|
||||
setActionTitle(likeButton, isPending ? 'Лайк…' : `${isLiked ? 'Убрать отметку «Нравится»' : 'Нравится'}, ${post.likesCount || 0}`);
|
||||
@@ -2033,6 +2032,19 @@ function renderPostCard(post, {
|
||||
}
|
||||
});
|
||||
|
||||
const likesStatsButton = document.createElement('button');
|
||||
likesStatsButton.type = 'button';
|
||||
likesStatsButton.className = 'ui-button channel-action-item channel-action-like-stats';
|
||||
likesStatsButton.textContent = String(Number(post.likesCount) || '');
|
||||
likesStatsButton.setAttribute('aria-label', `Посмотреть статистику и список лайков: ${Number(post.likesCount) || 0}`);
|
||||
likesStatsButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
void showLikeStatistics({
|
||||
counts: post,
|
||||
onViewList: (tab) => openMessageLikesListModal({ navigate, messageRef: post.messageRef, initialTab: tab }),
|
||||
});
|
||||
});
|
||||
|
||||
// Сервер считает только прямые ответы; полное число по всем уровням берём из обсуждения (кэш или подгрузка).
|
||||
if (Number(post.repliesCount || 0) > 0) {
|
||||
const threadRoute = buildThreadRoute(post, selector);
|
||||
@@ -2140,8 +2152,8 @@ function renderPostCard(post, {
|
||||
void onRepost?.(post.messageRef);
|
||||
});
|
||||
// Четыре кнопки как в Threads: лайк, ответы, репост, поделиться.
|
||||
if (threadsLayout) actions.append(likeButton, discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, shareButton, discussionButton);
|
||||
if (threadsLayout) actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), discussionButton, repostButton, shareButton);
|
||||
else actions.append(likeButton, ...(Number(post.likesCount) > 0 ? [likesStatsButton] : []), shareButton, discussionButton);
|
||||
if (selector?.publicOrdinalUrlsAllowed && post.messageRef?.blockNumber != null) {
|
||||
const streamRoute = makeShineChannelStreamRoute({
|
||||
ownerBlockchainName: selector?.ownerBlockchainName,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { bytesToBase64 } from '../services/crypto-utils.js';
|
||||
import { readShineUserPda } from '../services/shine-user-pda-service.js';
|
||||
@@ -50,7 +51,7 @@ export function render({navigate,chrome}){
|
||||
more.addEventListener('click',()=>void load());
|
||||
const start=document.createElement('button');start.className='primary-btn';start.type='button';start.textContent='Начать смену ключей';
|
||||
const error=document.createElement('div');error.className='meta-muted';
|
||||
start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error('Выберите последний доверенный блок');if(!oldP.el.value||!newP.el.value)throw new Error('Введите текущий и новый пароль');if(newP.el.value!==new2.el.value)throw new Error('Новые пароли не совпадают');if(oldP.el.value===newP.el.value)throw new Error('Новый пароль должен отличаться');if(!window.confirm('После запуска все остальные сеансы этого аккаунта будут закрыты. Продолжить?')){start.disabled=false;return;}cachedOldBundle=await derive(oldP.el.value);await verifyOldPassword(cachedOldBundle);cachedNewBundle=await derive(newP.el.value);const stateNow=await client.start({newRootKey:cachedNewBundle.rootPair.publicKeyB64,newBlockchainKey:cachedNewBundle.blockchainPair.publicKeyB64,newClientKey:cachedNewBundle.clientPair.publicKeyB64,forkFromBlock:selected.blockNumber,forkFromHash:selected.blockHash,reasonCode:Number(reason.value),comment:comment.value});updateTopbar(stateNow.rotationStatus);await runCopy(stateNow); }catch(e){error.textContent=e?.message||String(e);start.disabled=false;}});
|
||||
start.addEventListener('click',async()=>{start.disabled=true;error.textContent='';try{if(!selected)throw new Error('Выберите последний доверенный блок');if(!oldP.el.value||!newP.el.value)throw new Error('Введите текущий и новый пароль');if(newP.el.value!==new2.el.value)throw new Error('Новые пароли не совпадают');if(oldP.el.value===newP.el.value)throw new Error('Новый пароль должен отличаться');if(!await confirmPasswordBoundarySpaces(newP.el.value)){start.disabled=false;return;}if(!window.confirm('После запуска все остальные сеансы этого аккаунта будут закрыты. Продолжить?')){start.disabled=false;return;}cachedOldBundle=await derive(oldP.el.value);await verifyOldPassword(cachedOldBundle);cachedNewBundle=await derive(newP.el.value);const stateNow=await client.start({newRootKey:cachedNewBundle.rootPair.publicKeyB64,newBlockchainKey:cachedNewBundle.blockchainPair.publicKeyB64,newClientKey:cachedNewBundle.clientPair.publicKeyB64,forkFromBlock:selected.blockNumber,forkFromHash:selected.blockHash,reasonCode:Number(reason.value),comment:comment.value});updateTopbar(stateNow.rotationStatus);await runCopy(stateNow); }catch(e){error.textContent=e?.message||String(e);start.disabled=false;}});
|
||||
setRoot(head,oldP.wrap,newP.wrap,new2.wrap,reasonWrap,comment,list,more,start,error);void load();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createVisiblePasswordField } from '../components/visible-password-field.js';
|
||||
import {
|
||||
authService,
|
||||
authorizeSession,
|
||||
@@ -69,7 +70,7 @@ export function render({ navigate }) {
|
||||
|
||||
const passwordInput = document.createElement('input');
|
||||
passwordInput.className = 'input';
|
||||
passwordInput.type = 'password';
|
||||
passwordInput.type = 'text';
|
||||
passwordInput.name = 'shine-login-password';
|
||||
passwordInput.autocomplete = 'current-password';
|
||||
passwordInput.autocapitalize = 'off';
|
||||
@@ -78,7 +79,7 @@ export function render({ navigate }) {
|
||||
passwordInput.placeholder = 'Пароль';
|
||||
passwordInput.value = '';
|
||||
|
||||
passwordField.append(passwordInput);
|
||||
passwordField.append(createVisiblePasswordField(passwordInput));
|
||||
|
||||
const status = document.createElement('p');
|
||||
status.className = 'status-line is-unavailable';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Экран «Связи»: люди вокруг выбранного человека – картой или списком.
|
||||
// Данные – GetUserConnectionsGraph (только чтение). Карту рисует graph-canvas.js, здесь –
|
||||
// состав (центр, раскрытые связи), фильтры, поиск, список, карточка человека и заметки.
|
||||
// состав (центр, раскрытые связи), фильтры, поиск, список, карточка человека.
|
||||
// «Компании», «Интересы» и «Города»: знакомства, подписки и города людей первого круга
|
||||
// собираются по одному запросу на человека (network/people-data-store.js), группы считает
|
||||
// network/communities.js, свои названия компаний и ручные переносы – network/companies-store.js.
|
||||
@@ -20,8 +20,6 @@ import { userDisplayName } from '../services/user-display.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { matchesPeopleQuery } from '../services/people-search.js';
|
||||
import { PEOPLE_NOTES_EVENT, getAllPersonNotes } from '../services/people-notes.js';
|
||||
import { createPersonNotePreview, openPersonNoteSheet } from '../components/person-note-sheet.js';
|
||||
import { createGraphCanvas } from './network/graph-canvas.js';
|
||||
import { peopleFromGraphModel, relationTypeFromRelation } from './network/adapter.js';
|
||||
import { REST_GROUP, buildCityGroups, buildCompanies, buildInterestGroups, tieWeight } from './network/communities.js';
|
||||
@@ -194,7 +192,6 @@ const FILTERS = [
|
||||
{ id: 'close', label: 'Близкие', direct: true, pred: (node) => node.relationType === 'close_friend' || node.relationType === 'family' },
|
||||
{ id: 'friends', label: 'Друзья', direct: true, pred: (node) => node.relationType === 'friend' },
|
||||
{ id: 'shining', label: 'Сияющие', pred: (node) => Boolean(node.shining) },
|
||||
{ id: 'notes', label: 'С заметкой', pred: (node) => Boolean(node.mark || node.hasNote) },
|
||||
];
|
||||
const FILTER_BY_ID = new Map(FILTERS.map((filter) => [filter.id, filter]));
|
||||
|
||||
@@ -230,15 +227,14 @@ function tieWeights(ties, ids) {
|
||||
return weights;
|
||||
}
|
||||
|
||||
function composeMap(centerLogin, graphs, expanded, notes, ties = null) {
|
||||
function composeMap(centerLogin, graphs, expanded, ties = null) {
|
||||
const centerKey = normKey(centerLogin);
|
||||
const centerModel = graphs.get(centerKey);
|
||||
if (!centerModel) return null;
|
||||
const byId = new Map();
|
||||
const edges = [];
|
||||
const add = (node) => {
|
||||
const note = notes.get(node.id);
|
||||
byId.set(node.id, { ...node, mark: note?.mark || '', hasNote: Boolean(note?.text?.trim()), hiddenCount: 0 });
|
||||
byId.set(node.id, { ...node, hiddenCount: 0 });
|
||||
};
|
||||
|
||||
const { center, peers } = peopleFromGraphModel(centerModel);
|
||||
@@ -313,7 +309,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
let viewMode = getViewSetting('view', 'map') === 'list' ? 'list' : 'map';
|
||||
const LIST_SORTS = ['closeness', 'companies', 'interests', 'cities', 'name'];
|
||||
let listSort = LIST_SORTS.includes(getViewSetting('listSort', 'closeness')) ? getViewSetting('listSort', 'closeness') : 'closeness';
|
||||
let notes = getAllPersonNotes();
|
||||
const graphs = new Map();
|
||||
const expanding = new Set();
|
||||
let map = null;
|
||||
@@ -321,7 +316,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
let disposed = false;
|
||||
let loadSeq = 0;
|
||||
let loadError = null;
|
||||
let noteSheet = null;
|
||||
let legendSheet = null;
|
||||
let search = null; // { query, topbar, layer, remote: { seq, query, items, loading, failed } }
|
||||
let groupsModel = null; // острова «Компаний» / «Интересов»: { lens, groups, byId, byPerson }
|
||||
@@ -443,7 +437,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
let listFrame = 0;
|
||||
function renderMap({ fit = false, relayout = false } = {}) {
|
||||
if (disposed) return;
|
||||
map = composeMap(centerLogin, graphs, expanded, notes, getTies(normKey(centerLogin)));
|
||||
map = composeMap(centerLogin, graphs, expanded, getTies(normKey(centerLogin)));
|
||||
if (!map) return;
|
||||
// Фильтры должны быть на месте до вписывания карты: от них зависит свободная часть экрана.
|
||||
screen.classList.toggle('is-blank', map.nodes.length <= 1);
|
||||
@@ -494,7 +488,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
const relation = node.id === map.focusId ? 'в центре карты' : (RELATION_LABEL[node.relationType] || 'Связь').toLowerCase();
|
||||
button.textContent = `${node.name}, ${relation}${node.shining ? ', сияющий' : ''}${node.mark || node.hasNote ? ', есть заметка' : ''}`;
|
||||
button.textContent = `${node.name}, ${relation}${node.shining ? ', сияющий' : ''}`;
|
||||
button.addEventListener('click', () => selectNode(node.id, { reveal: true }));
|
||||
li.append(button);
|
||||
a11yList.append(li);
|
||||
@@ -640,7 +634,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
function collapseNode(id) {
|
||||
expanded.delete(id);
|
||||
for (;;) {
|
||||
const next = composeMap(centerLogin, graphs, expanded, notes);
|
||||
const next = composeMap(centerLogin, graphs, expanded);
|
||||
const orphan = [...expanded].find((key) => !next?.byId.has(key));
|
||||
if (!orphan) break;
|
||||
expanded.delete(orphan);
|
||||
@@ -809,9 +803,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
card.append(row);
|
||||
}
|
||||
|
||||
const note = isSelf ? null : notes.get(node.id);
|
||||
const notePreview = createPersonNotePreview(note, { className: 'net-card__note', onClick: () => openNoteEditor(node) });
|
||||
if (notePreview) card.append(notePreview);
|
||||
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'net-card__actions';
|
||||
@@ -829,7 +820,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
}));
|
||||
if (!isSelf) {
|
||||
actions.append(cardAction('message', 'Написать', () => navigate(`chat/${encodeURIComponent(node.login)}`)));
|
||||
actions.append(cardAction('edit', 'Заметка', () => openNoteEditor(node)));
|
||||
}
|
||||
card.append(actions);
|
||||
if (node.hiddenCount > 0) {
|
||||
@@ -842,17 +832,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
placeOverlays();
|
||||
}
|
||||
|
||||
// --- заметка ---
|
||||
function openNoteEditor(node) {
|
||||
noteSheet?.close();
|
||||
noteSheet = openPersonNoteSheet({ login: node.id, name: node.name, onClose: () => { noteSheet = null; } });
|
||||
}
|
||||
|
||||
function onNotesChanged() {
|
||||
notes = getAllPersonNotes();
|
||||
renderMap();
|
||||
}
|
||||
window.addEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
|
||||
// --- обозначения ---
|
||||
function openLegend() {
|
||||
@@ -870,7 +849,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
['dash', 'friend', 'Пунктир → точки – вы добавили друга, ответа пока нет'],
|
||||
['aura', '', 'Свечение вокруг – сияющий'],
|
||||
['badge', '', 'Синяя галочка – официальный аккаунт'],
|
||||
['mark', '', 'Цветная точка – ваша заметка или метка'],
|
||||
];
|
||||
for (const [kind, type, text] of rows) {
|
||||
const li = document.createElement('li');
|
||||
@@ -1809,7 +1787,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
const PRIMARY_FILTERS = ['all', 'close', 'friends'];
|
||||
const EXTRA_FILTERS = [
|
||||
{ id: 'shining', short: 'Сияющие', icon: 'sparkle' },
|
||||
{ id: 'notes', short: 'С заметкой', icon: 'edit' },
|
||||
];
|
||||
const filterBar = document.createElement('div');
|
||||
filterBar.className = 'net-filters';
|
||||
@@ -2033,7 +2010,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
if (!node) return [];
|
||||
return [
|
||||
{ label: 'Профиль', iconHtml: iconHtml('profile'), action: () => navigate(profileRoute(node.login)) },
|
||||
{ label: 'Заметка', iconHtml: iconHtml('edit'), action: () => openNoteEditor(node) },
|
||||
{ label: 'Показать на карте', iconHtml: iconHtml('network'), action: () => showOnMap(node.id) },
|
||||
{ label: 'Его связи', iconHtml: iconHtml('focus'), action: () => recenter(node.login) },
|
||||
];
|
||||
@@ -2063,7 +2039,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
// Вторая строка – только то, чего не видно из раздела: тип связи нужен, когда список
|
||||
// не разбит по типам, «взаимно» – обычный случай и не пишется.
|
||||
function personRow(node, { onOpen = null, withType = false } = {}) {
|
||||
const note = notes.get(node.id);
|
||||
const sub = [];
|
||||
if (normKey(node.name) !== node.id) sub.push(node.login);
|
||||
if (node.tier > 1) {
|
||||
@@ -2082,8 +2057,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
avatar: node.avatar,
|
||||
official: node.official,
|
||||
sub: sub.join(' · '),
|
||||
note: note?.text?.trim() ? note.text.trim().split('\n')[0] : '',
|
||||
markColor: note?.mark || (note?.text?.trim() ? 'note' : ''),
|
||||
ring: node.shining ? 'shining' : (node.relationType === 'close_friend' && node.tier === 1 ? 'close' : ''),
|
||||
tag: '',
|
||||
onClick: onOpen || (() => {
|
||||
@@ -2326,7 +2299,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
|
||||
function onKeydown(event) {
|
||||
const typing = event.target instanceof HTMLElement && event.target.closest('input, textarea, [contenteditable="true"]');
|
||||
const overlayOpen = Boolean(noteSheet || legendSheet || groupSheet || document.querySelector('.dropdown-portal, .modal'));
|
||||
const overlayOpen = Boolean(legendSheet || groupSheet || document.querySelector('.dropdown-portal, .modal'));
|
||||
if (event.key === 'Escape') {
|
||||
if (overlayOpen || search) return;
|
||||
if (selectedId) selectNode('');
|
||||
@@ -2384,11 +2357,9 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
moreMenu.destroy();
|
||||
window.cancelAnimationFrame(listFrame);
|
||||
window.clearTimeout(remoteTimer);
|
||||
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
|
||||
window.clearInterval(graphRefreshTimer);
|
||||
document.removeEventListener('keydown', onKeydown);
|
||||
noteSheet?.close();
|
||||
legendSheet?.close();
|
||||
groupSheet?.close();
|
||||
if (search) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { confirmPublicHistoryAction } from '../services/public-history-consent.js';
|
||||
import { confirmConsentSteps } from '../components/consent-steps.js';
|
||||
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
@@ -210,6 +211,7 @@ export function render({ navigate, chrome }) {
|
||||
const firstName = String(currentFields.find((field) => field.key === 'first_name')?.value || '').trim();
|
||||
const lastName = String(currentFields.find((field) => field.key === 'last_name')?.value || '').trim();
|
||||
avatarSlotEl.innerHTML = '';
|
||||
avatarSlotEl.classList.toggle('is-shining', currentShineStatus === PROFILE_SHINE_SHINING);
|
||||
avatarSlotEl.append(renderUserAvatar({
|
||||
login,
|
||||
firstName,
|
||||
@@ -220,6 +222,7 @@ export function render({ navigate, chrome }) {
|
||||
size: 'xl',
|
||||
// Как в карточке профиля: без стеклянного кольца, которое вылезало за край экрана.
|
||||
className: 'profile-avatar avatar-plain',
|
||||
official: currentAccountRole === PROFILE_ACCOUNT_ROLE_PRIMARY,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -368,7 +371,7 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
|
||||
async function onChangeAvatarClick() {
|
||||
const accepted = await confirmDialog({
|
||||
const accepted = await confirmPublicHistoryAction({
|
||||
title: 'Публичная история аватара',
|
||||
text: 'Новый аватар и ссылка на него могут остаться доступны в публичной истории даже после замены. Продолжить к выбору аватара?',
|
||||
confirmLabel: 'Выбрать аватар',
|
||||
@@ -483,7 +486,7 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
|
||||
if (String(entered).trim() === String(field.value || '').trim()) return;
|
||||
const accepted = await confirmDialog({
|
||||
const accepted = await confirmPublicHistoryAction({
|
||||
title: `Опубликовать изменение «${field.label}»?`,
|
||||
text: HISTORY_WARNING,
|
||||
confirmLabel: 'Да, записать',
|
||||
@@ -507,7 +510,7 @@ export function render({ navigate, chrome }) {
|
||||
async function onGenderClick() {
|
||||
const nextGender = await openGenderPickerModal(currentGender);
|
||||
if (!nextGender || nextGender === currentGender) return;
|
||||
const accepted = await confirmDialog({
|
||||
const accepted = await confirmPublicHistoryAction({
|
||||
title: 'Опубликовать изменение пола?',
|
||||
text: HISTORY_WARNING,
|
||||
confirmLabel: 'Да, записать',
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { createVisiblePasswordField } from '../components/visible-password-field.js';
|
||||
import { confirmPasswordBoundarySpaces } from '../services/password-boundary-warning.js';
|
||||
import { createRegistrationStepper } from '../components/registration-stepper.js';
|
||||
import { authService, clearAuthMessages, state } from '../state.js';
|
||||
import { PASSWORD_MAX_LENGTH } from '../services/password-words.js';
|
||||
@@ -151,16 +153,7 @@ export function render({ navigate }) {
|
||||
input.maxLength = PASSWORD_MAX_LENGTH;
|
||||
input.placeholder = 'Ваш секретный пароль';
|
||||
input.value = draft.password || '';
|
||||
const toggle = document.createElement('button');
|
||||
toggle.className = 'secondary-btn';
|
||||
toggle.type = 'button';
|
||||
toggle.textContent = 'Скрыть';
|
||||
toggle.setAttribute('aria-label', 'Показать или скрыть пароль');
|
||||
toggle.addEventListener('click', () => {
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
toggle.textContent = input.type === 'password' ? 'Показать' : 'Скрыть';
|
||||
});
|
||||
label.append(labelText, input);
|
||||
label.append(labelText, createVisiblePasswordField(input));
|
||||
const guidance = document.createElement('div');
|
||||
guidance.className = 'signup-guidance';
|
||||
guidance.innerHTML = `
|
||||
@@ -185,6 +178,9 @@ export function render({ navigate }) {
|
||||
return;
|
||||
}
|
||||
if (!draft.login || !draft.login.includes('@')) { status.textContent = 'Сначала выберите логин.'; return; }
|
||||
const warningRevision = inputRevision;
|
||||
if (!await confirmPasswordBoundarySpaces(value) || !screen.isConnected) return;
|
||||
if (warningRevision !== inputRevision || input.value !== value) { status.textContent = 'Пароль изменился. Нажмите «Продолжить» ещё раз.'; return; }
|
||||
if (draft.password && draft.password !== value && !confirmFundedWalletChange()) return;
|
||||
if (draft.password && draft.password !== value) {
|
||||
state.registrationPayment.walletAddress = '';
|
||||
@@ -211,7 +207,7 @@ export function render({ navigate }) {
|
||||
if (screen.isConnected && thisRequest === requestId) next.disabled = false;
|
||||
}
|
||||
});
|
||||
body.append(heading, description, label, toggle, guidance, status, next);
|
||||
body.append(heading, description, label, guidance, status, next);
|
||||
}
|
||||
|
||||
if (flowType !== 'free' && flowType !== 'paid') {
|
||||
|
||||
@@ -31,7 +31,7 @@ import { getNamespace, normalizeFullLogin } from '../services/shine-namespace-se
|
||||
import { calculateRegistrationFunding, USER_PDA_SPACE, solFromLamports } from '../services/registration-upgrade-helpers.js';
|
||||
|
||||
export const pageMeta = { id: 'registration-payment-view', title: 'Оплата регистрации', showAppChrome: false };
|
||||
const TEST_TOPUP_AMOUNT_SOL = 0.02;
|
||||
const TEST_TOPUP_AMOUNT_SOL = 0.032;
|
||||
const DEVNET_ENDPOINT = 'https://api.devnet.solana.com';
|
||||
const TEST_TOPUP_SENDER_PRIVATE_32_BASE58 = '6xqAuKYvA8qrCdAkcw7Y8aMgvBnYk8JLxWLma5BzbAvu';
|
||||
const AUTO_LOGIN_INITIAL_DELAY_MS = 1000;
|
||||
@@ -746,7 +746,7 @@ function renderSolanaDoneStage({ navigate, status, keyBundle, registrationTxId =
|
||||
}, AUTO_LOGIN_INITIAL_DELAY_MS);
|
||||
}
|
||||
|
||||
/** Тот же тестовый источник +0.02 devnet SOL, что используется обычной регистрацией.
|
||||
/** Тот же тестовый источник +0.032 devnet SOL, что используется обычной регистрацией.
|
||||
* Экспорт добавлен для FREE_CERT → Solana upgrade; поведение обычной регистрации не изменяется.
|
||||
* Никогда не используйте этот встроенный devnet-кошелёк для реальных средств.
|
||||
*/
|
||||
|
||||
@@ -127,6 +127,7 @@ export function render({navigate, chrome}) {
|
||||
<div class="nav-list">
|
||||
${row('settings-appearance', 'Оформление', appearanceHint)}
|
||||
${row('settings-notifications', 'Уведомления', 'Звук, разрешение, чаты без звука')}
|
||||
${row('settings-application', 'Настройки приложения', 'Подтверждения публичных записей')}
|
||||
${row('settings-language', 'Язык / Language', 'Русский')}
|
||||
</div>
|
||||
<div class="nav-list">
|
||||
@@ -173,6 +174,7 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
card.querySelector('#settings-appearance').addEventListener('click', () => navigate('appearance-view'));
|
||||
card.querySelector('#settings-notifications').addEventListener('click', () => navigate('notification-settings-view'));
|
||||
card.querySelector('#settings-application').addEventListener('click', () => navigate('application-settings-view'));
|
||||
card.querySelector('#settings-about').addEventListener('click', () => {
|
||||
aboutSheet?.close();
|
||||
aboutSheet = openAboutSheet();
|
||||
|
||||
@@ -8,9 +8,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { makeProfileLinksRoute } from '../services/shine-routes.js';
|
||||
import { navigateBack } from '../router.js';
|
||||
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
||||
import { createPersonNotePreview, openPersonNoteSheet } from '../components/person-note-sheet.js';
|
||||
import { iconHtml } from '../components/ui-icon.js';
|
||||
import { PEOPLE_NOTES_EVENT, getPersonNote } from '../services/people-notes.js';
|
||||
|
||||
export const pageMeta = { id: 'user', title: 'Профиль' };
|
||||
|
||||
@@ -46,19 +44,9 @@ export function render({ navigate, route, chrome }) {
|
||||
|
||||
let card = null;
|
||||
let disposed = false;
|
||||
let noteSheet = null;
|
||||
let relation = null; // кем человек вам приходится – для плитки «Добавить связь»
|
||||
|
||||
function openNote() {
|
||||
noteSheet?.close();
|
||||
const name = [card.firstName, card.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ') || card.login;
|
||||
noteSheet = openPersonNoteSheet({ login: card.login, name, onClose: () => { noteSheet = null; } });
|
||||
}
|
||||
|
||||
function renderProfile() {
|
||||
if (!card || disposed) return;
|
||||
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
||||
const note = isSelf ? null : getPersonNote(card.login);
|
||||
|
||||
body.innerHTML = profileCardHtml({
|
||||
card,
|
||||
@@ -71,18 +59,6 @@ export function render({ navigate, route, chrome }) {
|
||||
].join(''),
|
||||
});
|
||||
|
||||
// Личная заметка – сразу под кнопками действий; видна только владельцу аккаунта.
|
||||
let noteEl = createPersonNotePreview(note, { className: 'user-profile-note', onClick: openNote });
|
||||
if (noteEl) {
|
||||
noteEl.setAttribute('aria-label', `Ваша заметка: ${noteEl.textContent}. Изменить`);
|
||||
} else if (!isSelf) {
|
||||
noteEl = document.createElement('button');
|
||||
noteEl.type = 'button';
|
||||
noteEl.className = 'text-btn user-profile-note-add';
|
||||
noteEl.innerHTML = `${iconHtml('edit')}<span>Добавить личную заметку</span>`;
|
||||
noteEl.addEventListener('click', openNote);
|
||||
}
|
||||
if (noteEl) body.querySelector('.pf-tiles-wrap')?.after(noteEl);
|
||||
syncRelationTile();
|
||||
|
||||
const avatarSlot = body.querySelector('.user-profile-avatar-slot');
|
||||
@@ -154,13 +130,9 @@ export function render({ navigate, route, chrome }) {
|
||||
}
|
||||
});
|
||||
|
||||
const onNotesChanged = () => renderProfile();
|
||||
window.addEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
noteSheet?.close();
|
||||
};
|
||||
|
||||
async function refresh() {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { confirmPublicHistoryAction } from '../services/public-history-consent.js';
|
||||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||||
import { authService, state } from '../state.js';
|
||||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||||
@@ -215,7 +216,7 @@ export function render({ route, chrome }) {
|
||||
const isAttestation = confirm === 'official_account' || confirm === 'shine_confirmed';
|
||||
const withdrawing = (confirm === 'official_account' && flags.outOfficialAccount)
|
||||
|| (confirm === 'shine_confirmed' && flags.outShineConfirmed);
|
||||
const accepted = await confirmDialog({
|
||||
const accepted = await (isAttestation ? confirmDialog : confirmPublicHistoryAction)({
|
||||
title: isAttestation ? 'Подтверждаете другого человека?' : 'Изменить публичную связь?',
|
||||
text: isAttestation
|
||||
? 'Подтверждайте только реального человека, которого действительно знаете или можете обоснованно признать сияющим. Ложные подтверждения и их последующая отмена могут навсегда остаться в блокчейне и учитываться независимыми анализаторами.'
|
||||
|
||||
@@ -4,14 +4,12 @@ import { authService, state } from '../state.js';
|
||||
import {
|
||||
formatSol,
|
||||
getBalanceSol,
|
||||
getTopupSiteUrl,
|
||||
getWalletFromStoredBlockchainKey,
|
||||
transferSol,
|
||||
} from '../services/solana-wallet-service.js';
|
||||
import {
|
||||
formatAr,
|
||||
getArweaveBalance,
|
||||
getArweaveTopupSiteUrl,
|
||||
getArweaveWalletFromStoredBlockchainKey,
|
||||
transferAr,
|
||||
} from '../services/arweave-wallet-service.js';
|
||||
@@ -33,6 +31,11 @@ import {
|
||||
saveStoredBlockchainSnapshot,
|
||||
} from '../services/shine-blockchain-snapshot-service.js';
|
||||
import { actionErrorText } from '../services/ui-error-texts.js';
|
||||
import {
|
||||
formatTurboCredits,
|
||||
getTurboBalanceForStoredSolanaKey,
|
||||
topUpTurboWithSolana,
|
||||
} from '../services/turbo-upload-service.js';
|
||||
|
||||
export const pageMeta = { id: 'wallet-view', title: 'Кошелёк' };
|
||||
|
||||
@@ -85,6 +88,41 @@ function createModeBackButton(renderWalletChoice) {
|
||||
return backBtn;
|
||||
}
|
||||
|
||||
// A local, short-lived confirmation next to the address avoids changing page status.
|
||||
function enableAddressCopy(addressEl, getAddress) {
|
||||
const wrapper = addressEl.parentElement;
|
||||
addressEl.tabIndex = 0;
|
||||
addressEl.setAttribute('role', 'button');
|
||||
addressEl.setAttribute('aria-label', 'Скопировать адрес в буфер обмена');
|
||||
addressEl.title = 'Нажмите, чтобы скопировать адрес';
|
||||
addressEl.style.cursor = 'pointer';
|
||||
const message = document.createElement('span');
|
||||
message.className = 'meta-muted';
|
||||
message.style.cssText = 'display:block;min-height:18px;font-size:12px;';
|
||||
message.setAttribute('aria-live', 'polite');
|
||||
wrapper.append(message);
|
||||
let timeoutId = 0;
|
||||
const copy = async () => {
|
||||
const value = String(getAddress() || '').trim();
|
||||
if (!value) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
message.textContent = 'Скопировано в буфер';
|
||||
} catch {
|
||||
message.textContent = 'Не удалось скопировать адрес';
|
||||
}
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = setTimeout(() => { if (message.isConnected) message.textContent = ''; }, 2200);
|
||||
};
|
||||
addressEl.addEventListener('click', () => { void copy(); });
|
||||
addressEl.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
void copy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function sessionArgsOrThrow() {
|
||||
const login = String(state.session.login || '').trim();
|
||||
const storagePwd = String(state.session.storagePwdInMemory || '').trim();
|
||||
@@ -1283,8 +1321,8 @@ export function render({navigate, chrome}) {
|
||||
const items = [
|
||||
['Solana кошелёк', 'Баланс SOL', () => renderSolanaWallet()],
|
||||
['Arweave кошелёк', 'Баланс AR', () => renderArweaveWallet()],
|
||||
['Turbo кошелёк', 'Кредиты Turbo для загрузки файлов', () => renderTurboWallet()],
|
||||
['Предоплаченное место Сияния', 'Лимит, израсходовано и остаток', () => renderShineBlockchainWallet()],
|
||||
['Закрепление в Solana', 'Что закреплено в Solana и на сервере', () => renderSolanaPublishWallet()],
|
||||
['Поддержать проект Сияние', 'Билеты и справка', () => renderSupportHub()],
|
||||
];
|
||||
const buttons = items.map(([label, hint, open]) => {
|
||||
@@ -1297,8 +1335,7 @@ export function render({navigate, chrome}) {
|
||||
btn.addEventListener('click', () => { void open(); });
|
||||
return btn;
|
||||
});
|
||||
const [solanaBtn, arweaveBtn, shineBchBtn, solanaPublishBtn, supportBtn] = buttons;
|
||||
card.append(solanaBtn, arweaveBtn, shineBchBtn, solanaPublishBtn, supportBtn);
|
||||
card.append(...buttons);
|
||||
content.append(card);
|
||||
setStatus('');
|
||||
}
|
||||
@@ -1427,50 +1464,6 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
};
|
||||
|
||||
topupBtn.addEventListener('click', async () => {
|
||||
setButtonsDisabled(true);
|
||||
try {
|
||||
const economy = await getShineUsersEconomyConfig({ solanaEndpoint: state.entrySettings.solanaServer });
|
||||
const step = getLimitStepBytes();
|
||||
const input = window.prompt(
|
||||
`Введите, на сколько увеличить лимит (в байтах, шаг ${step.toString()}).\nЦена за шаг: ${lamportsToSolText(economy.lamportsPerLimitStep)} SOL`,
|
||||
step.toString(),
|
||||
);
|
||||
if (!input) {
|
||||
setStatus('Увеличение лимита отменено.');
|
||||
return;
|
||||
}
|
||||
const addBytes = BigInt(String(input).trim());
|
||||
const priceLamports = calcLimitTopupPriceLamports(addBytes, economy.lamportsPerLimitStep);
|
||||
const confirm = window.confirm(
|
||||
`Будет увеличено на ${formatKbFromBytes(addBytes)}.\n` +
|
||||
`С вашего Solana-счёта будет списано ~${lamportsToSolText(priceLamports)} SOL.\n` +
|
||||
`Продолжить?`,
|
||||
);
|
||||
if (!confirm) {
|
||||
setStatus('Увеличение лимита отменено.');
|
||||
return;
|
||||
}
|
||||
const signing = await resolveWalletSigningMaterial();
|
||||
const result = await updateShineUserPdaOnSolana({
|
||||
login: String(state.session.login || '').trim(),
|
||||
solanaEndpoint: state.entrySettings.solanaServer,
|
||||
rootPrivatePkcs8B64: signing.rootPrivatePkcs8B64,
|
||||
blockchainPrivatePkcs8B64: signing.blockchainPrivatePkcs8B64,
|
||||
clientPrivatePkcs8B64: signing.clientPrivatePkcs8B64,
|
||||
additionalLimitBytes: addBytes,
|
||||
});
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(`Лимит увеличен. Tx: ${result.signature}`);
|
||||
await refreshUsage();
|
||||
} catch (error) {
|
||||
if (modeToken !== activeModeToken) return;
|
||||
setStatus(formatLimitTopupError(error));
|
||||
} finally {
|
||||
setButtonsDisabled(false);
|
||||
}
|
||||
});
|
||||
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
void refreshUsage();
|
||||
});
|
||||
@@ -1867,6 +1860,7 @@ export function render({navigate, chrome}) {
|
||||
<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');
|
||||
enableAddressCopy(addressEl, () => walletAddress);
|
||||
|
||||
card.append(balanceWrap, addressCard);
|
||||
|
||||
@@ -1874,19 +1868,13 @@ export function render({navigate, chrome}) {
|
||||
actions.className = 'stack';
|
||||
actions.innerHTML = `
|
||||
<div class="row">
|
||||
<button class="text-btn" id="copy-address">Копировать адрес</button>
|
||||
<button class="ghost-btn" id="refresh-balance">Обновить баланс</button>
|
||||
</div>
|
||||
<div class="row">
|
||||
<button class="primary-btn" id="send-sol" style="width:100%;">Перевести</button>
|
||||
<button class="primary-btn" id="topup-sol" style="width:100%;">Пополнить</button>
|
||||
<button class="primary-btn" id="refresh-balance" style="flex:1;">Обновить баланс</button>
|
||||
<button class="primary-btn" id="send-sol" style="flex:1;">Перевести</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const copyBtn = actions.querySelector('#copy-address');
|
||||
const refreshBtn = actions.querySelector('#refresh-balance');
|
||||
const sendBtn = actions.querySelector('#send-sol');
|
||||
const topupBtn = actions.querySelector('#topup-sol');
|
||||
|
||||
const refreshBalance = async () => {
|
||||
if (!walletAddress) {
|
||||
@@ -1912,16 +1900,6 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
};
|
||||
|
||||
copyBtn.addEventListener('click', async () => {
|
||||
if (!walletAddress) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(walletAddress);
|
||||
setStatus('Адрес скопирован в буфер обмена');
|
||||
} catch {
|
||||
setStatus('Не удалось скопировать адрес в этом браузере');
|
||||
}
|
||||
});
|
||||
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
void refreshBalance();
|
||||
});
|
||||
@@ -1955,14 +1933,6 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
});
|
||||
|
||||
topupBtn.addEventListener('click', async () => {
|
||||
if (!walletAddress) {
|
||||
setStatus('Кошелёк не инициализирован.');
|
||||
return;
|
||||
}
|
||||
window.location.assign(getTopupSiteUrl(walletAddress));
|
||||
});
|
||||
|
||||
content.append(backBtn, card, actions);
|
||||
setStatus('Инициализация blockchain.key...');
|
||||
|
||||
@@ -1990,6 +1960,11 @@ export function render({navigate, chrome}) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
|
||||
const info = document.createElement('p');
|
||||
info.className = 'meta-muted';
|
||||
info.textContent = 'Arweave-кошелёк хранит баланс AR для прямой загрузки файлов в децентрализованную сеть Arweave. Прямая загрузка удобна для крупных файлов и может быть дешевле Turbo в зависимости от актуальных тарифов.';
|
||||
card.append(info);
|
||||
|
||||
const balanceWrap = document.createElement('div');
|
||||
const balanceLabel = document.createElement('p');
|
||||
balanceLabel.className = 'meta-muted';
|
||||
@@ -2013,6 +1988,7 @@ export function render({navigate, chrome}) {
|
||||
<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');
|
||||
enableAddressCopy(addressEl, () => walletAddress);
|
||||
|
||||
const helpCard = document.createElement('details');
|
||||
helpCard.className = 'card';
|
||||
@@ -2031,19 +2007,13 @@ export function render({navigate, chrome}) {
|
||||
actions.className = 'stack';
|
||||
actions.innerHTML = `
|
||||
<div class="row">
|
||||
<button class="text-btn" id="copy-address">Копировать адрес</button>
|
||||
<button class="ghost-btn" id="refresh-balance">Обновить баланс</button>
|
||||
</div>
|
||||
<div class="row">
|
||||
<button class="primary-btn" id="send-ar" style="width:100%;">Перевести</button>
|
||||
<button class="primary-btn" id="topup-ar" style="width:100%;">Пополнить</button>
|
||||
<button class="primary-btn" id="refresh-balance" style="flex:1;">Обновить баланс</button>
|
||||
<button class="primary-btn" id="send-ar" style="flex:1;">Перевести</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const copyBtn = actions.querySelector('#copy-address');
|
||||
const refreshBtn = actions.querySelector('#refresh-balance');
|
||||
const sendBtn = actions.querySelector('#send-ar');
|
||||
const topupBtn = actions.querySelector('#topup-ar');
|
||||
|
||||
const refreshBalance = async () => {
|
||||
if (!walletAddress) {
|
||||
@@ -2069,16 +2039,6 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
};
|
||||
|
||||
copyBtn.addEventListener('click', async () => {
|
||||
if (!walletAddress) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(walletAddress);
|
||||
setStatus('Адрес скопирован');
|
||||
} catch {
|
||||
setStatus('Не удалось скопировать адрес в этом браузере');
|
||||
}
|
||||
});
|
||||
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
void refreshBalance();
|
||||
});
|
||||
@@ -2112,11 +2072,6 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
});
|
||||
|
||||
topupBtn.addEventListener('click', () => {
|
||||
window.open(getArweaveTopupSiteUrl(), '_blank', 'noopener,noreferrer');
|
||||
setStatus('Открыта страница пополнения.');
|
||||
});
|
||||
|
||||
content.append(backBtn, card, actions);
|
||||
setStatus('Генерация Arweave-кошелька...');
|
||||
|
||||
@@ -2148,6 +2103,106 @@ export function render({navigate, chrome}) {
|
||||
}
|
||||
}
|
||||
|
||||
async function renderTurboWallet() {
|
||||
const modeToken = ++activeModeToken;
|
||||
clearArweaveSecretsInMemory();
|
||||
content.innerHTML = '';
|
||||
let walletAddress = '';
|
||||
const backBtn = createModeBackButton(renderWalletChoice);
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card stack';
|
||||
const info = document.createElement('p');
|
||||
info.className = 'meta-muted';
|
||||
info.textContent = 'Turbo — сторонний централизованный сервис загрузки в Arweave. Удобен для небольших файлов и быстрого пополнения кредитов напрямую с вашего Solana-кошелька. Баланс Turbo измеряется в кредитах, а не в SOL или AR.';
|
||||
const balanceLabel = document.createElement('p');
|
||||
balanceLabel.className = 'meta-muted';
|
||||
balanceLabel.textContent = 'Доступный баланс Turbo';
|
||||
const balanceValue = document.createElement('h2');
|
||||
balanceValue.style.fontSize = '30px';
|
||||
balanceValue.textContent = '– кредитов';
|
||||
const updatedLabel = document.createElement('p');
|
||||
updatedLabel.className = 'meta-muted';
|
||||
updatedLabel.textContent = 'Обновлено: –';
|
||||
const solanaBalanceLabel = document.createElement('p');
|
||||
solanaBalanceLabel.className = 'meta-muted';
|
||||
solanaBalanceLabel.textContent = 'Баланс Solana для пополнения: –';
|
||||
const addressCard = document.createElement('div');
|
||||
addressCard.className = 'card';
|
||||
addressCard.style.padding = '10px';
|
||||
const addressHint = document.createElement('p');
|
||||
addressHint.className = 'meta-muted';
|
||||
addressHint.textContent = 'Solana-адрес, связанный с балансом Turbo (нажмите, чтобы скопировать)';
|
||||
const addressEl = document.createElement('p');
|
||||
addressEl.style.cssText = 'font-size:13px;line-height:1.4;word-break:break-all;';
|
||||
addressEl.textContent = '–';
|
||||
addressCard.append(addressHint, addressEl);
|
||||
enableAddressCopy(addressEl, () => walletAddress);
|
||||
card.append(info, balanceLabel, balanceValue, updatedLabel, solanaBalanceLabel, addressCard);
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'row';
|
||||
const refreshBtn = document.createElement('button');
|
||||
refreshBtn.type = 'button';
|
||||
refreshBtn.className = 'primary-btn';
|
||||
refreshBtn.style.flex = '1';
|
||||
refreshBtn.textContent = 'Обновить баланс';
|
||||
const topupBtn = document.createElement('button');
|
||||
topupBtn.type = 'button';
|
||||
topupBtn.className = 'primary-btn';
|
||||
topupBtn.style.flex = '1';
|
||||
topupBtn.textContent = 'Пополнить';
|
||||
actions.append(refreshBtn, topupBtn);
|
||||
content.append(backBtn, card, actions);
|
||||
|
||||
const refreshBalance = async () => {
|
||||
refreshBtn.disabled = true;
|
||||
try {
|
||||
const result = await getTurboBalanceForStoredSolanaKey(sessionArgsOrThrow());
|
||||
if (modeToken !== activeModeToken) return null;
|
||||
walletAddress = result.address;
|
||||
addressEl.textContent = walletAddress;
|
||||
balanceValue.textContent = `${formatTurboCredits(result.effectiveCredits, 6)} кредитов`;
|
||||
solanaBalanceLabel.textContent = `Баланс Solana для пополнения: ${formatSol(result.solBalance, 6)} SOL`;
|
||||
updatedLabel.textContent = `Обновлено: ${nowRu()}`;
|
||||
setStatus('Баланс обновлён.');
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (modeToken === activeModeToken) setStatus(actionErrorText('Не удалось получить баланс Turbo', error));
|
||||
return null;
|
||||
} finally {
|
||||
refreshBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
refreshBtn.addEventListener('click', () => { void refreshBalance(); });
|
||||
topupBtn.addEventListener('click', async () => {
|
||||
if (!walletAddress) {
|
||||
setStatus('Сначала загрузите адрес Turbo-кошелька.');
|
||||
return;
|
||||
}
|
||||
const rawAmount = window.prompt('Сколько SOL перевести с вашего Solana-кошелька на баланс Turbo?', '0.01');
|
||||
if (rawAmount === null) return;
|
||||
const amount = String(rawAmount).trim().replace(',', '.');
|
||||
if (!/^(?:\d+)(?:\.\d{1,9})?$/.test(amount) || !(Number(amount) > 0)) {
|
||||
setStatus('Укажите положительную сумму SOL (не более 9 знаков после запятой).');
|
||||
return;
|
||||
}
|
||||
if (!window.confirm(`Пополнить Turbo на ${amount} SOL с вашего Solana-кошелька? Это реальная операция в сети Solana.`)) return;
|
||||
topupBtn.disabled = true;
|
||||
setStatus('Отправка SOL через Turbo SDK...');
|
||||
try {
|
||||
const result = await topUpTurboWithSolana({ ...sessionArgsOrThrow(), amountSol: amount });
|
||||
if (modeToken !== activeModeToken) return;
|
||||
await refreshBalance();
|
||||
if (modeToken === activeModeToken) setStatus(`Пополнение отправлено. Транзакция: ${result.txId || 'подтверждение получено'}`);
|
||||
} catch (error) {
|
||||
if (modeToken === activeModeToken) setStatus(actionErrorText('Не удалось пополнить Turbo', error));
|
||||
} finally {
|
||||
topupBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
setStatus('Загрузка баланса Turbo...');
|
||||
await refreshBalance();
|
||||
}
|
||||
|
||||
renderWalletChoice();
|
||||
return screen;
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ const PRETTY_PATHS = new Map([
|
||||
['language-view', 'settings/language'],
|
||||
['appearance-view', 'settings/appearance'],
|
||||
['notification-settings-view', 'settings/notifications'],
|
||||
['application-settings-view', 'settings/application'],
|
||||
['app-log-view', 'settings/app-log'],
|
||||
['pwa-diagnostics-view', 'settings/pwa-diagnostics'],
|
||||
['solana-users-init-view', 'settings/solana-users-init'],
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
|
||||
// Не обрезаем пароль: пробелы участвуют в формировании криптографических ключей.
|
||||
// Предупреждаем только при выборе НОВОГО пароля, а не при авторизации.
|
||||
export function confirmPasswordBoundarySpaces(password) {
|
||||
const value = String(password ?? '');
|
||||
const starts = /^\s/u.test(value);
|
||||
const ends = /\s$/u.test(value);
|
||||
if (!starts && !ends) return Promise.resolve(true);
|
||||
const where = starts && ends ? 'начинается и заканчивается пробелом'
|
||||
: starts ? 'начинается с пробела' : 'заканчивается пробелом';
|
||||
return confirmDialog({
|
||||
title: 'Пробел в пароле',
|
||||
text: `Ваш пароль ${where}. Такой пробел трудно заметить при следующем входе, но он является частью пароля и влияет на ключи доступа. Вы уверены, что хотите оставить его?`,
|
||||
confirmLabel: 'Да, оставить пароль',
|
||||
cancelLabel: 'Вернуться к паролю',
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Локальный выбор пользователя: каждый аккаунт подтверждает публичную историю отдельно
|
||||
// на каждом устройстве. Сервер и блокчейн не хранят этот переключатель.
|
||||
import { state } from '../state.js';
|
||||
import { getDevicePref, setDevicePref } from './device-prefs.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
|
||||
const PREFIX = 'showPublicHistoryWarning:';
|
||||
export const PUBLIC_HISTORY_REMEMBER_LABEL = 'Я понимаю, что публичные записи могут храниться навсегда, и согласен(на) не получать это предупреждение при будущих действиях на данном устройстве.';
|
||||
|
||||
function preferenceKey() {
|
||||
const login = String(state.session?.login || '').trim().toLowerCase();
|
||||
return login ? `${PREFIX}${login}` : null;
|
||||
}
|
||||
|
||||
export function getShowPublicHistoryWarning() {
|
||||
const key = preferenceKey();
|
||||
return key ? getDevicePref(key, true) !== false : true;
|
||||
}
|
||||
|
||||
export function setShowPublicHistoryWarning(show) {
|
||||
const key = preferenceKey();
|
||||
if (key) setDevicePref(key, Boolean(show));
|
||||
}
|
||||
|
||||
export function confirmPublicHistoryAction(options = {}) {
|
||||
if (!preferenceKey() || getShowPublicHistoryWarning()) {
|
||||
return confirmDialog({
|
||||
...options,
|
||||
rememberChoice: {
|
||||
label: PUBLIC_HISTORY_REMEMBER_LABEL,
|
||||
onConfirm: () => setShowPublicHistoryWarning(false),
|
||||
},
|
||||
});
|
||||
}
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
export const USER_PDA_SPACE = 768; // shine-solana/shine/programs/shine_users/src/settings.rs
|
||||
// Запас для предварительной проверки баланса; сеть списывает фактическую комиссию.
|
||||
export const REGISTRATION_NETWORK_RESERVE_LAMPORTS = 100_000n;
|
||||
export const UPGRADE_TEST_TOPUP_SOL = 0.02;
|
||||
export const UPGRADE_TEST_TOPUP_SOL = 0.032;
|
||||
export const LAMPORTS_PER_SOL = 1_000_000_000;
|
||||
|
||||
export function calculateRegistrationFunding({ namespaceFeeLamports, rentLamports }) {
|
||||
|
||||
Reference in New Issue
Block a user