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

This commit is contained in:
2026-09-02 11:43:47 +03:00
parent 58b564b385
commit 822a72e246
2 changed files with 1021 additions and 45 deletions
+329 -43
View File
@@ -1,56 +1,342 @@
import { renderHeader } from '../components/header.js';
import { state } from '../state.js';
import { loadUserProfileCard } from '../services/user-connections.js';
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
import { renderUserAvatar } from '../components/avatar-image.js';
import { authService, state } from '../state.js';
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
import { makeProfileLinksRoute } from '../services/shine-routes.js';
import { navigateBack } from '../router.js';
export const pageMeta = { id: 'user', title: 'Профиль пользователя' };
export const pageMeta = { id: 'user', title: 'Профиль' };
function escapeHtml(text){return String(text||'').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');}
function fullName(card){return [card.firstName,card.lastName].filter(Boolean).join(' ')||card.login;}
function openTextModal(title,text){
const root=document.getElementById('modal-root'); if(!root)return;
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',e=>{if(e.target?.id==='profile-text-modal')close();});
function escapeHtml(text) {
return String(text || '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
function statusBadges(card){
const role=card.accountRole==='primary'?'Основной аккаунт':card.accountRole==='non_voting'?'Голос не учитывать':'';
const shine=card.shineStatus==='shining'?'Сияющий':'';
return `<div class="row wrap-row">${role?`<span class="badge">${escapeHtml(role)}</span>`:''}${shine?'<span class="badge is-yes-shine">Сияющий</span>':''}${card.shineStatus==='not_interested'?'<span class="profile-shine-not-interested" title="Сияние неинтересно"><img src="/assets/shine-status-not-interested.svg" alt="Сияние неинтересно"></span>':''}</div>`;
function effectiveSocial(flags = {}) {
if (flags.outCloseFriend) return 'close_friend';
if (flags.outFriend) return 'friend';
if (flags.outContact) return 'contact';
return 'none';
}
function statsHtml(card){
const s=card.stats||{};
const rows=[
['friends','Друзья',s.friendsCount],['close_friends','Близкие друзья',s.closeFriendsCount],
['primary_received','Подтвердили основной аккаунт',s.primaryReceivedCount],['primary_given','Подтверждённые аккаунты',s.primaryGivenCount],
['shine_received','Считают сияющим',s.shineReceivedCount],['shine_given','Подтверждённые сияющие',s.shineGivenCount],
['channels_following','Подписки на каналы',s.followingChannelsCount],['channels_owned','Каналы',s.ownedPublicChannelsCount],
];
return `<div class="profile-stats-grid">${rows.map(([kind,label,n])=>`<button type="button" class="card profile-stat-card" data-profile-list="${kind}"><b>${Number(n||0)}</b><span>${escapeHtml(label)}</span></button>`).join('')}</div>`;
function metricHtml({ kind, label, value, glow = false, positionClass = '' }) {
const numericValue = Number(value || 0);
return `
<button
type="button"
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>`;
}
export function render({navigate,route}){
const requestedLogin=String(route?.params?.login||'').trim(); const selfLogin=String(state.session.login||'').trim();
const screen=document.createElement('section'); screen.className='stack'; const body=document.createElement('div');body.className='stack';const status=document.createElement('div');status.className='status-line';status.textContent='Загрузка профиля...';
screen.append(renderHeader({title:'Профиль пользователя',leftAction:{label:'←',onClick:()=>navigateBack()}}),status,body);
let card=null;
async function refresh(){
card=await loadUserProfileCard(requestedLogin); const isSelf=card.login.toLowerCase()===selfLogin.toLowerCase();
body.innerHTML=`${statusBadges(card)}<div class="card profile-about" style="white-space:pre-wrap">${escapeHtml(card.about||'')}</div>${statsHtml(card)}
<div class="row wrap-row"><button class="secondary-btn" data-profile-detail="contacts">Контакты</button><button class="secondary-btn" data-profile-detail="spiritual">Духовный путь</button></div>
${!isSelf?`<div class="row profile-bottom-actions"><button class="icon-btn" data-bottom="chat" title="Диалог">💬</button><button class="icon-btn" data-bottom="links" title="Связи">✦</button><button class="primary-btn" data-bottom="add">Добавить</button></div>`:''}`;
const identity=document.createElement('div');identity.className='card row';identity.style.gap='12px';identity.style.alignItems='center';
identity.append(renderUserAvatar({login:card.login,firstName:card.firstName,lastName:card.lastName,avatar:card.avatar,size:'xl',className:'profile-avatar'}));
const txt=document.createElement('div');txt.innerHTML=`<div class="profile-identity-line">${escapeHtml(fullName(card))}</div><div class="profile-identity-login">${escapeHtml(card.login)}</div>`;identity.append(txt);body.prepend(identity);status.textContent='';
}
body.addEventListener('click',e=>{const el=e.target.closest('[data-profile-list],[data-profile-detail],[data-bottom]');if(!el||!card)return;
const list=el.dataset.profileList;if(list){navigate(`SHiNE/${encodeURIComponent(card.login)}/list/${encodeURIComponent(list)}`);return;}
const detail=el.dataset.profileDetail;if(detail==='contacts'){openTextModal('Контакты',[card.web?`Links: ${card.web}`:'',card.phone?`Телефон: ${card.phone}`:'',card.address?`Адрес: ${card.address}`:''].filter(Boolean).join('\n')||'Не заполнено');return;} if(detail==='spiritual'){openTextModal('Духовный путь',card.spiritualPath);return;}
const bottom=el.dataset.bottom;if(bottom==='chat')navigate(`chat/${encodeURIComponent(card.login)}`);if(bottom==='links')navigate(makeProfileLinksRoute(card.login));if(bottom==='add')navigate(`SHiNE/${encodeURIComponent(card.login)}/manage`);
});
refresh().catch(e=>{status.className='status-line is-unavailable';status.textContent=`Ошибка: ${e.message||'unknown'}`;}); return screen;
function openProfileSheet(title, html) {
const root = document.getElementById('modal-root');
if (!root) return;
root.innerHTML = `
<div class="user-profile-sheet-backdrop" id="user-profile-sheet-backdrop">
<section class="user-profile-sheet" role="dialog" aria-modal="true" aria-label="${escapeHtml(title)}">
<div class="user-profile-sheet-handle" aria-hidden="true"></div>
<div class="user-profile-sheet-title">${escapeHtml(title)}</div>
<div class="user-profile-sheet-content">${html}</div>
</section>
</div>`;
const close = () => {
if (root.querySelector('#user-profile-sheet-backdrop')) root.innerHTML = '';
};
root.querySelector('#user-profile-sheet-backdrop')?.addEventListener('click', (event) => {
if (event.target?.id === 'user-profile-sheet-backdrop') close();
});
}
function aboutSheetHtml(card) {
return `<div class="user-profile-sheet-copy">${escapeHtml(card?.about || 'Не заполнено')}</div>`;
}
function contactsSheetHtml(card) {
const rows = [
['Ссылки', card?.web],
['Телефон', card?.phone],
['Адрес', card?.address],
].filter(([, value]) => String(value || '').trim());
if (!rows.length) {
return '<div class="user-profile-sheet-copy is-muted">Не заполнено</div>';
}
return rows.map(([label, value]) => `
<div class="user-profile-contact-row">
<span>${escapeHtml(label)}</span>
<b>${escapeHtml(value)}</b>
</div>`).join('');
}
function addIconHtml() {
return `
<svg class="user-profile-action-svg" viewBox="0 0 40 40" aria-hidden="true">
<path d="M10.5 20.5 17 27l13-14" />
</svg>`;
}
function relationMenuHtml(flags = {}) {
const current = effectiveSocial(flags);
const rows = [
['friend', 'Друг'],
['close_friend', 'Близкий друг'],
['contact', 'Контакт'],
];
return rows.map(([kind, label]) => `
<button type="button" class="user-profile-add-option${current === kind ? ' is-current' : ''}" data-relation-kind="${kind}">
<span>${escapeHtml(label)}</span>
<span class="user-profile-add-option-check" aria-hidden="true">${current === kind ? '✓' : ''}</span>
</button>`).join('');
}
export function render({ navigate, route, chrome }) {
const requestedLogin = String(route?.params?.login || '').trim();
const selfLogin = String(state.session.login || '').trim();
const screen = document.createElement('section');
screen.className = 'stack user-profile-screen';
const header = renderHeader({
title: requestedLogin || 'Профиль',
leftAction: { label: '←', onClick: () => navigateBack() },
});
header.classList.add('user-profile-header');
chrome?.setTopbar(header);
const status = document.createElement('div');
status.className = 'status-line user-profile-status';
status.textContent = 'Загрузка профиля...';
const body = document.createElement('div');
body.className = 'user-profile-body';
screen.append(status, body);
let card = null;
let relationFlags = null;
let relationLoadPromise = null;
let addMenu = null;
let addActionButton = null;
function updateRelationUi() {
if (!addMenu) return;
addMenu.innerHTML = relationMenuHtml(relationFlags || {});
const social = effectiveSocial(relationFlags || {});
addActionButton?.classList.toggle('is-active', social !== 'none');
addActionButton?.setAttribute('aria-label', social === 'none' ? 'Добавить' : 'Изменить связь');
}
async function ensureRelationFlags() {
if (relationFlags) return relationFlags;
if (relationLoadPromise) return relationLoadPromise;
if (!selfLogin || !card?.login) return {};
relationLoadPromise = loadRelationsForPair({ currentLogin: selfLogin, targetLogin: card.login })
.then((flags) => {
relationFlags = flags || {};
updateRelationUi();
return relationFlags;
})
.finally(() => {
relationLoadPromise = null;
});
return relationLoadPromise;
}
async function setRelationKind(kind, enabled) {
await authService.setUserRelation({
login: selfLogin,
toLogin: card.login,
kind,
enabled,
storagePwd: state.session.storagePwdInMemory,
});
}
async function changeSocial(next) {
const flags = await ensureRelationFlags();
const current = effectiveSocial(flags);
if (current === next) return;
if (next === 'contact') {
if (flags.outCloseFriend) await setRelationKind('close_friend', false);
if (flags.outFriend) await setRelationKind('friend', false);
if (!flags.outContact) await setRelationKind('contact', true);
}
if (next === 'friend') {
if (flags.outCloseFriend) await setRelationKind('close_friend', false);
if (!flags.outFriend) await setRelationKind('friend', true);
}
if (next === 'close_friend' && !flags.outCloseFriend) {
await setRelationKind('close_friend', true);
}
relationFlags = await loadRelationsForPair({ currentLogin: selfLogin, targetLogin: card.login });
updateRelationUi();
}
function renderProfile() {
if (!card) return;
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
const stats = card.stats || {};
const official = card.accountRole === 'primary';
const shining = card.shineStatus === 'shining';
const title = header.querySelector('.page-title');
if (title) title.textContent = card.login;
body.innerHTML = `
<div class="user-profile-hero" aria-label="Профиль ${escapeHtml(card.login)}">
${metricHtml({ kind: 'primary_received', label: 'Официальный', value: stats.primaryReceivedCount, glow: official, positionClass: 'is-top-left' })}
${metricHtml({ kind: 'shine_received', label: 'Сияющий', value: stats.shineReceivedCount, glow: shining, positionClass: 'is-top-right' })}
<div class="user-profile-avatar-slot"></div>
${metricHtml({ kind: 'friends', label: 'Друзья', value: stats.friendsCount, positionClass: 'is-bottom-left' })}
${metricHtml({ kind: 'close_friends', label: 'Близкие друзья', value: stats.closeFriendsCount, positionClass: 'is-bottom-right' })}
</div>
<div class="user-profile-channel-metrics">
${metricHtml({ kind: 'channels_following', label: 'Подписки', value: stats.followingChannelsCount, positionClass: 'is-channel-metric' })}
${metricHtml({ kind: 'channels_owned', label: 'Каналы', value: stats.ownedPublicChannelsCount, positionClass: 'is-channel-metric' })}
</div>
${!isSelf ? `
<div class="user-profile-actions-wrap">
<div class="user-profile-add-menu" hidden></div>
<div class="user-profile-actions" aria-label="Действия с пользователем">
<button type="button" class="user-profile-action-btn" data-profile-action="add" aria-label="Добавить" aria-haspopup="menu" aria-expanded="false">
${addIconHtml()}
</button>
<button type="button" class="user-profile-action-btn is-links" data-profile-action="links" aria-label="Связи" title="Связи">
<img src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true">
</button>
<button type="button" class="user-profile-action-btn" data-profile-action="chat" aria-label="Сообщение" title="Сообщение">
<img src="/assets/icon_lichnye.png" alt="" aria-hidden="true">
</button>
</div>
</div>` : ''}
<div class="user-profile-detail-links">
<button type="button" data-profile-detail="about">О себе</button>
<button type="button" data-profile-detail="contacts">Контакты</button>
</div>`;
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,
}));
addMenu = body.querySelector('.user-profile-add-menu');
addActionButton = body.querySelector('[data-profile-action="add"]');
updateRelationUi();
status.textContent = '';
if (!isSelf && selfLogin) {
void ensureRelationFlags().catch(() => {});
}
}
body.addEventListener('click', async (event) => {
if (!card) return;
const listButton = event.target.closest('[data-profile-list]');
if (listButton) {
const kind = listButton.dataset.profileList;
if (kind) navigate(`SHiNE/${encodeURIComponent(card.login)}/list/${encodeURIComponent(kind)}`);
return;
}
const detailButton = event.target.closest('[data-profile-detail]');
if (detailButton?.dataset.profileDetail === 'about') {
openProfileSheet('О себе', aboutSheetHtml(card));
return;
}
if (detailButton?.dataset.profileDetail === 'contacts') {
openProfileSheet('Контакты', contactsSheetHtml(card));
return;
}
const relationButton = event.target.closest('[data-relation-kind]');
if (relationButton) {
if (!selfLogin) {
status.className = 'status-line user-profile-status is-unavailable';
status.textContent = 'Для добавления пользователя необходимо войти.';
return;
}
const next = relationButton.dataset.relationKind;
try {
addMenu?.classList.add('is-busy');
await changeSocial(next);
if (addMenu) addMenu.hidden = true;
addActionButton?.setAttribute('aria-expanded', 'false');
status.className = 'status-line user-profile-status';
status.textContent = '';
} catch (error) {
status.className = 'status-line user-profile-status is-unavailable';
status.textContent = `Ошибка: ${error?.message || 'Не удалось изменить связь'}`;
} finally {
addMenu?.classList.remove('is-busy');
}
return;
}
const actionButton = event.target.closest('[data-profile-action]');
const action = actionButton?.dataset.profileAction;
if (action === 'add') {
if (!addMenu) return;
const willOpen = addMenu.hidden;
addMenu.hidden = !willOpen;
actionButton.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
if (willOpen && selfLogin) void ensureRelationFlags().catch(() => {});
return;
}
if (action === 'links') {
navigate(makeProfileLinksRoute(card.login));
return;
}
if (action === 'chat') {
navigate(`chat/${encodeURIComponent(card.login)}`);
}
});
const handleOutsidePointer = (event) => {
if (!addMenu || addMenu.hidden) return;
if (event.target instanceof Node && body.contains(event.target)) {
const insideActions = event.target.closest?.('.user-profile-actions-wrap');
if (insideActions) return;
}
addMenu.hidden = true;
addActionButton?.setAttribute('aria-expanded', 'false');
};
document.addEventListener('pointerdown', handleOutsidePointer);
async function refresh() {
card = await loadUserProfileCard(requestedLogin);
renderProfile();
}
refresh().catch((error) => {
status.className = 'status-line user-profile-status is-unavailable';
status.textContent = `Ошибка: ${error?.message || 'unknown'}`;
});
screen.cleanup = () => {
document.removeEventListener('pointerdown', handleOutsidePointer);
const root = document.getElementById('modal-root');
if (root?.querySelector('#user-profile-sheet-backdrop')) root.innerHTML = '';
};
return screen;
}