SHA256
130 lines
5.6 KiB
JavaScript
130 lines
5.6 KiB
JavaScript
import { profile } from '../mock-data.js';
|
|
import { state } from '../state.js';
|
|
import { renderUserAvatar } from '../components/avatar-image.js';
|
|
import { createTopBar } from '../components/topbar.js';
|
|
import { loadUserProfileCard } from '../services/user-connections.js';
|
|
import { profileCardHtml, profileTileHtml } from '../components/profile-card.js';
|
|
import { openShareSheet } from '../components/share-sheet.js';
|
|
import { createErrorState, createLoadingState } from '../components/feedback.js';
|
|
import { makeSharedProfileRoute } from '../services/shine-routes.js';
|
|
import { toUserMessage } from '../services/ui-error-texts.js';
|
|
|
|
export const pageMeta = { id: 'profile-view', title: 'Профиль' };
|
|
|
|
// Последняя загруженная карточка своего профиля: при повторном заходе показываем её сразу и тихо обновляем.
|
|
const cardCache = new Map();
|
|
|
|
export function render({ navigate, chrome }) {
|
|
const login = String(state.session.login || profile.login || '').trim();
|
|
const screen = document.createElement('section');
|
|
screen.className = 'stack user-profile-screen';
|
|
|
|
// Ссылка на свой профиль – самое частое «поделиться» в соцсети.
|
|
const shareProfile = () => {
|
|
const url = new URL(window.location.href);
|
|
url.pathname = `/${makeSharedProfileRoute(login)}`;
|
|
url.search = '';
|
|
url.hash = '';
|
|
const name = [card?.firstName, card?.lastName].map((part) => String(part || '').trim()).filter(Boolean).join(' ');
|
|
openShareSheet({ title: 'Поделиться профилем', kicker: name ? `${name} · ${login}` : login, text: 'Профиль в Сиянии', url: url.toString() });
|
|
};
|
|
const topbar = createTopBar({
|
|
title: 'Профиль',
|
|
className: 'topbar--root user-profile-header',
|
|
actions: [{ icon: 'share', title: 'Поделиться профилем', ariaLabel: 'Поделиться профилем', className: 'profile-share-btn', onClick: shareProfile }],
|
|
});
|
|
chrome?.setTopbar(topbar);
|
|
|
|
const status = document.createElement('div');
|
|
status.className = 'user-profile-status';
|
|
let card = cardCache.get(login.toLowerCase()) || null;
|
|
// Первый заход – спиннер, но только если профиль грузится заметно долго.
|
|
if (!card) status.append(createLoadingState({ label: 'Загружаю профиль' }));
|
|
|
|
const body = document.createElement('div');
|
|
body.className = 'user-profile-body';
|
|
screen.append(status, body);
|
|
|
|
function renderProfile() {
|
|
if (!card) return;
|
|
body.innerHTML = profileCardHtml({
|
|
card,
|
|
login,
|
|
tilesHtml: [
|
|
profileTileHtml({ icon: 'edit', label: 'Редактировать', attrs: 'data-self-profile-action="edit"' }),
|
|
profileTileHtml({ icon: 'wallet', label: 'Кошелёк', attrs: 'data-self-profile-action="wallet"' }),
|
|
profileTileHtml({ icon: 'settings', label: 'Настройки', attrs: 'data-self-profile-action="settings"' }),
|
|
].join(''),
|
|
}) + `
|
|
<div class="nav-list profile-more-list">
|
|
<button class="nav-row" type="button" data-self-profile-action="profiles"><span class="nav-row__label">Сменить профиль</span><span class="nav-row__hint">Другие аккаунты на этом устройстве</span></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',
|
|
official: card.accountRole === 'primary',
|
|
}));
|
|
|
|
status.replaceChildren();
|
|
}
|
|
|
|
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-self-profile-action]');
|
|
if (actionButton) {
|
|
const action = actionButton.dataset.selfProfileAction;
|
|
if (action === 'edit') navigate('profile-edit-view');
|
|
if (action === 'wallet') navigate('wallet-view');
|
|
if (action === 'settings') navigate('settings-view');
|
|
if (action === 'profiles') navigate('profiles-view');
|
|
return;
|
|
}
|
|
|
|
});
|
|
|
|
async function refresh() {
|
|
if (state.session.isLocalDemo) {
|
|
status.textContent = 'Локальный тестовый режим.';
|
|
return;
|
|
}
|
|
const fresh = await loadUserProfileCard(login);
|
|
if (!screen.isConnected && card) return;
|
|
// Та же карточка – не перерисовываем, иначе аватар и счётчики мигают.
|
|
if (card && JSON.stringify(card) === JSON.stringify(fresh)) return;
|
|
card = fresh;
|
|
cardCache.set(login.toLowerCase(), card);
|
|
renderProfile();
|
|
}
|
|
|
|
renderProfile();
|
|
|
|
const showLoadError = (error) => {
|
|
if (card) return;
|
|
status.replaceChildren(createErrorState({
|
|
title: 'Не удалось загрузить профиль',
|
|
text: toUserMessage(error, 'Проверьте соединение и попробуйте ещё раз.'),
|
|
onRetry: () => {
|
|
status.replaceChildren(createLoadingState({ label: 'Загружаю профиль', delayMs: 0 }));
|
|
refresh().catch(showLoadError);
|
|
},
|
|
}));
|
|
};
|
|
refresh().catch(showLoadError);
|
|
|
|
return screen;
|
|
}
|