Files
SHiNE-server/shine-UI/js/pages/user-profile-view.js
T

228 lines
8.9 KiB
JavaScript

import { renderHeader } from '../components/header.js';
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
import { renderUserAvatar } from '../components/avatar-image.js';
import { state } from '../state.js';
import { loadUserProfileCard } from '../services/user-connections.js';
import { makeProfileLinksRoute } from '../services/shine-routes.js';
import { navigateBack } from '../router.js';
export const pageMeta = { id: 'user', title: 'Профиль' };
function escapeHtml(text) {
return String(text || '')
.replaceAll('&', '&')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
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>`;
}
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 spiritualPathSheetHtml(card) {
return `<div class="user-profile-sheet-copy">${escapeHtml(card?.spiritualPath || 'Не заполнено')}</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>`;
}
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;
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 fullName = [card.firstName, card.lastName]
.map((value) => String(value || '').trim())
.filter(Boolean)
.join(' ');
const about = String(card.about || '').trim();
const title = header.querySelector('.page-title');
if (title) title.textContent = card.login;
body.innerHTML = `
${fullName ? `<div class="user-profile-full-name">${escapeHtml(fullName)}</div>` : ''}
<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>
${about ? `<div class="user-profile-about-inline">${escapeHtml(about)}</div>` : ''}
<div class="user-profile-channel-metrics${about ? ' has-about' : ''}">
${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-actions" aria-label="Действия с пользователем">
<button type="button" class="user-profile-action-btn" data-profile-action="add" aria-label="Добавить" title="Добавить">
${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="spiritual-path">Духовный путь</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,
}));
status.textContent = '';
}
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 === 'spiritual-path') {
openProfileSheet('Духовный путь', spiritualPathSheetHtml(card));
return;
}
if (detailButton?.dataset.profileDetail === 'contacts') {
openProfileSheet('Контакты', contactsSheetHtml(card));
return;
}
const actionButton = event.target.closest('[data-profile-action]');
const action = actionButton?.dataset.profileAction;
if (action === 'add') {
if (!selfLogin) {
status.className = 'status-line user-profile-status is-unavailable';
status.textContent = 'Для добавления пользователя необходимо войти.';
return;
}
navigate(`SHiNE/${encodeURIComponent(card.login)}/manage`);
return;
}
if (action === 'links') {
navigate(makeProfileLinksRoute(card.login));
return;
}
if (action === 'chat') {
navigate(`chat/${encodeURIComponent(card.login)}`);
}
});
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 = () => {
const root = document.getElementById('modal-root');
if (root?.querySelector('#user-profile-sheet-backdrop')) root.innerHTML = '';
};
return screen;
}