Поправил пуши для личных сообщений

This commit is contained in:
AidarKC
2026-10-21 11:47:27 +03:00
parent aa5addb5d9
commit 7a6ab3b35a
22 changed files with 723 additions and 678 deletions
+53 -171
View File
@@ -13,6 +13,7 @@ import { renderUserAvatar } from '../components/avatar-image.js';
import { createErrorState, createSpinner, createStateMessage } from '../components/feedback.js';
import { createListSection, createPersonRow } from '../components/person-row.js';
import { authService, state } from '../state.js';
import { getConnectionsGraphCached as loadSharedGraph, cachedConnectionsGraph as getCachedSharedGraph, CONNECTIONS_GRAPH_CHANGED, CONNECTIONS_GRAPH_TTL_MS } from '../services/connections-graph-cache.js';
import { openHistoryLayer } from '../router.js';
import { makeProfileRoute, makeProfileLinksRoute, makeShineChannelRootRoute } from '../services/shine-routes.js';
import { userDisplayName } from '../services/user-display.js';
@@ -30,7 +31,7 @@ import {
updateCompanySnapshots,
} from './network/companies-store.js';
import {
PEOPLE_DATA_FRESH_MS, channelInfo, channelKey, getCities, getSubs, getTies, saveCities, saveSubs, saveTies,
PEOPLE_DATA_FRESH_MS, peopleDataGeneration, channelInfo, channelKey, getCities, getSubs, getTies, saveCities, saveSubs, saveTies,
} from './network/people-data-store.js';
import {
clearManualLayout, getAutoLayoutMode, getLayoutMode, getManualBase, getManualLayout, getViewSetting, hasManualLayout,
@@ -119,52 +120,28 @@ function normalizeAvatar(row) {
function buildGraphModel(graph, centerLogin) {
const login = normalizeLogin(graph?.login || centerLogin || state.session.login);
const outFriends = toSet(graph?.outFriends);
const inFriends = toSet(graph?.inFriends);
const outCloseFriends = toSet(graph?.outCloseFriends);
const inFriends = toSet(graph?.inFriends);
const inCloseFriends = toSet(graph?.inCloseFriends);
const outContacts = toSet(graph?.outContacts);
const inContacts = toSet(graph?.inContacts);
const outFollows = toSet(graph?.outFollows);
const inFollows = toSet(graph?.inFollows);
const outOfficial = toSet(graph?.outOfficialAccounts);
const inOfficial = toSet(graph?.inOfficialAccounts);
const allMarks = getMarkByLogin(graph?.allUsers);
// Родственные связи сервер хранит, но в интерфейсе они пока скрыты.
// Граф показывает только тех, кого владелец сам выбрал другом.
// Входящие друзья нужны лишь для проверки взаимности, контакты и подписки исключены.
const allLogins = uniqueLogins([
...(graph?.outFriends || []),
...(graph?.inFriends || []),
...(graph?.outCloseFriends || []),
...(graph?.inCloseFriends || []),
...(graph?.outContacts || []),
...(graph?.inContacts || []),
...(graph?.outFollows || []),
...(graph?.inFollows || []),
...(graph?.outOfficialAccounts || []),
...(graph?.inOfficialAccounts || []),
...(graph?.outFriends || []),
]).filter((entry) => normKey(entry) !== normKey(login));
const relations = allLogins.map((targetLogin) => {
const friendOut = hasLogin(outFriends, targetLogin);
const friendIn = hasLogin(inFriends, targetLogin);
const closeFriendOut = hasLogin(outCloseFriends, targetLogin);
const closeFriendIn = hasLogin(inCloseFriends, targetLogin);
const contactOut = hasLogin(outContacts, targetLogin) || hasLogin(outFollows, targetLogin) || hasLogin(outOfficial, targetLogin);
const contactIn = hasLogin(inContacts, targetLogin) || hasLogin(inFollows, targetLogin) || hasLogin(inOfficial, targetLogin);
const role = closeFriendOut || closeFriendIn || friendOut || friendIn ? 'friend' : 'contact';
// Взаимность – по любой связи с той стороны: «друг» в ответ на «контакт» – тоже ответ.
const forward = closeFriendOut || friendOut || contactOut;
const backward = closeFriendIn || friendIn || contactIn;
return {
login: targetLogin,
key: normKey(targetLogin),
role,
isRelative: false,
forward,
backward,
mark: allMarks.get(normKey(targetLogin)) || null,
};
});
const relations = allLogins.map((targetLogin) => ({
login: targetLogin,
key: normKey(targetLogin),
role: 'friend',
relationType: hasLogin(outCloseFriends, targetLogin) ? 'close_friend' : 'friend',
isRelative: false,
forward: true,
backward: hasLogin(inCloseFriends, targetLogin) || hasLogin(inFriends, targetLogin),
mark: allMarks.get(normKey(targetLogin)) || null,
}));
return {
centerLogin: login,
@@ -188,52 +165,8 @@ async function mapWithConcurrency(items, concurrency, worker) {
return out;
}
const NETWORK_GRAPH_CACHE_TTL_MS = 2 * 60 * 1000;
const NETWORK_GRAPH_CACHE_MAX = 240;
const networkGraphCache = new Map();
const networkGraphInflight = new Map();
function cachedGraph(login) {
const cached = networkGraphCache.get(normKey(login));
return cached && Date.now() - cached.savedAt < NETWORK_GRAPH_CACHE_TTL_MS ? cached.graph : null;
}
async function getConnectionsGraphCached(login, { force = false, retries = 0 } = {}) {
const clean = normalizeLogin(login);
const key = normKey(clean);
if (!key) throw new Error('LOGIN_REQUIRED');
const fresh = force ? null : cachedGraph(clean);
if (fresh) return fresh;
if (!force && networkGraphInflight.has(key)) return networkGraphInflight.get(key);
const request = (async () => {
let lastError = null;
for (let attempt = 0; attempt <= Math.max(0, retries); attempt += 1) {
try {
const graph = await authService.getUserConnectionsGraph(clean);
networkGraphCache.delete(key);
networkGraphCache.set(key, { graph, savedAt: Date.now() });
while (networkGraphCache.size > NETWORK_GRAPH_CACHE_MAX) {
const oldestKey = networkGraphCache.keys().next().value;
if (!oldestKey) break;
networkGraphCache.delete(oldestKey);
}
return graph;
} catch (error) {
lastError = error;
if (attempt < retries) await new Promise((resolve) => window.setTimeout(resolve, 120 * (attempt + 1)));
}
}
throw lastError || new Error('GRAPH_LOAD_FAILED');
})();
networkGraphInflight.set(key, request);
try {
return await request;
} finally {
if (networkGraphInflight.get(key) === request) networkGraphInflight.delete(key);
}
}
const cachedGraph = (login) => getCachedSharedGraph(authService, login);
const getConnectionsGraphCached = (login, options) => loadSharedGraph(authService, login, options);
// Поиск без учёта регистра и «ё».
function searchText(value) {
@@ -247,24 +180,19 @@ const MAX_NODES = 400; // предел карты: дальше раскры
const RELATION_RANK = { close_friend: 0, family: 1, friend: 2, contact: 3 };
const FRIEND_TYPES = new Set(['close_friend', 'friend', 'family']);
const RELATION_LABEL = { close_friend: 'Близкий друг', friend: 'Друг', family: 'Семья', contact: 'Контакт' };
// Связь только с той стороны: другу – «хочет дружить», контакту – «вас добавили».
// Строгая взаимность дружбы. Чисто входящие пользователи на карте отсутствуют.
function directionLabel(node) {
if (node.direction === 'out') return 'без ответа';
if (node.direction === 'in') return FRIEND_TYPES.has(node.relationType) ? 'хочет дружить' : 'вас добавили';
return 'взаимно';
return node.direction === 'out' ? 'без ответа' : 'взаимно';
}
// Переживает уход с экрана: возврат по «Связям» из профиля показывает ту же карту.
const persisted = { centerLogin: '', expanded: [], filter: 'all', friendsOfFriends: false, interest: '', view: null, listScroll: 0 };
// Фильтр – один выбранный. Тип связи и «добавили вас» – только про прямые связи центра,
// «сияющие» и «с заметкой» – про всех на карте.
// Фильтры относятся только к исходящему кругу друзей, а также раскрытым друзьям друзей.
const FILTERS = [
{ id: 'all', label: 'Все', pred: null },
{ id: 'close', label: 'Близкие', direct: true, pred: (node) => node.relationType === 'close_friend' || node.relationType === 'family' },
{ id: 'friends', label: 'Друзья', direct: true, pred: (node) => node.relationType === 'friend' },
{ id: 'contacts', label: 'Контакты', direct: true, pred: (node) => node.relationType === 'contact' },
{ id: 'incoming', label: 'Добавили вас', direct: true, selfOnly: true, pred: (node) => node.direction === 'in' },
{ id: 'shining', label: 'Сияющие', pred: (node) => Boolean(node.shining) },
{ id: 'notes', label: 'С заметкой', pred: (node) => Boolean(node.mark || node.hasNote) },
];
@@ -396,7 +324,6 @@ export function render({ navigate, route, chrome } = {}) {
let noteSheet = null;
let legendSheet = null;
let search = null; // { query, topbar, layer, remote: { seq, query, items, loading, failed } }
let waitingExpanded = false; // «Добавили вас» в списке: сначала несколько, по кнопке – все
let groupsModel = null; // острова «Компаний» / «Интересов»: { lens, groups, byId, byPerson }
let selectedGroupId = '';
let groupSheet = null;
@@ -905,16 +832,6 @@ export function render({ navigate, route, chrome } = {}) {
actions.append(cardAction('edit', 'Заметка', () => openNoteEditor(node)));
}
card.append(actions);
if (canAnswerBack(node)) {
const answer = document.createElement('button');
answer.type = 'button';
answer.className = 'primary-btn net-card__answer';
const busy = answering.has(node.id);
answer.disabled = busy;
answer.textContent = busy ? 'Сохраняю…' : answerBackLabel(node);
answer.addEventListener('click', () => { void answerBack(node); });
card.append(answer);
}
if (node.hiddenCount > 0) {
const more = document.createElement('p');
more.className = 'net-card__hint';
@@ -925,40 +842,6 @@ export function render({ navigate, route, chrome } = {}) {
placeOverlays();
}
// --- ответ взаимностью ---
// «Добавили вас»: ответить в одно касание – другом на дружбу, контактом на контакт
// (другой вид связи можно выбрать в профиле человека).
const answering = new Set();
function canAnswerBack(node) {
return Boolean(node) && node.id !== map?.focusId && node.tier === 1 && node.direction === 'in' && isSelfCenter();
}
function answerBackLabel(node) {
return FRIEND_TYPES.has(node.relationType) ? 'Дружить в ответ' : 'Добавить в ответ';
}
async function answerBack(node) {
if (!node || answering.has(node.id)) return;
const kind = FRIEND_TYPES.has(node.relationType) ? 'friend' : 'contact';
answering.add(node.id);
renderCard();
if (viewMode === 'list') renderList();
let done = false;
try {
await authService.setUserRelation({
login: state.session.login, toLogin: node.login, kind, enabled: true, storagePwd: state.session.storagePwdInMemory,
});
done = true;
if (!disposed) showToast(kind === 'friend' ? 'Теперь вы друзья' : 'Добавлено в контакты');
const graph = await getConnectionsGraphCached(selfLogin, { force: true });
if (!disposed) graphs.set(selfKey, buildGraphModel(graph, selfLogin));
} catch (error) {
// Связь сохранена, но карта не перечиталась – она обновится при следующем открытии.
if (!done && !disposed) showToast(actionErrorText('Не удалось ответить', error), { kind: 'error' });
} finally {
answering.delete(node.id);
if (!disposed) renderMap();
}
}
// --- заметка ---
function openNoteEditor(node) {
noteSheet?.close();
@@ -984,8 +867,7 @@ export function render({ navigate, route, chrome } = {}) {
const rows = [
['line', 'close_friend', 'Близкий друг'],
['line', 'friend', 'Друг'],
['line', 'contact', 'Контакт'],
['dash', 'friend', 'Пунктир – связь только с одной стороны'],
['dash', 'friend', 'Пунктир → точки – вы добавили друга, ответа пока нет'],
['aura', '', 'Свечение вокруг – сияющий'],
['badge', '', 'Синяя галочка – официальный аккаунт'],
['mark', '', 'Цветная точка – ваша заметка или метка'],
@@ -1005,7 +887,7 @@ export function render({ navigate, route, chrome } = {}) {
const tips = document.createElement('ul');
tips.className = 'net-legend__tips';
for (const tip of [
'«По близости»: ближе к центру – близкие, дальше – друзья, снаружи – контакты. Знакомые между собой стоят рядом.',
'«По близости»: ближе к центру – близкие друзья, дальше – друзья. Знакомые между собой стоят рядом.',
'«Компании» (в меню «•••») собирают вместе тех, кто знаком между собой: школа, работа, друзья по увлечению. Нить между компаниями – сколько в них знакомых друг с другом. Нажмите на название компании – откроется её карточка, там её можно назвать.',
'Человека можно перетащить в другую компанию – он останется в ней. Или нажмите «Перенести…» в его карточке.',
'«Интересы» собирают людей у каналов, которые они читают; нажмите на канал – подсветятся все его читатели. «Города» – кто где живёт (по полю «Город» в профиле). Знакомства, подписки и города узнаются один раз и хранятся на этом устройстве.',
@@ -1226,6 +1108,7 @@ export function render({ navigate, route, chrome } = {}) {
async function loadPeopleData(kind, { quiet = false, force = false } = {}) {
if (disposed || !map) return false;
const centerKey = normKey(centerLogin);
const generationAtStart = peopleDataGeneration();
const jobKey = `${kind}|${centerKey}`;
if (lensLoads.has(jobKey) || (!force && (lensBlockedUntil.get(jobKey) || 0) > Date.now())) return false;
const people = directPeople().slice(0, PEOPLE_DATA_LIMIT);
@@ -1259,7 +1142,7 @@ export function render({ navigate, route, chrome } = {}) {
const near = new Map();
for (const relation of buildGraphModel(graph, node.login).relations) {
if (relation.key === node.id || !directIds.has(relation.key)) continue;
near.set(relation.key, { type: relationTypeFromRelation(relation), mutual: relation.forward && relation.backward });
if (relation.forward) near.set(relation.key, { type: relationTypeFromRelation(relation), mutual: relation.backward });
}
entry.people.set(node.id, near);
} else if (kind === 'subs') {
@@ -1277,7 +1160,9 @@ export function render({ navigate, route, chrome } = {}) {
job.done += 1;
if (job.foreground && !disposed) syncLensProgress();
});
lensLoads.delete(jobKey);
if (lensLoads.get(jobKey) === job) lensLoads.delete(jobKey);
// Прежняя пачка данных могла закончиться уже после изменения дружбы.
if (disposed || generationAtStart !== peopleDataGeneration()) return false;
if (failed) lensBlockedUntil.set(jobKey, Date.now() + 60 * 1000);
else lensBlockedUntil.delete(jobKey);
// Освежили всех – отметка времени; если большинство не ответило, попробуем в следующий раз.
@@ -1486,19 +1371,17 @@ export function render({ navigate, route, chrome } = {}) {
persist();
}
// Состав по близости: «3 близких, 8 друзей, 15 контактов».
// Состав по близости: здесь считаются только друзья.
function compositionText(members) {
const counts = { close: 0, friend: 0, contact: 0 };
const counts = { close: 0, friend: 0 };
members.forEach((id) => {
const type = map?.byId.get(id)?.relationType;
if (type === 'close_friend' || type === 'family') counts.close += 1;
else if (type === 'friend') counts.friend += 1;
else counts.contact += 1;
});
const parts = [];
if (counts.close) parts.push(`${counts.close} ${pluralRu(counts.close, 'близкий', 'близких', 'близких')}`);
if (counts.friend) parts.push(`${counts.friend} ${pluralRu(counts.friend, 'друг', 'друга', 'друзей')}`);
if (counts.contact) parts.push(`${counts.contact} ${pluralRu(counts.contact, 'контакт', 'контакта', 'контактов')}`);
return parts.join(', ');
}
@@ -1922,11 +1805,9 @@ export function render({ navigate, route, chrome } = {}) {
ensureLensData();
}
// --- фильтры: «Все / Близкие / Друзья / Контакты» – тем же переключателем, что в чатах;
// реже нужное («Добавили вас», «Сияющие», «С заметкой», «Друзья друзей») – в «Ещё».
const PRIMARY_FILTERS = ['all', 'close', 'friends', 'contacts'];
// Дружеский круг: все, близкие, друзья; остальные условия – в меню «Ещё».
const PRIMARY_FILTERS = ['all', 'close', 'friends'];
const EXTRA_FILTERS = [
{ id: 'incoming', short: 'Добавили', icon: 'user-plus' },
{ id: 'shining', short: 'Сияющие', icon: 'sparkle' },
{ id: 'notes', short: 'С заметкой', icon: 'edit' },
];
@@ -2204,15 +2085,12 @@ export function render({ navigate, route, chrome } = {}) {
note: note?.text?.trim() ? note.text.trim().split('\n')[0] : '',
markColor: note?.mark || (note?.text?.trim() ? 'note' : ''),
ring: node.shining ? 'shining' : (node.relationType === 'close_friend' && node.tier === 1 ? 'close' : ''),
tag: node.tier === 1 && node.direction === 'in' && isSelfCenter() ? directionLabel(node) : '',
tag: '',
onClick: onOpen || (() => {
if (search) closeSearch();
navigate(profileRoute(node.login));
}),
actions: [
canAnswerBack(node)
? { icon: 'user-plus', label: answerBackLabel(node), primary: true, busy: answering.has(node.id), onClick: () => { void answerBack(node); } }
: null,
{ icon: 'message', label: 'Написать', onClick: () => navigate(`chat/${encodeURIComponent(node.login)}`) },
{ icon: 'more', label: 'Ещё', onClick: (event, button) => openRowMenu(node, button) },
],
@@ -2254,13 +2132,10 @@ export function render({ navigate, route, chrome } = {}) {
].filter((section) => section.items.length);
}
const direct = people.filter((node) => node.tier === 1);
const waiting = isSelfCenter() ? direct.filter((node) => node.direction === 'in') : [];
const rest = direct.filter((node) => !waiting.includes(node));
const rest = direct;
return [
{ title: 'Добавили вас', items: waiting.sort(byName), waiting: true },
{ title: 'Близкие', items: rest.filter((node) => node.relationType === 'close_friend' || node.relationType === 'family').sort(byName) },
{ title: 'Друзья', items: rest.filter((node) => node.relationType === 'friend').sort(byName) },
{ title: 'Контакты', items: rest.filter((node) => node.relationType === 'contact').sort(byName) },
{ title: 'Друзья друзей', items: people.filter((node) => node.tier > 1).sort(byName) },
].filter((group) => group.items.length);
}
@@ -2285,18 +2160,7 @@ export function render({ navigate, route, chrome } = {}) {
section.prepend(groupDot(group.group));
}
frag.append(section);
// Длинный «Добавили вас» не должен закрывать собой весь список: сначала трое.
const collapsed = group.waiting && !waitingExpanded && !query && group.items.length > 4;
const shown = collapsed ? group.items.slice(0, 3) : group.items;
shown.forEach((node) => frag.append(personRow(node, { withType })));
if (collapsed) {
const more = document.createElement('button');
more.type = 'button';
more.className = 'list-more';
more.innerHTML = `${iconHtml('chevron-down')}<span>Показать всех · ${group.items.length}</span>`;
more.addEventListener('click', () => { waitingExpanded = true; renderList(); });
frag.append(more);
}
group.items.forEach((node) => frag.append(personRow(node, { withType })));
}
if (query) appendRemoteResults(frag, new Set(people.map((node) => node.id)));
if (!people.length && map.nodes.length > 1 && !(query && search?.remote?.items?.length)) {
@@ -2490,6 +2354,22 @@ export function render({ navigate, route, chrome } = {}) {
overlayObserver?.observe(stage);
overlayObserver?.observe(filterBar);
function refreshConnectionsView() {
if (disposed || !centerLogin) return;
// Полный сброс отображаемых графов; запросы заново заполняют общий кэш.
graphs.clear();
lensLoads.clear();
lensBlockedUntil.clear();
groupsModel = null;
if (map) restoreView = engine.getView();
void load(centerLogin);
}
window.addEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
const graphRefreshTimer = window.setInterval(() => {
// TTL сам по себе не перерисовывает уже открытую карту — обновляем её при активности вкладки.
if (!disposed && !document.hidden) refreshConnectionsView();
}, CONNECTIONS_GRAPH_TTL_MS);
screen.cleanup = () => {
if (disposed) return;
disposed = true;
@@ -2505,6 +2385,8 @@ export function render({ navigate, route, chrome } = {}) {
window.cancelAnimationFrame(listFrame);
window.clearTimeout(remoteTimer);
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
window.clearInterval(graphRefreshTimer);
document.removeEventListener('keydown', onKeydown);
noteSheet?.close();
legendSheet?.close();