SHA256
169 lines
6.6 KiB
JavaScript
169 lines
6.6 KiB
JavaScript
import { createTopBar } from '../components/topbar.js';
|
||
import { SHINE_CONNECTIONS_LOGO_SRC } from '../components/shine-logo.js';
|
||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||
import { state } from '../state.js';
|
||
import { loadRelationsForPair, loadUserProfileCard } from '../services/user-connections.js';
|
||
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
||
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 { iconHtml } from '../components/ui-icon.js';
|
||
|
||
export const pageMeta = { id: 'user', title: 'Профиль' };
|
||
|
||
function escapeHtml(text) {
|
||
return String(text || '')
|
||
.replaceAll('&', '&')
|
||
.replaceAll('<', '<')
|
||
.replaceAll('>', '>')
|
||
.replaceAll('"', '"')
|
||
.replaceAll("'", ''');
|
||
}
|
||
|
||
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 = createTopBar({
|
||
title: 'Профиль',
|
||
back: { label: '←', onClick: () => navigateBack() },
|
||
});
|
||
header.classList.add('user-profile-header');
|
||
chrome?.setTopbar(header);
|
||
|
||
const status = document.createElement('div');
|
||
status.className = 'user-profile-status';
|
||
status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
||
|
||
const body = document.createElement('div');
|
||
body.className = 'user-profile-body';
|
||
screen.append(status, body);
|
||
|
||
let card = null;
|
||
let disposed = false;
|
||
function renderProfile() {
|
||
if (!card || disposed) return;
|
||
const isSelf = card.login.toLowerCase() === selfLogin.toLowerCase();
|
||
|
||
body.innerHTML = profileCardHtml({
|
||
card,
|
||
login: requestedLogin,
|
||
isSelf,
|
||
tilesHtml: isSelf ? '' : [
|
||
profileTileHtml({ icon: 'user-plus', label: 'Добавить связь', attrs: 'data-profile-action="add"' }),
|
||
profileTileHtml({ label: 'Связи', attrs: 'data-profile-action="links"', iconMarkup: `<img class="pf-tile-mandala" src="${SHINE_CONNECTIONS_LOGO_SRC}" alt="" aria-hidden="true">` }),
|
||
profileTileHtml({ icon: 'message', label: 'Написать', attrs: 'data-profile-action="chat"' }),
|
||
].join(''),
|
||
});
|
||
|
||
syncRelationTile();
|
||
|
||
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',
|
||
official: card.accountRole === 'primary',
|
||
}));
|
||
|
||
status.replaceChildren();
|
||
}
|
||
|
||
// Плитка показывает текущую связь («Друг ✓») или предлагает ответить, если человек
|
||
// добавил вас первым; нажатие – как раньше, в управление связью.
|
||
function syncRelationTile() {
|
||
const tile = body.querySelector('[data-profile-action="add"]');
|
||
if (!tile || !relation) return;
|
||
const r = relation;
|
||
const theyFriend = r.inFriend || r.inCloseFriend;
|
||
let icon = 'user-plus';
|
||
let label = 'Добавить связь';
|
||
let hint = '';
|
||
if (r.outCloseFriend) { icon = 'check'; label = 'Близкий друг'; }
|
||
else if (r.outFriend) { icon = 'check'; label = 'Друг'; }
|
||
else if (r.outContact) { icon = 'check'; label = 'Контакт'; }
|
||
else if (theyFriend) { label = 'Дружить в ответ'; hint = 'хочет с вами дружить'; }
|
||
else if (r.inContact) {
|
||
label = 'Добавить в ответ';
|
||
hint = `${card.gender === 'female' ? 'добавила' : card.gender === 'male' ? 'добавил' : 'добавил(а)'} вас в контакты`;
|
||
}
|
||
tile.innerHTML = `${iconHtml(icon)}<span></span>`;
|
||
tile.querySelector('span').textContent = label;
|
||
tile.classList.toggle('is-related', icon === 'check');
|
||
tile.setAttribute('aria-label', icon === 'check' ? `${label}. Изменить связь` : label);
|
||
body.querySelector('.user-profile-relation-hint')?.remove();
|
||
if (hint) {
|
||
const note = document.createElement('p');
|
||
note.className = 'user-profile-relation-hint';
|
||
note.textContent = `${[card.firstName, card.lastName].map((v) => String(v || '').trim()).filter(Boolean).join(' ') || card.login} ${hint}`;
|
||
body.querySelector('.pf-tiles-wrap')?.before(note);
|
||
}
|
||
}
|
||
|
||
body.addEventListener('click', (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 actionButton = event.target.closest('[data-profile-action]');
|
||
const action = actionButton?.dataset.profileAction;
|
||
if (action === 'add') {
|
||
navigate(`SHiNE/${encodeURIComponent(card.login)}/manage`);
|
||
return;
|
||
}
|
||
if (action === 'links') {
|
||
navigate(makeProfileLinksRoute(card.login));
|
||
return;
|
||
}
|
||
if (action === 'chat') {
|
||
navigate(`chat/${encodeURIComponent(card.login)}`);
|
||
}
|
||
});
|
||
|
||
screen.cleanup = () => {
|
||
if (disposed) return;
|
||
disposed = true;
|
||
};
|
||
|
||
async function refresh() {
|
||
const loaded = await loadUserProfileCard(requestedLogin);
|
||
if (disposed) return;
|
||
card = loaded;
|
||
renderProfile();
|
||
if (selfLogin && card.login.toLowerCase() !== selfLogin.toLowerCase()) {
|
||
loadRelationsForPair({ currentLogin: selfLogin, targetLogin: card.login })
|
||
.then((flags) => {
|
||
if (disposed) return;
|
||
relation = flags;
|
||
syncRelationTile();
|
||
})
|
||
.catch(() => { /* без сведений о связи плитка остаётся «Добавить связь» */ });
|
||
}
|
||
}
|
||
|
||
const showLoadError = (error) => {
|
||
if (disposed) return;
|
||
status.replaceChildren(createErrorState({
|
||
title: 'Не удалось загрузить профиль',
|
||
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
||
onRetry: () => {
|
||
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
||
refresh().catch(showLoadError);
|
||
},
|
||
}));
|
||
};
|
||
refresh().catch(showLoadError);
|
||
|
||
return screen;
|
||
}
|