UI: экраны без мелькания – кэш каналов и обсуждений, фоновая подгрузка, заставка как экран входа

- «Назад» при открытом редакторе закрывает только редактор: слой в истории ведёт роутер
  (openHistoryLayer), экран под ним больше не пересоздаётся.
- Канал и обсуждение при возврате рисуются сразу из памяти (page-data-cache), свежие данные
  подтягиваются тихо и перерисовывают экран, только если что-то изменилось; место в ленте сохраняется.
- Раз в минуту, пока вкладка на экране, обновляются лента каналов и шесть самых активных каналов.
- Обсуждение начинает грузиться при касании записи или ответа, канал для него берётся из кэша.
- Уведомления и профиль при повторном заходе без пустого кадра; убрано проявление списка каналов.
- Заглушка – только если загрузка дольше 0,5 с.
- Общая карточка «не удалось загрузить»: заголовок, причина в пару строк, крупная кнопка снизу.
- Стартовая заставка повторяет экран входа (знак, надпись, раскладка, фаза сияния) – смена незаметна.
This commit is contained in:
q
2026-10-12 09:23:55 +03:00
parent b5ce7b0fa0
commit cfb0f9b734
15 changed files with 1028 additions and 753 deletions
File diff suppressed because it is too large Load Diff
+218 -189
View File
@@ -2,7 +2,8 @@ import { appendShineMessageLinks } from '../services/shine-message-links.js';
import { confirmDialog } from '../components/confirm-dialog.js';
import { iconHtml } from '../components/ui-icon.js';
import { rememberChannelPosition, readChannelPosition, requestReplyEditorOnOpen, restoreChannelPosition } from '../services/channel-view-state.js';
import { getPreviousTrackedPath } from '../router.js';
import { getPreviousTrackedPath, parseRouteFromPath, toPrettyPath } from '../router.js';
import { prefetchThreadPage } from './channel-thread-view.js';
import { attachMessageMenu } from '../components/message-menu.js';
import { createTopBar } from '../components/topbar.js';
import {
@@ -15,6 +16,7 @@ import {
import { toUserMessage } from '../services/ui-error-texts.js';
import {
animatePress,
createLoadErrorCard,
createSkeletonRows,
SKELETON_DELAY_MS,
dayKey,
@@ -51,6 +53,7 @@ import {
makeShineChannelDonateRoute,
} from '../services/shine-routes.js';
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
import { dropPageData, readPageData, writePageData } from '../services/page-data-cache.js';
import { sortedChannelPublications } from '../services/channel-message-ordinals.js';
export const pageMeta = { id: 'channel-view', title: 'Канал', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
@@ -1571,27 +1574,12 @@ async function loadFromApi(route, channelId) {
}
function renderLoadError(screen, navigate, message, onRetry) {
const card = document.createElement('div');
card.className = 'card stack channels-status';
card.innerHTML = `
<strong>Не удалось загрузить канал</strong>
<p class="meta-muted">${message || 'Проверьте подключение к серверу и повторите попытку.'}</p>
`;
const retry = document.createElement('button');
retry.type = 'button';
retry.className = 'primary-btn';
retry.textContent = 'Повторить';
retry.addEventListener('click', onRetry);
const back = document.createElement('button');
back.type = 'button';
back.className = 'secondary-btn';
back.textContent = 'Назад к каналам';
back.addEventListener('click', () => navigate('channels-list'));
card.append(retry, back);
screen.append(card);
screen.append(createLoadErrorCard({
title: 'Не удалось загрузить канал',
message: message || 'Проверьте подключение и повторите попытку.',
onRetry,
secondary: { label: 'Назад к каналам', onClick: () => navigate('channels-list') },
}));
}
function renderDemoFallback(screen, navigate, error) {
@@ -2123,6 +2111,11 @@ function renderPostCard(post, {
openDiscussion();
});
card.classList.add('is-openable');
// Обсуждение начинаем грузить уже при касании – к моменту клика оно обычно готово.
card.addEventListener('pointerdown', () => {
const route = buildThreadRoute(post, selector);
if (route) prefetchThreadPage(`/${toPrettyPath(route)}`);
}, { passive: true });
const replyButton = document.createElement('button');
replyButton.type = 'button';
@@ -2501,6 +2494,16 @@ function renderBody(screen, navigate, routeKey, channelData, handlers) {
};
}
// Фоновая подгрузка канала в кэш, чтобы он открывался сразу (вызывается из обхода ленты каналов).
export async function prefetchChannelPage(path) {
const pathname = new URL(path, window.location.origin).pathname;
const route = parseRouteFromPath(pathname);
if (route.pageId !== 'channel-view') return false;
const data = await loadFromApi(route, route.params.channelId || '');
writePageData('channel', pathname, data);
return true;
}
// Место под заглушку занимаем сразу, а сами строки рисуем, только если загрузка затянулась.
function renderSkeleton(screen) {
const wrap = document.createElement('div');
@@ -2960,6 +2963,163 @@ export function render({ navigate, route, chrome }) {
}
};
// Рисует канал по готовым данным: и из кэша при возврате, и после загрузки с сервера.
const paint = (apiData, restorePosition) => {
activeSelector = apiData?.selector || null;
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
const entrypointPosts = getEntrypointPosts(apiData?.posts);
const openEntrypointHistory = () => {
openEntrypointHistoryModal({
channelTitle: titleLabel,
posts: apiData?.posts,
onSelect: (post) => {
if (!flashAndScrollToMessage(post?.messageRef)) {
showToast('Не удалось найти запись оглавления в ленте');
}
},
});
};
activeOpenEntrypointHistory = openEntrypointHistory;
if (channelHeaderButton) {
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
const slug = String(apiData?.channel?.name || '').trim();
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
channelHeaderButton.replaceChildren();
const text = document.createElement('span');
text.className = 'topbar-identity__text';
const titleNode = document.createElement('span');
titleNode.className = 'topbar-identity__title';
titleNode.textContent = titleLabel;
const subNode = document.createElement('span');
subNode.className = 'topbar-identity__sub';
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
text.append(titleNode, subNode);
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
channelHeaderButton.disabled = false;
channelHeaderButton.onclick = (event) => {
animatePress(event.currentTarget);
const aboutRoute = makeShineChannelAboutRoute({
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
});
if (aboutRoute) navigate(aboutRoute);
};
}
activeChannelData = apiData;
if (channelMoreButton) {
channelMoreButton.disabled = false;
}
if (channelEntrypointButton) {
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
channelEntrypointButton.hidden = !canShowEntrypointButton;
channelEntrypointButton.disabled = !canShowEntrypointButton;
channelEntrypointButton.onclick = () => {
const latestEntrypoint = entrypointPosts[0];
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
showToast('Не удалось найти актуальное оглавление');
}
};
}
clearContent();
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
chrome,
restorePosition,
scrollToMessageOrdinal,
showStatus,
isActive: () => !disposed,
onAddMessage: activeAddMessage = async () => {
if (apiData?.channel?.deleted) {
const confirmed = await confirmDialog({
title: 'Восстановить канал?',
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
confirmLabel: 'Восстановить и написать',
});
if (!confirmed || disposed) return;
}
openAddMessageModal({
channelName: apiData?.channel?.name || '',
channelTitle: apiData?.channel?.displayTitle || '',
navigate,
isActive: () => !disposed,
onSubmit: async ({ text: bodyText, msgSubType }) => {
try {
await onAddPost(bodyText, msgSubType);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
}
},
});
},
onToggleLike: async (messageRef, action) => {
try {
await onToggleLike(messageRef, action);
showStatus('');
} catch (error) {
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
}
},
onReply: async (messageRef, text) => {
try {
await onReply(messageRef, text);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
}
},
onRating: async (messageRef, text) => {
try {
await onRating(messageRef, text);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
}
},
onStatusAction: async (post) => {
try {
await onStatusAction(post);
showStatus('');
} catch (error) {
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
}
},
onOpenEntrypointMenu: () => {
openEntrypointMenuModal({
onShowHistory: openEntrypointHistory,
});
},
onRepost: async (messageRef) => {
try {
await onRepost(messageRef);
showStatus('');
} catch (error) {
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
}
},
onAddPost: async (bodyText) => {
try {
await onAddPost(bodyText);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
}
},
onShare: onShare,
onEdit: async (messageRef, text) => {
try {
await onEditPost(messageRef, text);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
}
},
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
});
};
refresh = async () => {
if (disposed) return;
const seq = ++refreshSeq;
@@ -2972,183 +3132,52 @@ export function render({ navigate, route, chrome }) {
? getChannelScrollRoot()?.scrollTop
: (returnedFromChannelPage ? readChannelPosition(positionKey) : undefined);
if (!hadContent) clearContent();
activeChannelData = null;
activeOpenEntrypointHistory = null;
activeSelector = null;
showStatus('');
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
channelHeaderButton.disabled = true;
channelHeaderButton.onclick = null;
if (channelMoreButton) channelMoreButton.disabled = true;
if (channelEntrypointButton) {
channelEntrypointButton.disabled = true;
channelEntrypointButton.hidden = true;
channelEntrypointButton.onclick = null;
const cacheKey = window.location.pathname;
// При возврате на канал сразу показываем прошлую загрузку, без заглушки и пустого кадра.
const cached = hadContent ? null : readPageData('channel', cacheKey);
let shown = hadContent;
if (cached) {
// Роутер вставляет экран в страницу сразу после render: ждём этого (до первого кадра), иначе прокрутку не к чему применить.
await Promise.resolve();
if (disposed || seq !== refreshSeq) return;
try {
paint(cached.data, restorePosition);
shown = true;
} catch (error) {
dropPageData('channel', cacheKey);
clearContent();
}
}
const skeleton = hadContent ? null : renderSkeleton(screen);
if (!shown) {
activeChannelData = null;
activeOpenEntrypointHistory = null;
activeSelector = null;
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span><span class="channel-header-owner">Загрузка…</span>';
channelHeaderButton.disabled = true;
channelHeaderButton.onclick = null;
if (channelMoreButton) channelMoreButton.disabled = true;
if (channelEntrypointButton) {
channelEntrypointButton.disabled = true;
channelEntrypointButton.hidden = true;
channelEntrypointButton.onclick = null;
}
}
const skeleton = shown ? null : renderSkeleton(screen);
try {
const apiData = await loadFromApi(route, channelId);
if (disposed || seq !== refreshSeq) return;
activeSelector = apiData?.selector || null;
const titleLabel = apiData?.channel?.displayTitle || apiData?.channel?.name || 'channel';
const entrypointPosts = getEntrypointPosts(apiData?.posts);
const openEntrypointHistory = () => {
openEntrypointHistoryModal({
channelTitle: titleLabel,
posts: apiData?.posts,
onSelect: (post) => {
if (!flashAndScrollToMessage(post?.messageRef)) {
showToast('Не удалось найти запись оглавления в ленте');
}
},
});
};
activeOpenEntrypointHistory = openEntrypointHistory;
if (channelHeaderButton) {
// Под названием показываем владельца и короткое название, одинаково для ленты и /s/<номер>.
const slug = String(apiData?.channel?.name || '').trim();
const owner = String(apiData?.channel?.ownerName || extractLoginFromBlockchainName(apiData?.selector?.ownerBlockchainName) || '').trim();
channelHeaderButton.replaceChildren();
const text = document.createElement('span');
text.className = 'topbar-identity__text';
const titleNode = document.createElement('span');
titleNode.className = 'topbar-identity__title';
titleNode.textContent = titleLabel;
const subNode = document.createElement('span');
subNode.className = 'topbar-identity__sub';
subNode.textContent = apiData?.isDiary ? 'Только вам' : `${owner ? `@${owner}` : ''}${owner && slug ? ' / ' : ''}${slug}`;
text.append(titleNode, subNode);
channelHeaderButton.append(createChannelAvatarElement(apiData?.channel, 40), text);
channelHeaderButton.setAttribute('aria-label', `${titleLabel}. О канале`);
channelHeaderButton.disabled = false;
channelHeaderButton.onclick = (event) => {
animatePress(event.currentTarget);
const aboutRoute = makeShineChannelAboutRoute({
ownerBlockchainName: apiData?.channel?.ownerBlockchainName || apiData?.selector?.ownerBlockchainName || '',
channelRootBlockNumber: apiData?.selector?.channelRootBlockNumber ?? apiData?.channel?.channelRoot?.blockNumber ?? '',
channelRootBlockHash: apiData?.selector?.channelRootBlockHash ?? apiData?.channel?.channelRoot?.blockHash ?? '',
});
if (aboutRoute) navigate(aboutRoute);
};
}
activeChannelData = apiData;
if (channelMoreButton) {
channelMoreButton.disabled = false;
}
if (channelEntrypointButton) {
const canShowEntrypointButton = !apiData?.isDiary && entrypointPosts.length > 0;
channelEntrypointButton.hidden = !canShowEntrypointButton;
channelEntrypointButton.disabled = !canShowEntrypointButton;
channelEntrypointButton.onclick = () => {
const latestEntrypoint = entrypointPosts[0];
if (!latestEntrypoint?.messageRef || !flashAndScrollToMessage(latestEntrypoint.messageRef)) {
showToast('Не удалось найти актуальное оглавление');
}
};
}
const signature = writePageData('channel', cacheKey, apiData);
// Сервер вернул то же, что уже на экране, – ничего не трогаем, чтобы не дёргать ленту.
if (cached && cached.signature === signature) return;
skeleton?.remove();
clearContent();
cleanupSeenTracking = renderBody(screen, navigate, routeKey, apiData, {
chrome,
restorePosition,
scrollToMessageOrdinal,
showStatus,
isActive: () => !disposed,
onAddMessage: activeAddMessage = async () => {
if (apiData?.channel?.deleted) {
const confirmed = await confirmDialog({
title: 'Восстановить канал?',
text: 'Новое сообщение восстановит канал: он перестанет считаться удалённым и снова появится в обычном списке ваших каналов.',
confirmLabel: 'Восстановить и написать',
});
if (!confirmed || disposed) return;
}
openAddMessageModal({
channelName: apiData?.channel?.name || '',
channelTitle: apiData?.channel?.displayTitle || '',
navigate,
isActive: () => !disposed,
onSubmit: async ({ text: bodyText, msgSubType }) => {
try {
await onAddPost(bodyText, msgSubType);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
}
},
});
},
onToggleLike: async (messageRef, action) => {
try {
await onToggleLike(messageRef, action);
showStatus('');
} catch (error) {
showStatus(toUserMessage(error, action === 'unlike' ? 'Не удалось убрать лайк.' : 'Не удалось поставить лайк.'));
}
},
onReply: async (messageRef, text) => {
try {
await onReply(messageRef, text);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось отправить ответ.'));
}
},
onRating: async (messageRef, text) => {
try {
await onRating(messageRef, text);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось отправить оценку.'));
}
},
onStatusAction: async (post) => {
try {
await onStatusAction(post);
showStatus('');
} catch (error) {
showStatus(toUserMessage(error, 'Не удалось записать действие.'));
}
},
onOpenEntrypointMenu: () => {
openEntrypointMenuModal({
onShowHistory: openEntrypointHistory,
});
},
onRepost: async (messageRef) => {
try {
await onRepost(messageRef);
showStatus('');
} catch (error) {
showStatus(toUserMessage(error, 'Не удалось сделать репост.'));
}
},
onAddPost: async (bodyText) => {
try {
await onAddPost(bodyText);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось добавить сообщение.'));
}
},
onShare: onShare,
onEdit: async (messageRef, text) => {
try {
await onEditPost(messageRef, text);
showStatus('');
} catch (error) {
throw new Error(toUserMessage(error, 'Не удалось изменить сообщение.'));
}
},
onSubscribeChannel: (event) => subscribeToChannel(apiData, event),
});
paint(apiData, shown ? getChannelScrollRoot()?.scrollTop : restorePosition);
} catch (error) {
if (disposed || seq !== refreshSeq) return;
skeleton?.remove();
if (hadContent) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
if (shown) { showStatus(toUserMessage(error, 'Не удалось обновить канал.')); return; }
channelHeaderButton.innerHTML = '<span class="channel-header-title">Канал</span>';
if (isChannelsDemoMode()) {
renderDemoFallback(screen, navigate, error);
return;
+39 -19
View File
@@ -5,6 +5,7 @@ import { toUserMessage } from '../services/ui-error-texts.js';
import { parseMessageAttachments } from '../services/attachment-format.js';
import {
animatePress,
createLoadErrorCard,
createSkeletonRows,
SKELETON_DELAY_MS,
formatListTime,
@@ -21,6 +22,9 @@ import { createDropdownMenu } from '../components/dropdown-menu.js';
import { createTopBar } from '../components/topbar.js';
import { parseDmTechBlocks } from '../services/dm-tech-blocks.js';
import { rememberChannelPosition, readChannelPosition, restoreChannelPosition } from '../services/channel-view-state.js';
import { pageDataAge } from '../services/page-data-cache.js';
import { toPrettyPath } from '../router.js';
import { prefetchChannelPage } from './channel-view.js';
export const pageMeta = { id: 'channels-list', title: 'Каналы', shellMode: { scrollbar: 'hidden', topFade: false, contentUnderTopbar: false, contentWidth: 'wide' } };
@@ -892,6 +896,35 @@ function mapApiFeed(feed, notificationsState, diaryPayload = null) {
return { ownChannels, followedUserChannels, subscribedChannels, index };
}
const PREFETCH_CHANNELS = 6;
const PREFETCH_FRESH_MS = 50_000;
// Фоновое обновление ленты каналов и самых активных каналов: экран «Каналы» и сами каналы
// открываются сразу из памяти. Запросы идут по одному, чтобы не нагружать сервер.
export async function refreshChannelsInBackground({ isCurrent = () => true } = {}) {
if (!state.session.isAuthorized || state.session.isLocalDemo) return;
const login = state.session.login;
const feed = await authService.listSubscriptionsFeed(login, 200);
if (!isCurrent() || state.session.login !== login) return;
const groups = mapApiFeed(feed, {}, null);
setChannelsFeed(feed, groups.index);
const routes = toListModel(groups)
.filter((row) => row.route)
.sort((a, b) => Number(b.lastMessageAt || 0) - Number(a.lastMessageAt || 0))
.slice(0, PREFETCH_CHANNELS)
.map((row) => `/${toPrettyPath(row.route)}`);
for (const route of routes) {
if (!isCurrent() || state.session.login !== login) return;
const pathname = new URL(route, window.location.origin).pathname;
if (pathname === window.location.pathname || pageDataAge('channel', pathname) < PREFETCH_FRESH_MS) continue;
try {
await prefetchChannelPage(pathname);
} catch {
// Фоновая подгрузка не должна мешать: канал загрузится обычным путём при открытии.
}
}
}
function toListModel(groups) {
return [
...(groups.ownChannels || []),
@@ -923,24 +956,11 @@ function renderSkeletonList(container, count = 4) {
}
function renderErrorState(container, error, onRetry) {
const errCard = document.createElement('div');
errCard.className = 'card stack channels-status';
const title = document.createElement('strong');
title.textContent = 'Не удалось загрузить каналы';
const details = document.createElement('p');
details.className = 'meta-muted';
details.textContent = toUserMessage(error, 'Проверьте подключение к серверу и повторите попытку.');
const retry = document.createElement('button');
retry.className = 'primary-btn';
retry.type = 'button';
retry.textContent = 'Повторить';
retry.addEventListener('click', onRetry);
errCard.append(title, details, retry);
container.append(errCard);
container.append(createLoadErrorCard({
title: 'Не удалось загрузить каналы',
message: toUserMessage(error, 'Проверьте подключение и повторите попытку.'),
onRetry,
}));
}
function renderDemoFallback(container, navigate, error, onRetry, { localOnly = false } = {}) {
@@ -1064,7 +1084,7 @@ function renderListContent({ screen, container, listState, navigate, refreshFeed
}
const list = document.createElement('div');
list.className = 'stack channels-groups channels-list-body-fade';
list.className = 'stack channels-groups';
const rerenderList = () => renderListContent({ screen, container, listState, navigate, refreshFeed });
+16 -2
View File
@@ -280,6 +280,9 @@ function renderItem(item, activeTab, navigate) {
return row;
}
// Последние уведомления – только в памяти вкладки: при повторном заходе экран рисуется сразу, без пустого кадра.
let lastNotifications = null;
export function render({ navigate, chrome } = {}) {
const screen = document.createElement('section');
screen.className = 'stack notifications-screen';
@@ -382,8 +385,19 @@ export function render({ navigate, chrome } = {}) {
}
async function load() {
const seq=++requestSeq; list.replaceChildren(renderEmpty(state.notificationsTab));
try { payloadCache=await authService.getNotifications(); if(seq!==requestSeq)return; updateToolbarBadge(payloadCache); await renderCurrent(); }
const seq=++requestSeq;
const login = state.session.login;
const cached = lastNotifications?.login === login ? lastNotifications : null;
if (cached) { payloadCache = structuredClone(cached.payload); void renderCurrent(); }
else renderTabs({});
try {
const fresh=await authService.getNotifications(); if(seq!==requestSeq)return;
const signature = JSON.stringify(fresh);
lastNotifications = { login, payload: structuredClone(fresh), signature };
updateToolbarBadge(fresh);
if (cached?.signature === signature) return;
payloadCache=fresh; await renderCurrent();
}
catch(error){ if(seq!==requestSeq)return; const card=document.createElement('article');card.className='card stack';card.innerHTML='<strong>Не удалось загрузить уведомления</strong>';const t=document.createElement('p');t.className='meta-muted';t.textContent=error?.message||'Ошибка запроса к серверу';card.append(t);list.replaceChildren(card);}
}
+2
View File
@@ -90,6 +90,8 @@ export function render({ navigate, chrome }) {
}
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();
+20 -8
View File
@@ -23,20 +23,14 @@ export function render({ navigate }) {
logoWrap.append(logo);
const brandBlock = document.createElement('div');
brandBlock.className = 'stack';
brandBlock.style.alignItems = 'center';
brandBlock.style.gap = '22px';
brandBlock.className = 'stack auth-brand-block';
const title = document.createElement('h1');
title.className = 'auth-brand';
title.append(createShineWordmark());
const siteName = document.createElement('p');
siteName.className = 'meta-muted';
siteName.style.margin = '0';
siteName.style.fontSize = '18px';
siteName.style.letterSpacing = '0.045em';
siteName.style.lineHeight = '1.25';
siteName.className = 'meta-muted auth-site-name';
siteName.textContent = window.location.host || window.location.hostname || 'shineup.me';
brandBlock.append(title, siteName);
@@ -73,5 +67,23 @@ export function render({ navigate }) {
actions.append(loginButton, registerButton, languageButton, settingsButton);
screen.append(logoWrap, brandBlock, actions);
// Экран монтируется сразу после render – тогда и подхватываем анимацию знака с заставки.
queueMicrotask(() => continueSplashAnimations(logoWrap));
return screen;
}
// Заставка рисует тот же знак: продолжаем её сияние с той же фазы, чтобы при смене не было скачка.
function continueSplashAnimations(logoWrap) {
const splashWrap = document.querySelector('#initial-splash .auth-logo-wrap');
if (!splashWrap || !logoWrap.isConnected) return;
const keyOf = (animation) => {
const target = animation.effect?.target;
const part = target?.classList?.contains('auth-logo') ? 'logo' : 'wrap';
return `${part}${animation.effect?.pseudoElement || ''}|${animation.animationName || ''}`;
};
const source = new Map(splashWrap.getAnimations({ subtree: true }).map((animation) => [keyOf(animation), animation]));
logoWrap.getAnimations({ subtree: true }).forEach((animation) => {
const match = source.get(keyOf(animation));
if (match && match.currentTime != null) animation.currentTime = match.currentTime;
});
}