SHA256
- плитка «Добавить связь» показывает текущую связь («Друг ✓», «Близкий друг ✓», «Контакт ✓») или предлагает ответить – «Дружить в ответ» / «Добавить в ответ» с подписью «… хочет с вами дружить» / «… добавил(а) вас в контакты»; - загрузка – спиннер с задержкой вместо «Загрузка профиля...», ошибка – понятным текстом и «Повторить».
194 lines
8.1 KiB
JavaScript
194 lines
8.1 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 { 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: 'Профиль' };
|
|
|
|
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;
|
|
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,
|
|
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(''),
|
|
});
|
|
|
|
// Личная заметка – сразу под кнопками действий; видна только владельцу аккаунта.
|
|
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');
|
|
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 = 'добавил(а) вас в контакты'; }
|
|
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)}`);
|
|
}
|
|
});
|
|
|
|
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() {
|
|
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;
|
|
}
|