Обновить профиль пользователя

This commit is contained in:
2026-09-03 15:37:28 +03:00
parent 85d90a7f95
commit 023d61a1e9
+143 -126
View File
@@ -1,12 +1,9 @@
import { profile } from '../mock-data.js'; import { profile } from '../mock-data.js';
import { authService, state } from '../state.js'; import { state } from '../state.js';
import {
loadProfileSnapshot,
} from '../services/user-profile-params.js';
import { renderUserAvatar } from '../components/avatar-image.js'; import { renderUserAvatar } from '../components/avatar-image.js';
import { createOverflowDots } from '../components/overflow-dots.js'; import { createOverflowDots } from '../components/overflow-dots.js';
import { createDropdownMenu } from '../components/dropdown-menu.js'; import { createDropdownMenu } from '../components/dropdown-menu.js';
import { userDisplayName } from '../services/user-display.js'; import { loadUserProfileCard } from '../services/user-connections.js';
export const pageMeta = { id: 'profile-view', title: 'Профиль' }; export const pageMeta = { id: 'profile-view', title: 'Профиль' };
@@ -19,172 +16,194 @@ function escapeHtml(text) {
.replaceAll("'", '''); .replaceAll("'", ''');
} }
function fieldMap(snapshot) { function metricHtml({ kind, label, value, glow = false, positionClass = '' }) {
const out = {}; const numericValue = Number(value || 0);
(Array.isArray(snapshot?.fields) ? snapshot.fields : []).forEach((field) => { return `
out[String(field?.key || '').trim()] = String(field?.value || '').trim(); <button
}); type="button"
return out; class="user-profile-metric ${positionClass}${glow ? ' is-glowing' : ''}"
data-profile-list="${escapeHtml(kind)}"
aria-label="${escapeHtml(label)}: ${numericValue}"
>
<span class="user-profile-metric-circle">${numericValue}</span>
<span class="user-profile-metric-label">${escapeHtml(label)}</span>
</button>`;
} }
function openTextModal(title, text) { function spiritualPathDetailHtml(card) {
const root = document.getElementById('modal-root'); const value = String(card?.spiritualPath || '').trim();
if (!root) return; return `<div class="user-profile-detail-copy${value ? '' : ' is-muted'}">${escapeHtml(value || 'Не заполнено')}</div>`;
root.innerHTML = `
<div class="modal" id="profile-text-modal">
<div class="modal-card stack">
<h3>${escapeHtml(title)}</h3>
<div style="white-space:pre-wrap;line-height:1.5">${escapeHtml(text || 'Не заполнено')}</div>
<button class="secondary-btn" id="profile-text-close">Закрыть</button>
</div>
</div>`;
const close = () => { root.innerHTML = ''; };
root.querySelector('#profile-text-close')?.addEventListener('click', close);
root.querySelector('#profile-text-modal')?.addEventListener('click', (event) => {
if (event.target?.id === 'profile-text-modal') close();
});
} }
function statusBadges(accountRole, shineStatus) { function contactsDetailHtml(card) {
const role = accountRole === 'primary' ? 'Основной аккаунт' : accountRole === 'non_voting' ? 'Голос не учитывать' : ''; const rows = [
const shine = shineStatus === 'shining' ? 'Сияющий' : ''; ['Ссылки', card?.web],
return `<div class="row wrap-row"> ['Телефон', card?.phone],
${role ? `<span class="badge">${escapeHtml(role)}</span>` : ''} ['Адрес', card?.address],
${shine ? '<span class="badge is-yes-shine">Сияющий</span>' : ''} ].filter(([, value]) => String(value || '').trim());
${shineStatus === 'not_interested' ? '<span class="profile-shine-not-interested" title="Сияние неинтересно"><img src="/assets/shine-status-not-interested.svg" alt="Сияние неинтересно"></span>' : ''}
</div>`;
}
function statsRows(stats = {}) { if (!rows.length) {
return [ return '<div class="user-profile-detail-copy is-muted">Не заполнено</div>';
['friends', 'Друзья', stats.friendsCount], }
['close_friends', 'Близкие друзья', stats.closeFriendsCount], return rows.map(([label, value]) => `
['primary_received', 'Подтвердили основной аккаунт', stats.primaryReceivedCount], <div class="user-profile-contact-row">
['primary_given', 'Подтверждённые аккаунты', stats.primaryGivenCount], <span>${escapeHtml(label)}</span>
['shine_received', 'Считают сияющим', stats.shineReceivedCount], <b>${escapeHtml(value)}</b>
['shine_given', 'Подтверждённые сияющие', stats.shineGivenCount], </div>`).join('');
['channels_following', 'Подписки на каналы', stats.followingChannelsCount],
['channels_owned', 'Каналы', stats.ownedPublicChannelsCount],
];
} }
export function render({ navigate, chrome }) { export function render({ navigate, chrome }) {
const login = String(state.session.login || profile.login || '').trim(); const login = String(state.session.login || profile.login || '').trim();
const screen = document.createElement('section'); const screen = document.createElement('section');
screen.className = 'stack profile-screen'; screen.className = 'stack user-profile-screen';
const topbar = document.createElement('header'); const topbar = document.createElement('header');
topbar.className = 'page-header app-topbar-shell app-topbar-shell--profile'; topbar.className = 'page-header app-topbar-shell app-topbar-shell--profile user-profile-header';
topbar.innerHTML = ` topbar.innerHTML = `
<div class="header-left" aria-hidden="true"></div> <div class="header-left" aria-hidden="true"></div>
<div class="header-center"><h1 class="page-title">Профиль</h1></div> <div class="header-center"><h1 class="page-title">${escapeHtml(login || 'Профиль')}</h1></div>
<div class="header-actions profile-head-menu-wrap dm-head-menu-wrap"> <div class="header-actions profile-head-menu-wrap dm-head-menu-wrap">
<button type="button" class="dm-head-menu-btn profile-head-menu-btn" aria-label="Меню профиля" aria-haspopup="menu" aria-expanded="false"></button> <button type="button" class="dm-head-menu-btn profile-head-menu-btn" aria-label="Меню профиля" aria-haspopup="menu" aria-expanded="false"></button>
</div>`; </div>`;
const menuButton = topbar.querySelector('.profile-head-menu-btn'); const menuButton = topbar.querySelector('.profile-head-menu-btn');
menuButton?.append(createOverflowDots()); menuButton?.append(createOverflowDots());
const profileMenu = createDropdownMenu({ const profileMenu = createDropdownMenu({
anchorEl: menuButton, anchorEl: menuButton,
className: 'profile-head-menu', className: 'profile-head-menu',
minWidth: 230, minWidth: 250,
items: [ items: [
{ label: 'Редактировать профиль', iconSrc: '/assets/profile-icon-profile.svg', action: () => navigate('profile-edit-view') }, { label: 'Редактировать профиль', iconSrc: '/assets/profile-icon-profile.svg', action: () => navigate('profile-edit-view') },
{ label: 'Кошелёк', iconSrc: '/assets/profile-icon-wallet.svg', action: () => navigate('wallet-view') }, { label: 'Кошелёк', iconSrc: '/assets/profile-icon-wallet.svg', action: () => navigate('wallet-view') },
{ label: 'Настройки', iconSrc: '/assets/profile-icon-settings.svg', action: () => navigate('settings-view') }, { label: 'Настройки', iconSrc: '/assets/profile-icon-settings.svg', action: () => navigate('settings-view') },
{ label: 'Подтверждённые аккаунты', action: () => navigate(`SHiNE/${encodeURIComponent(login)}/list/primary_given`) },
{ label: 'Подтверждённые сияющие', action: () => navigate(`SHiNE/${encodeURIComponent(login)}/list/shine_given`) },
{ label: 'Сменить профиль', action: () => navigate('profiles-view') }, { label: 'Сменить профиль', action: () => navigate('profiles-view') },
], ],
}); });
chrome?.setTopbar(topbar); chrome?.setTopbar(topbar);
const status = document.createElement('div'); const status = document.createElement('div');
status.className = 'status-line'; status.className = 'status-line user-profile-status';
status.textContent = 'Загрузка профиля...'; status.textContent = 'Загрузка профиля...';
const body = document.createElement('div'); const body = document.createElement('div');
body.className = 'stack'; body.className = 'user-profile-body';
screen.append(status, body); screen.append(status, body);
let current = null; let card = null;
function renderProfile() { function renderProfile() {
if (!current) return; if (!card) return;
const { snapshot, user } = current; const stats = card.stats || {};
const fields = fieldMap(snapshot); const official = card.accountRole === 'primary';
const firstName = fields.first_name || ''; const shining = card.shineStatus === 'shining';
const lastName = fields.last_name || ''; const fullName = [card.firstName, card.lastName]
const displayName = userDisplayName({ login, firstName, lastName }); .map((value) => String(value || '').trim())
const avatar = snapshot?.avatar?.txId .filter(Boolean)
? { ar: String(snapshot.avatar.txId).trim(), sha256Hex: String(snapshot?.avatar?.sha256Hex || '').trim().toLowerCase() } .join(' ');
: null; const about = String(card.about || '').trim();
const stats = {
ownedPublicChannelsCount: Number(user?.ownedPublicChannelsCount || 0),
followingChannelsCount: Number(user?.followingChannelsCount || 0),
friendsCount: Number(user?.friendsCount || 0),
closeFriendsCount: Number(user?.closeFriendsCount || 0),
primaryReceivedCount: Number(user?.primaryConfirmationsReceivedCount || 0),
primaryGivenCount: Number(user?.primaryConfirmationsGivenCount || 0),
shineReceivedCount: Number(user?.shineConfirmationsReceivedCount || 0),
shineGivenCount: Number(user?.shineConfirmationsGivenCount || 0),
};
body.innerHTML = ''; const title = topbar.querySelector('.page-title');
const identity = document.createElement('div'); if (title) title.textContent = card.login || login || 'Профиль';
identity.className = 'card row';
identity.style.gap = '12px';
identity.style.alignItems = 'center';
identity.append(renderUserAvatar({ login, firstName, lastName, avatar, size: 'xl', className: 'profile-avatar' }));
const identityText = document.createElement('div');
identityText.innerHTML = `<div class="profile-identity-line">${escapeHtml(displayName)}</div><div class="profile-identity-login">${escapeHtml(login)}</div>`;
identity.append(identityText);
body.append(identity);
const badges = document.createElement('div'); body.innerHTML = `
badges.innerHTML = statusBadges(String(snapshot?.accountRole || '').trim().toLowerCase(), String(snapshot?.shineStatus || '').trim().toLowerCase()); ${fullName ? `<div class="user-profile-full-name">${escapeHtml(fullName)}</div>` : ''}
body.append(...badges.children);
if (fields.about) { <div class="user-profile-hero" aria-label="Профиль ${escapeHtml(card.login)}">
const about = document.createElement('div'); ${metricHtml({ kind: 'primary_received', label: 'Официальный', value: stats.primaryReceivedCount, glow: official, positionClass: 'is-top-left' })}
about.className = 'card profile-about'; ${metricHtml({ kind: 'shine_received', label: 'Сияющий', value: stats.shineReceivedCount, glow: shining, positionClass: 'is-top-right' })}
about.style.whiteSpace = 'pre-wrap'; <div class="user-profile-avatar-slot"></div>
about.textContent = fields.about; ${metricHtml({ kind: 'friends', label: 'Друзья', value: stats.friendsCount, positionClass: 'is-bottom-left' })}
body.append(about); ${metricHtml({ kind: 'close_friends', label: 'Близкие друзья', value: stats.closeFriendsCount, positionClass: 'is-bottom-right' })}
} </div>
const statsGrid = document.createElement('div'); ${about ? `<div class="user-profile-about-inline">${escapeHtml(about)}</div>` : ''}
statsGrid.className = 'profile-stats-grid';
statsRows(stats).forEach(([kind, label, value]) => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'card profile-stat-card';
button.dataset.profileList = kind;
button.innerHTML = `<b>${Number(value || 0)}</b><span>${escapeHtml(label)}</span>`;
statsGrid.append(button);
});
body.append(statsGrid);
const detailRow = document.createElement('div'); <div class="user-profile-channel-metrics">
detailRow.className = 'row wrap-row'; ${metricHtml({ kind: 'channels_following', label: 'Подписки', value: stats.followingChannelsCount, positionClass: 'is-channel-metric' })}
detailRow.innerHTML = '<button class="secondary-btn" data-profile-detail="contacts">Контакты</button><button class="secondary-btn" data-profile-detail="spiritual">Духовный путь</button>'; ${metricHtml({ kind: 'channels_owned', label: 'Каналы', value: stats.ownedPublicChannelsCount, positionClass: 'is-channel-metric' })}
body.append(detailRow); </div>
<div class="user-profile-actions-wrap">
<div class="user-profile-actions" aria-label="Действия со своим профилем">
<button type="button" class="user-profile-action-btn" data-self-profile-action="edit" aria-label="Редактировать профиль" title="Редактировать профиль">
<img src="/assets/profile-icon-profile.svg" alt="" aria-hidden="true">
</button>
<button type="button" class="user-profile-action-btn" data-self-profile-action="wallet" aria-label="Кошелёк" title="Кошелёк">
<img src="/assets/profile-icon-wallet.svg" alt="" aria-hidden="true">
</button>
<button type="button" class="user-profile-action-btn" data-self-profile-action="settings" aria-label="Настройки" title="Настройки">
<img src="/assets/profile-icon-settings.svg" alt="" aria-hidden="true">
</button>
</div>
</div>
<div class="user-profile-detail-links" aria-label="Дополнительная информация о профиле">
<button type="button" data-profile-detail="spiritual-path" aria-pressed="false" aria-controls="profile-view-detail-panel">
<span class="user-profile-detail-tab-label">Духовный путь</span>
</button>
<button type="button" data-profile-detail="contacts" aria-pressed="false" aria-controls="profile-view-detail-panel">
<span class="user-profile-detail-tab-label">Контакты</span>
</button>
</div>
<section class="user-profile-detail-panel" id="profile-view-detail-panel" aria-live="polite" hidden></section>`;
const avatarSlot = body.querySelector('.user-profile-avatar-slot');
avatarSlot?.append(renderUserAvatar({
login: card.login,
firstName: card.firstName,
lastName: card.lastName,
avatar: card.avatar,
size: 'xl',
className: 'user-profile-hero-avatar',
glow: shining,
}));
status.textContent = '';
} }
body.addEventListener('click', (event) => { body.addEventListener('click', (event) => {
if (!current) return; if (!card) return;
const el = event.target.closest('[data-profile-list],[data-profile-detail]');
if (!el) return; const listButton = event.target.closest('[data-profile-list]');
const kind = el.dataset.profileList; if (listButton) {
if (kind) { const kind = listButton.dataset.profileList;
navigate(`SHiNE/${encodeURIComponent(login)}/list/${encodeURIComponent(kind)}`); if (kind) navigate(`SHiNE/${encodeURIComponent(card.login)}/list/${encodeURIComponent(kind)}`);
return; return;
} }
const fields = fieldMap(current.snapshot);
if (el.dataset.profileDetail === 'contacts') { const actionButton = event.target.closest('[data-self-profile-action]');
openTextModal('Контакты', [ if (actionButton) {
fields.web ? `Links: ${fields.web}` : '', const action = actionButton.dataset.selfProfileAction;
fields.phone ? `Телефон: ${fields.phone}` : '', if (action === 'edit') navigate('profile-edit-view');
fields.address ? `Адрес: ${fields.address}` : '', if (action === 'wallet') navigate('wallet-view');
].filter(Boolean).join('\n') || 'Не заполнено'); if (action === 'settings') navigate('settings-view');
return;
} }
if (el.dataset.profileDetail === 'spiritual') openTextModal('Духовный путь', fields.spiritual_path);
const detailButton = event.target.closest('[data-profile-detail]');
if (!detailButton) return;
const detailKind = detailButton.dataset.profileDetail;
const detailPanel = body.querySelector('#profile-view-detail-panel');
if (!detailPanel) return;
body.querySelectorAll('[data-profile-detail]').forEach((button) => {
const active = button === detailButton;
button.classList.toggle('is-active', active);
button.setAttribute('aria-pressed', active ? 'true' : 'false');
});
if (detailKind === 'spiritual-path') {
detailPanel.innerHTML = spiritualPathDetailHtml(card);
} else if (detailKind === 'contacts') {
detailPanel.innerHTML = contactsDetailHtml(card);
} else {
return;
}
detailPanel.hidden = false;
detailPanel.dataset.activeDetail = detailKind;
}); });
async function refresh() { async function refresh() {
@@ -192,14 +211,12 @@ export function render({ navigate, chrome }) {
status.textContent = 'Локальный тестовый режим.'; status.textContent = 'Локальный тестовый режим.';
return; return;
} }
const [snapshot, user] = await Promise.all([loadProfileSnapshot(login), authService.getUser(login)]); card = await loadUserProfileCard(login);
current = { snapshot, user };
renderProfile(); renderProfile();
status.textContent = '';
} }
refresh().catch((error) => { refresh().catch((error) => {
status.className = 'status-line is-unavailable'; status.className = 'status-line user-profile-status is-unavailable';
status.textContent = `Ошибка: ${error?.message || 'unknown'}`; status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
}); });