Files
SHiNE-server/shine-UI/js/pages/user-profile-view.js
q 6997bc7600 Уведомления: «Добавила вас в друзья» вместо «Добавил(а)»
Если в профиле автора указан пол, глагол в уведомлениях о связях и подписках
согласуется с ним («Добавила вас в друзья», «Подписался на ваш канал»); пока профиль не
пришёл или пол не указан – прежнее нейтральное «Добавил(а)». То же в подсказке на чужом
профиле («добавила вас в контакты»).
2026-10-13 08:57:07 +03:00

197 lines
8.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
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 = `${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)}`);
}
});
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;
}