// Экран «Связи»: люди вокруг выбранного человека – картой или списком.
// Данные – GetUserConnectionsGraph (только чтение). Карту рисует graph-canvas.js, здесь –
// состав (центр, раскрытые связи), фильтры, поиск, список, карточка человека и заметки.
import { createSearchTopBar, createTopBar } from '../components/topbar.js';
import { createOverflowDots } from '../components/overflow-dots.js';
import { createDropdownMenu } from '../components/dropdown-menu.js';
import { iconHtml } from '../components/ui-icon.js';
import { openSheet } from '../components/sheet.js';
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 { openHistoryLayer } from '../router.js';
import { makeProfileRoute, makeProfileLinksRoute } from '../services/shine-routes.js';
import { userDisplayName } from '../services/user-display.js';
import { showToast } from '../services/channels-ux.js';
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
import { matchesPeopleQuery } from '../services/people-search.js';
import { PEOPLE_NOTES_EVENT, getAllPersonNotes } from '../services/people-notes.js';
import { createPersonNotePreview, openPersonNoteSheet } from '../components/person-note-sheet.js';
import { createGraphCanvas } from './network/graph-canvas.js';
import { peopleFromGraphModel } from './network/adapter.js';
import {
clearManualLayout, getAutoLayoutMode, getLayoutMode, getManualBase, getManualLayout, getViewSetting, hasManualLayout,
restoreManualLayout, saveManualLayout, setLayoutMode, setManualPoint, setViewSetting,
} from './network/layout-store.js';
export const pageMeta = {
id: 'network-view',
title: 'Связи',
shellMode: {
topFade: true,
bottomFade: true,
bottomFadeAnchor: 'toolbar',
fadeProfile: 'edge',
contentUnderTopbar: true,
scrollContainer: 'locked',
},
};
function normalizeLogin(value) {
return String(value || '').trim();
}
function normKey(value) {
return normalizeLogin(value).toLowerCase();
}
function uniqueLogins(list) {
const out = [];
const seen = new Set();
(Array.isArray(list) ? list : []).forEach((item) => {
const login = normalizeLogin(item);
if (!login) return;
const key = normKey(login);
if (seen.has(key)) return;
seen.add(key);
out.push(login);
});
return out;
}
function toSet(list) {
return new Set(uniqueLogins(list).map((value) => normKey(value)));
}
function hasLogin(setObj, login) {
return setObj.has(normKey(login));
}
function getMarkByLogin(allUsers) {
const map = new Map();
(Array.isArray(allUsers) ? allUsers : []).forEach((row) => {
const login = normalizeLogin(row?.login);
if (!login) return;
map.set(normKey(login), {
login,
firstName: String(row?.firstName || '').trim(),
lastName: String(row?.lastName || '').trim(),
displayName: userDisplayName({ login, firstName: row?.firstName, lastName: row?.lastName }),
relationType: String(row?.relationType || '').trim().toLowerCase(),
primaryConfirmed: Boolean(row?.primaryConfirmed),
shineConfirmed: Boolean(row?.shineConfirmed),
// Основной источник — server official. accountRole оставляем как совместимый fallback,
// чтобы badge не пропадал на серверах/ответах переходного периода.
official: row?.official === true
|| String(row?.official || '').trim().toLowerCase() === 'true'
|| String(row?.accountRole || '').trim().toLowerCase() === 'primary',
shine: row?.shine === true
|| String(row?.shine || '').trim().toLowerCase() === 'true'
|| String(row?.shineStatus || '').trim().toLowerCase() === 'shining',
avatar: normalizeAvatar(row),
});
});
return map;
}
function normalizeAvatar(row) {
const txFromAvatar = String(row?.avatar?.ar || '').trim();
const shaFromAvatar = String(row?.avatar?.sha256Hex || row?.avatar?.sha256 || '').trim().toLowerCase();
if (txFromAvatar || shaFromAvatar) return { ar: txFromAvatar, sha256Hex: shaFromAvatar };
const txFallback = String(row?.avatarTxId || '').trim();
if (txFallback) return { ar: txFallback };
return null;
}
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 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 || []),
]).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,
};
});
return {
centerLogin: login,
centerMark: allMarks.get(normKey(login)) || null,
relations,
};
}
async function mapWithConcurrency(items, concurrency, worker) {
const list = Array.isArray(items) ? items : [];
const out = new Array(list.length);
let cursor = 0;
const runners = new Array(Math.min(Math.max(1, concurrency), list.length)).fill(0).map(async () => {
while (cursor < list.length) {
const index = cursor++;
try { out[index] = await worker(list[index], index); }
catch (error) { out[index] = { error }; }
}
});
await Promise.all(runners);
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);
}
}
// Поиск без учёта регистра и «ё».
function searchText(value) {
return String(value || '').toLowerCase().replaceAll('ё', 'е').trim();
}
// --- Состав карты ---------------------------------------------------------------------------
const EXPAND_LIMIT = 40; // сколько новых людей добавляет раскрытие одного человека
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 'взаимно';
}
// Переживает уход с экрана: возврат по «Связям» из профиля показывает ту же карту.
const persisted = { centerLogin: '', expanded: [], filter: 'all', friendsOfFriends: false, 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) },
];
const FILTER_BY_ID = new Map(FILTERS.map((filter) => [filter.id, filter]));
function composeMap(centerLogin, graphs, expanded, notes) {
const centerKey = normKey(centerLogin);
const centerModel = graphs.get(centerKey);
if (!centerModel) return null;
const byId = new Map();
const edges = [];
const add = (node) => {
const note = notes.get(node.id);
byId.set(node.id, { ...node, mark: note?.mark || '', hasNote: Boolean(note?.text?.trim()), hiddenCount: 0 });
};
const { center, peers } = peopleFromGraphModel(centerModel);
add({ ...center, relationType: 'self', tier: 1, parentId: '', direction: '' });
for (const peer of peers) {
add({ ...peer.person, relationType: peer.relationType, mutual: peer.mutual, direction: peer.direction, tier: 1, parentId: center.id });
edges.push({ a: center.id, b: peer.person.id, type: peer.relationType, mutual: peer.mutual });
}
for (const key of expanded) {
const owner = byId.get(key);
const model = graphs.get(key);
if (!owner || !model) continue;
const tier = Math.min(3, (owner.id === center.id ? 0 : owner.tier) + 1);
const ordered = [...peopleFromGraphModel(model).peers]
.sort((a, b) => (RELATION_RANK[a.relationType] ?? 9) - (RELATION_RANK[b.relationType] ?? 9));
let added = 0;
for (const peer of ordered) {
const id = peer.person.id;
if (byId.has(id)) {
edges.push({ a: key, b: id, type: peer.relationType, mutual: peer.mutual });
continue;
}
if (added >= EXPAND_LIMIT || byId.size >= MAX_NODES) {
owner.hiddenCount += 1;
continue;
}
add({ ...peer.person, relationType: peer.relationType, mutual: peer.mutual, direction: peer.direction, tier, parentId: key });
edges.push({ a: key, b: id, type: peer.relationType, mutual: peer.mutual });
added += 1;
}
}
byId.forEach((node) => { node.expanded = expanded.has(node.id); });
return { focusId: center.id, nodes: [...byId.values()], edges, byId };
}
// --- Страница -------------------------------------------------------------------------------
export function render({ navigate, route, chrome } = {}) {
const keepHistory = String(route?.params?.mode || '').trim().toLowerCase() === 'keep-history';
const routeLogin = normalizeLogin(route?.params?.login || '');
const selfLogin = normalizeLogin(state.session.login || '');
const selfKey = normKey(selfLogin);
let centerLogin = routeLogin || (keepHistory && persisted.centerLogin) || selfLogin;
const restore = keepHistory && normKey(persisted.centerLogin) === normKey(centerLogin);
const expanded = new Set(restore ? persisted.expanded : []);
let filterId = keepHistory && FILTER_BY_ID.has(persisted.filter) ? persisted.filter : 'all';
let friendsOfFriends = restore && persisted.friendsOfFriends;
// «Назад» из профиля – карта и список там же, где были.
let restoreView = restore ? persisted.view : null;
let restoreListScroll = restore ? persisted.listScroll : 0;
let layoutMode = getLayoutMode();
let viewMode = getViewSetting('view', 'map') === 'list' ? 'list' : 'map';
let listSort = getViewSetting('listSort', 'closeness') === 'name' ? 'name' : 'closeness';
let notes = getAllPersonNotes();
const graphs = new Map();
const expanding = new Set();
let map = null;
let selectedId = '';
let disposed = false;
let loadSeq = 0;
let loadError = null;
let noteSheet = null;
let legendSheet = null;
let search = null; // { query, topbar, layer, remote: { seq, query, items, loading, failed } }
let waitingExpanded = false; // «Добавили вас» в списке: сначала несколько, по кнопке – все
const screen = document.createElement('section');
screen.className = 'network-screen';
screen.dataset.view = viewMode;
const stage = document.createElement('div');
stage.className = 'network-stage';
const board = document.createElement('div');
board.className = 'network-board network-board--full net-board';
const list = document.createElement('div');
list.className = 'net-list';
list.hidden = viewMode !== 'list';
const overlay = document.createElement('div');
overlay.className = 'net-overlay';
overlay.hidden = true;
const busyPill = document.createElement('div');
busyPill.className = 'net-busy';
busyPill.hidden = true;
busyPill.append(createSpinner({ size: 'sm', label: 'Загружаю связи' }));
const searchPanel = document.createElement('div');
searchPanel.className = 'net-search-panel';
searchPanel.hidden = true;
const a11yList = document.createElement('ul');
a11yList.className = 'sr-only';
a11yList.setAttribute('aria-label', 'Люди на карте');
function persist() {
persisted.centerLogin = centerLogin;
persisted.expanded = [...expanded];
persisted.filter = filterId;
persisted.friendsOfFriends = friendsOfFriends;
}
const isSelfCenter = () => normKey(centerLogin) === selfKey;
function profileRoute(login) {
const clean = normalizeLogin(login);
if (!clean) return '';
return normKey(clean) === selfKey ? 'profile-view' : makeProfileRoute(clean);
}
function syncLinksUrl(login, { push = false } = {}) {
const clean = normalizeLogin(login);
if (!clean) return;
const nextPath = `/${makeProfileLinksRoute(clean)}`;
if (window.location.pathname === nextPath) return;
if (push) window.history.pushState({}, '', nextPath);
else window.history.replaceState({}, '', nextPath);
}
function activeFilter() {
const filter = FILTER_BY_ID.get(filterId);
if (!filter?.pred || (filter.selfOnly && !isSelfCenter())) return null;
return filter;
}
function filterPredicate() {
const filter = activeFilter();
if (!filter) return null;
return (node) => (filter.direct ? Number(node.tier) <= 1 : true) && filter.pred(node);
}
// Поля, занятые панелями поверх карты: фильтры сверху, нижнее меню и карточка снизу.
function toolbarOverlap() {
const toolbar = document.getElementById('toolbar-slot');
if (!toolbar) return 0;
const t = toolbar.getBoundingClientRect();
const s = stage.getBoundingClientRect();
return t.height > 0 ? Math.max(0, s.bottom - t.top) : 0;
}
function insets() {
const s = stage.getBoundingClientRect();
const f = filterBar.getBoundingClientRect();
const top = f.height ? f.bottom - s.top + 8 : 8;
const bottom = toolbarOverlap() + (card.hidden ? 56 : card.offsetHeight + 12) + 8;
return { top, bottom };
}
function placeOverlays() {
const overlap = toolbarOverlap();
card.style.bottom = `${overlap + 12}px`;
modePill.style.bottom = `${overlap + 14}px`;
zoomBar.style.bottom = `${overlap + 12 + (card.hidden ? 0 : card.offsetHeight + 10)}px`;
list.style.paddingBottom = `${overlap + 76}px`;
const stageTop = stage.getBoundingClientRect().top;
const chipsRect = filterBar.getBoundingClientRect();
list.style.paddingTop = `${Math.max(0, chipsRect.bottom - stageTop + 4)}px`;
searchPanel.style.top = `${Math.max(0, chipsRect.top - stageTop)}px`;
searchPanel.style.bottom = `${overlap}px`;
}
const engine = createGraphCanvas({
stage: board,
getInsets: insets,
onSelect: (node) => selectNode(node ? node.id : ''),
onNodeMoved: (node, point) => onNodeMoved(node, point),
});
let listFrame = 0;
function renderMap({ fit = false, relayout = false } = {}) {
if (disposed) return;
map = composeMap(centerLogin, graphs, expanded, notes);
if (!map) return;
// Фильтры должны быть на месте до вписывания карты: от них зависит свободная часть экрана.
screen.classList.toggle('is-blank', map.nodes.length <= 1);
const layout = currentLayout();
engine.setGraph(map, { manual: layout.manual, mode: layout.mode, relayout, fit });
engine.setFilter(filterPredicate());
renderA11y();
syncFilters();
syncHeader();
syncStateMessage();
if (selectedId && !map.byId.has(selectedId)) selectNode('');
else if (selectedId) renderCard();
if (viewMode === 'list' && !listFrame) {
listFrame = window.requestAnimationFrame(() => { listFrame = 0; renderList(); });
}
if (search) renderSearchResults();
persist();
}
function renderA11y() {
a11yList.replaceChildren();
if (!map) return;
for (const node of map.nodes) {
const li = document.createElement('li');
const button = document.createElement('button');
button.type = 'button';
const relation = node.id === map.focusId ? 'в центре карты' : (RELATION_LABEL[node.relationType] || 'Связь').toLowerCase();
button.textContent = `${node.name}, ${relation}${node.shining ? ', сияющий' : ''}${node.mark || node.hasNote ? ', есть заметка' : ''}`;
button.addEventListener('click', () => selectNode(node.id, { reveal: true }));
li.append(button);
a11yList.append(li);
}
}
// Индикатор подгрузки поверх уже показанной карты (появляется с задержкой, без мелькания).
let busyCount = 0;
function setBusy(on) {
busyCount = Math.max(0, busyCount + (on ? 1 : -1));
busyPill.hidden = busyCount === 0;
}
// Что показать вместо карты: загрузка, ошибка, «пока нет связей» или «никого не нашлось».
function syncStateMessage() {
overlay.replaceChildren();
let content = null;
if (!map) {
if (loadError) {
content = createErrorState({
title: 'Не удалось загрузить связи',
text: toUserMessage(loadError, 'Проверьте соединение и попробуйте ещё раз.'),
onRetry: () => { void load(centerLogin); },
});
} else {
content = document.createElement('div');
content.className = 'loading-state';
content.style.setProperty('--loading-delay', '300ms');
content.append(createSpinner({ label: 'Загружаю связи' }));
}
} else if (map.nodes.length <= 1) {
const self = isSelfCenter();
const center = map.byId.get(map.focusId);
content = createStateMessage({
icon: 'network',
title: self ? 'Пока нет связей' : `У ${center?.name || centerLogin} пока нет связей`,
text: self
? 'Отмечайте друзей и знакомых в их профилях – они появятся здесь, на карте и в списке.'
: 'Когда этот человек отметит друзей или знакомых, они появятся здесь.',
actionLabel: self ? 'Найти людей' : 'К моим связям',
onAction: self ? () => openSearch() : () => recenter(selfLogin),
});
} else if (viewMode === 'map' && activeFilter() && engine.visibleCount() === 0) {
content = createStateMessage({
icon: 'search',
title: 'Никого не нашлось',
text: 'Под этот фильтр сейчас никто не подходит.',
actionLabel: 'Показать всех',
onAction: () => setFilter('all'),
});
}
overlay.hidden = !content;
if (content) overlay.append(content);
// Пока показывать нечего, фильтры, масштаб и «Списком» не нужны; в пустой карте
// сообщение стоит под точкой человека в центре.
const blank = !map || map.nodes.length <= 1;
screen.classList.toggle('is-blank', blank);
overlay.classList.toggle('net-overlay--below-center', Boolean(map) && map.nodes.length <= 1);
}
async function load(login, { push = false } = {}) {
const clean = normalizeLogin(login);
if (!clean) return;
const seq = ++loadSeq;
const known = Boolean(graphs.has(normKey(clean)) || cachedGraph(clean));
const busy = Boolean(map) && !known;
if (busy) setBusy(true);
if (!map) { loadError = null; syncStateMessage(); }
try {
const graph = await getConnectionsGraphCached(clean);
if (disposed || seq !== loadSeq) return;
graphs.set(normKey(clean), buildGraphModel(graph, clean));
if (normKey(clean) !== normKey(centerLogin)) {
expanded.clear();
friendsOfFriends = false;
if (FILTER_BY_ID.get(filterId)?.selfOnly && normKey(clean) !== selfKey) filterId = 'all';
selectNode('');
}
centerLogin = normalizeLogin(graph?.login || clean);
loadError = null;
syncLinksUrl(centerLogin, { push });
const restoring = Boolean(restoreView);
renderMap({ fit: !restoring });
if (restoreView) {
engine.setView(restoreView);
restoreView = null;
}
if (friendsOfFriends) void expandFriends({ fit: !restoring });
else if (expanded.size) void restoreExpanded();
} catch (error) {
if (disposed || seq !== loadSeq) return;
if (map) showToast(`Не удалось загрузить связи. ${toUserMessage(error, 'Попробуйте ещё раз.')}`, { kind: 'error', timeoutMs: 3200 });
else {
loadError = error;
syncStateMessage();
}
} finally {
if (busy && !disposed) setBusy(false);
}
}
async function fetchGraphs(logins) {
const missing = logins.filter((login) => !graphs.has(normKey(login)));
const results = await mapWithConcurrency(missing, 4, async (login) => {
const graph = await getConnectionsGraphCached(login, { retries: 1 });
return { login, graph };
});
let failed = 0;
results.forEach((row) => {
if (!row || row.error) { failed += 1; return; }
graphs.set(normKey(row.login), buildGraphModel(row.graph, row.login));
});
return failed;
}
async function expandNode(id) {
const node = map?.byId.get(id);
if (!node || expanding.has(id)) return;
const centerAtStart = normKey(centerLogin);
expanding.add(id);
renderCard();
const failed = await fetchGraphs([node.login]);
expanding.delete(id);
if (disposed || normKey(centerLogin) !== centerAtStart) return;
if (failed) {
renderCard();
showToast('Не удалось загрузить связи этого человека. Попробуйте ещё раз.', { kind: 'error', timeoutMs: 2600 });
return;
}
expanded.add(id);
renderMap({ fit: true });
}
// Свернуть: убираем и тех, кто держался на карте только через свёрнутого.
function collapseNode(id) {
expanded.delete(id);
for (;;) {
const next = composeMap(centerLogin, graphs, expanded, notes);
const orphan = [...expanded].find((key) => !next?.byId.has(key));
if (!orphan) break;
expanded.delete(orphan);
}
renderMap({ fit: true });
}
// Раскрытые вручную связи после возврата на экран: их графы надо подгрузить заново
// (обычно они ещё в кэше), иначе раскрытие молча пропадало.
async function restoreExpanded() {
const centerAtStart = normKey(centerLogin);
const logins = [...expanded].filter((key) => !graphs.has(key));
if (!logins.length) return;
await fetchGraphs(logins);
if (disposed || normKey(centerLogin) !== centerAtStart) return;
renderMap();
}
async function expandFriends({ fit = true } = {}) {
const centerAtStart = normKey(centerLogin);
const friends = (map?.nodes || []).filter((node) => node.tier === 1 && node.id !== map.focusId && FRIEND_TYPES.has(node.relationType));
if (!friends.length) {
friendsOfFriends = false;
syncFilters();
showToast(isSelfCenter() ? 'Пока нет друзей – раскрывать нечего' : 'У этого человека пока нет друзей на карте', { kind: 'info', timeoutMs: 2200 });
return;
}
setBusy(true);
const failed = await fetchGraphs(friends.map((node) => node.login));
setBusy(false);
if (disposed || normKey(centerLogin) !== centerAtStart || !friendsOfFriends) return;
friends.forEach((node) => { if (graphs.has(node.id)) expanded.add(node.id); });
// Полная перестройка: теперь известно, кто с кем знаком, – знакомые встанут рядом.
renderMap({ fit, relayout: true });
if (failed) showToast(`Не удалось загрузить связи ${failed} из ${friends.length} друзей`, { kind: 'error', timeoutMs: 2600 });
}
function toggleFriendsOfFriends() {
friendsOfFriends = !friendsOfFriends;
syncFilters();
if (friendsOfFriends) {
void expandFriends();
} else {
expanded.clear();
renderMap({ fit: true, relayout: true });
}
persist();
}
function recenter(login) {
selectNode('');
if (search) closeSearch();
void load(login, { push: true });
}
// --- карточка выбранного человека ---
const card = document.createElement('div');
card.className = 'net-card';
card.hidden = true;
card.setAttribute('role', 'region');
card.addEventListener('pointerdown', (event) => event.stopPropagation());
function selectNode(id, { reveal = false } = {}) {
selectedId = id && map?.byId.has(id) ? id : '';
engine.select(selectedId, { reveal });
renderCard();
// Выбранный не должен прятаться под карточкой.
if (selectedId && !reveal) engine.ensureVisible(selectedId);
}
function cardAction(icon, label, onClick, { disabled = false, pressed = null, busy = false } = {}) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'ui-button net-card__action';
if (busy) button.append(createSpinner({ size: 'sm', label }));
else button.innerHTML = iconHtml(icon);
const text = document.createElement('span');
text.textContent = label;
button.append(text);
button.disabled = disabled;
if (pressed !== null) button.setAttribute('aria-pressed', pressed ? 'true' : 'false');
button.addEventListener('click', onClick);
return button;
}
function relationText(node) {
if (node.tier > 1) {
const via = map.byId.get(node.parentId);
return via ? `${(RELATION_LABEL[node.relationType] || 'связь').toLowerCase()} у ${via.name}` : 'друг друга';
}
return `${RELATION_LABEL[node.relationType] || 'Связь'} · ${directionLabel(node)}`;
}
function renderCard() {
const node = selectedId ? map?.byId.get(selectedId) : null;
card.replaceChildren();
card.hidden = !node || viewMode !== 'map';
modePill.hidden = !card.hidden;
if (node && viewMode === 'map') {
const isCenter = node.id === map.focusId;
const isSelf = node.id === selfKey;
card.setAttribute('aria-label', node.name);
const head = document.createElement('div');
head.className = 'net-card__head';
const avatarWrap = document.createElement('span');
avatarWrap.className = `net-card__avatar${node.shining ? ' is-shining' : ''}`;
avatarWrap.append(renderUserAvatar({
login: node.login, firstName: node.firstName, lastName: node.lastName, avatar: node.avatar, size: 'md', official: node.official,
}));
const titles = document.createElement('div');
titles.className = 'net-card__titles';
const name = document.createElement('div');
name.className = 'net-card__name';
name.textContent = node.name;
const meta = document.createElement('div');
meta.className = 'net-card__meta';
const parts = [];
if (normKey(node.name) !== node.id) parts.push(`@${node.login}`);
if (isCenter) parts.push(isSelf ? 'это вы' : 'в центре карты');
else parts.push(relationText(node));
if (node.shining) parts.push('сияющий');
meta.textContent = parts.join(' · ');
titles.append(name, meta);
const close = document.createElement('button');
close.type = 'button';
close.className = 'icon-btn net-card__close';
close.setAttribute('aria-label', 'Закрыть карточку');
close.innerHTML = iconHtml('close');
close.addEventListener('click', () => selectNode(''));
head.append(avatarWrap, titles, close);
card.append(head);
const note = isSelf ? null : notes.get(node.id);
const notePreview = createPersonNotePreview(note, { className: 'net-card__note', onClick: () => openNoteEditor(node) });
if (notePreview) card.append(notePreview);
const actions = document.createElement('div');
actions.className = 'net-card__actions';
if (!isCenter) {
const busy = expanding.has(node.id);
actions.append(cardAction('network', node.expanded ? 'Скрыть' : 'Связи', () => {
if (node.expanded) collapseNode(node.id);
else void expandNode(node.id);
}, { disabled: busy, pressed: node.expanded, busy }));
actions.append(cardAction('focus', 'В центр', () => recenter(node.login)));
}
actions.append(cardAction('profile', 'Профиль', () => {
const target = profileRoute(node.login);
if (target) navigate(target);
}));
if (!isSelf) {
actions.append(cardAction('message', 'Написать', () => navigate(`chat/${encodeURIComponent(node.login)}`)));
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';
more.textContent = `Ещё ${node.hiddenCount} – все видны на его карте («В центр»).`;
card.append(more);
}
}
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();
noteSheet = openPersonNoteSheet({ login: node.id, name: node.name, onClose: () => { noteSheet = null; } });
}
function onNotesChanged() {
notes = getAllPersonNotes();
renderMap();
}
window.addEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
// --- обозначения ---
function openLegend() {
legendSheet?.close();
legendSheet = openSheet({
title: 'Как читать карту',
className: 'net-legend-sheet',
onClose: () => { legendSheet = null; },
content: () => {
const legend = document.createElement('ul');
legend.className = 'net-legend';
const rows = [
['line', 'close_friend', 'Близкий друг'],
['line', 'friend', 'Друг'],
['line', 'contact', 'Контакт'],
['dash', 'friend', 'Пунктир – связь только с одной стороны'],
['aura', '', 'Свечение вокруг – сияющий'],
['badge', '', 'Синяя галочка – официальный аккаунт'],
['mark', '', 'Цветная точка – ваша заметка или метка'],
];
for (const [kind, type, text] of rows) {
const li = document.createElement('li');
li.className = 'net-legend__row';
const sample = document.createElement('span');
sample.className = `net-legend__sample net-legend__sample--${kind}`;
if (type) sample.dataset.type = type;
sample.setAttribute('aria-hidden', 'true');
const label = document.createElement('span');
label.textContent = text;
li.append(sample, label);
legend.append(li);
}
const tips = document.createElement('ul');
tips.className = 'net-legend__tips';
for (const tip of [
'«По близости»: ближе к центру – близкие, дальше – друзья, снаружи – контакты. Знакомые между собой стоят рядом.',
'Другие раскладки – в меню «•••»: по группам, «Подсолнух» и «Мандала».',
'«Друзья друзей» (в «Ещё» над картой) встают на внешнее кольцо, рядом с теми, через кого вы знакомы.',
'Нажмите на человека – откроется карточка. Двойное нажатие по пустому месту – вся карта.',
'Человека можно переставить: задержите на нём палец (мышью – просто тащите). Так появляется «Своя раскладка» – она запоминается для каждой карты на этом устройстве, и к ней можно вернуться из любой другой.',
]) {
const li = document.createElement('li');
li.textContent = tip;
tips.append(li);
}
const box = document.createElement('div');
box.className = 'stack';
box.append(legend, tips);
return box;
},
});
}
// --- шапка ---
function menuItems() {
const items = [];
if (!isSelfCenter()) {
items.push({ label: 'Мои связи', iconHtml: iconHtml('focus'), action: () => recenter(selfLogin) }, { divider: true });
}
if (viewMode === 'list') {
items.push(
{ label: 'По близости', selected: listSort === 'closeness', iconHtml: iconHtml(listSort === 'closeness' ? 'check' : 'network'), action: () => changeListSort('closeness') },
{ label: 'По имени', selected: listSort === 'name', iconHtml: iconHtml(listSort === 'name' ? 'check' : 'list'), action: () => changeListSort('name') },
);
return items;
}
const hasManual = hasManualLayout(normKey(centerLogin));
const active = currentLayout().id;
const layoutItem = (id, label, icon, extra = {}) => ({
label, selected: active === id, iconHtml: iconHtml(active === id ? 'check' : icon), action: () => changeLayoutMode(id), ...extra,
});
items.push(
layoutItem('rings', 'По близости', 'network'),
layoutItem('groups', 'По группам', 'pie'),
layoutItem('spiral', 'Подсолнух', 'spiral'),
layoutItem('mandala', 'Мандала', 'flower'),
hasManual
? layoutItem('manual', 'Своя раскладка', 'edit')
: { label: 'Своя раскладка', hint: 'Перетащите кого-нибудь на карте', disabled: true, iconHtml: iconHtml('edit') },
{ divider: true },
{ label: 'Показать всю карту', iconHtml: iconHtml('fit'), action: () => engine.fit() },
hasManual ? { label: 'Удалить свою раскладку', iconHtml: iconHtml('trash'), action: () => deleteManualLayout() } : null,
{ divider: true },
{ label: 'Как читать карту', iconHtml: iconHtml('info'), action: openLegend },
);
return items;
}
const headerActions = () => [
{
icon: 'search',
title: 'Найти человека',
ariaLabel: 'Найти человека',
className: 'network-search-btn',
onClick: () => openSearch(),
},
{
iconNode: createOverflowDots(),
title: viewMode === 'list' ? 'Порядок списка' : 'Настройки карты',
ariaLabel: viewMode === 'list' ? 'Порядок списка' : 'Настройки карты',
className: 'topbar-overflow-action--raised',
menu: { minWidth: 240, items: menuItems },
},
];
let headerKey = '';
function syncHeader({ force = false } = {}) {
if (search || disposed) return;
const center = map?.byId.get(map.focusId);
const self = isSelfCenter();
const count = map ? map.nodes.filter((node) => node.tier === 1 && node.id !== map.focusId).length : -1;
const key = `${self ? 'self' : normKey(centerLogin)}|${center?.name || ''}|${viewMode}|${count}`;
if (!force && key === headerKey) return;
headerKey = key;
if (self) {
chrome?.setTopbar(createTopBar({ title: 'Связи', className: 'topbar--root', actions: headerActions() }));
return;
}
// Чужая карта: кто в центре и сколько у него связей; стрелка – к своей карте.
const identity = document.createElement('button');
identity.type = 'button';
identity.className = 'topbar-identity';
identity.title = 'Открыть профиль';
identity.append(renderUserAvatar({
login: centerLogin, firstName: center?.firstName, lastName: center?.lastName, avatar: center?.avatar, size: 'sm',
}));
const text = document.createElement('span');
text.className = 'topbar-identity__text';
const title = document.createElement('span');
title.className = 'topbar-identity__title';
title.textContent = center?.name || centerLogin;
const sub = document.createElement('span');
sub.className = 'topbar-identity__sub';
sub.textContent = count >= 0 ? `Связи · ${count}` : 'Связи';
text.append(title, sub);
identity.append(text);
identity.addEventListener('click', () => navigate(profileRoute(centerLogin)));
chrome?.setTopbar(createTopBar({
className: 'topbar--identity',
back: { onClick: () => recenter(selfLogin), ariaLabel: 'К моим связям', title: 'К моим связям' },
center: identity,
actions: headerActions(),
}));
}
// --- раскладки ---
// Своя раскладка – у каждой карты своя; если у этой карты её нет, видна последняя
// выбранная автоматическая.
function currentLayout() {
const key = normKey(centerLogin);
if (layoutMode === 'manual' && hasManualLayout(key)) {
return { id: 'manual', mode: getManualBase(key), manual: getManualLayout(key) };
}
const mode = layoutMode === 'manual' ? getAutoLayoutMode() : layoutMode;
return { id: mode, mode, manual: new Map() };
}
function changeLayoutMode(mode) {
if (mode === currentLayout().id) return;
layoutMode = mode;
setLayoutMode(mode);
renderMap({ relayout: true, fit: true });
}
// Человека перетащили. В своей раскладке – запоминаем его место; в автоматической –
// вся картина становится своей раскладкой этой карты (прежнюю можно вернуть «Отменить»).
function onNodeMoved(node, point) {
const key = normKey(centerLogin);
const layout = currentLayout();
if (layout.id === 'manual') {
setManualPoint(key, node.id, point);
return;
}
const points = engine.getPositions();
points.set(node.id, point);
const previousMode = layoutMode;
const previous = saveManualLayout(key, points, layout.mode);
layoutMode = 'manual';
setLayoutMode('manual');
renderMap();
showToast(previous ? 'Своя раскладка заменена этой' : 'Сохранено как своя раскладка', {
kind: 'info',
timeoutMs: 5000,
action: {
label: 'Отменить',
onClick: () => {
if (disposed || normKey(centerLogin) !== key) return;
restoreManualLayout(key, previous);
layoutMode = previousMode;
setLayoutMode(previousMode);
renderMap({ relayout: true });
},
},
});
}
function deleteManualLayout() {
const key = normKey(centerLogin);
const removed = clearManualLayout(key);
renderMap({ relayout: true, fit: true });
showToast('Своя раскладка удалена', {
kind: 'info',
timeoutMs: 5000,
action: {
label: 'Вернуть',
onClick: () => {
if (disposed || normKey(centerLogin) !== key) return;
restoreManualLayout(key, removed);
layoutMode = 'manual';
setLayoutMode('manual');
renderMap({ relayout: true, fit: true });
},
},
});
}
function changeListSort(sort) {
if (sort === listSort) return;
listSort = sort;
setViewSetting('listSort', sort);
renderList();
list.scrollTop = 0;
}
// --- фильтры: «Все / Близкие / Друзья / Контакты» – тем же переключателем, что в чатах;
// реже нужное («Добавили вас», «Сияющие», «С заметкой», «Друзья друзей») – в «Ещё».
const PRIMARY_FILTERS = ['all', 'close', 'friends', 'contacts'];
const EXTRA_FILTERS = [
{ id: 'incoming', short: 'Добавили', icon: 'user-plus' },
{ id: 'shining', short: 'Сияющие', icon: 'sparkle' },
{ id: 'notes', short: 'С заметкой', icon: 'edit' },
];
const filterBar = document.createElement('div');
filterBar.className = 'net-filters';
filterBar.addEventListener('pointerdown', (event) => event.stopPropagation());
const filterTabs = document.createElement('div');
filterTabs.className = 'tabs tabs--auto tabs--dense net-filters__tabs';
filterTabs.setAttribute('role', 'radiogroup');
filterTabs.setAttribute('aria-label', 'Кого показывать');
filterBar.append(filterTabs);
const filterButtons = new Map();
for (const id of PRIMARY_FILTERS) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'tab-btn';
button.dataset.filter = id;
button.setAttribute('role', 'radio');
button.textContent = FILTER_BY_ID.get(id).label;
button.addEventListener('click', () => setFilter(id));
filterButtons.set(id, button);
filterTabs.append(button);
}
const moreFilter = document.createElement('button');
moreFilter.type = 'button';
moreFilter.className = 'tab-btn net-filters__more';
filterTabs.append(moreFilter);
filterTabs.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
const visible = PRIMARY_FILTERS.filter((id) => !filterButtons.get(id).hidden);
const index = Math.max(0, visible.indexOf(filterId));
const next = visible[(index + (event.key === 'ArrowRight' ? 1 : -1) + visible.length) % visible.length];
setFilter(next);
filterButtons.get(next)?.focus();
event.preventDefault();
});
function filterCounts() {
const direct = (map?.nodes || []).filter((node) => node.tier === 1 && node.id !== map.focusId);
const everyone = (map?.nodes || []).filter((node) => node.id !== map?.focusId);
const counts = new Map();
for (const filter of FILTERS) {
const pool = filter.direct ? direct : everyone;
counts.set(filter.id, filter.pred ? pool.filter(filter.pred).length : direct.length);
}
return counts;
}
const moreMenu = createDropdownMenu({
anchorEl: moreFilter,
minWidth: 236,
placement: 'bottom-end',
items: () => {
const counts = filterCounts();
const items = EXTRA_FILTERS
.filter(({ id }) => !(FILTER_BY_ID.get(id).selfOnly && !isSelfCenter()))
.map(({ id, icon }) => {
const selected = filterId === id;
const n = counts.get(id) || 0;
return {
label: `${FILTER_BY_ID.get(id).label} · ${n}`,
selected,
disabled: !n && !selected,
iconHtml: iconHtml(selected ? 'check' : icon),
action: () => setFilter(selected ? 'all' : id),
};
});
items.push({ divider: true }, {
label: 'Друзья друзей',
hint: friendsOfFriends ? 'Показаны – нажмите, чтобы скрыть' : 'Кто дружит с вашими друзьями',
selected: friendsOfFriends,
iconHtml: iconHtml(friendsOfFriends ? 'check' : 'network'),
action: toggleFriendsOfFriends,
});
return items;
},
});
function setFilter(id) {
filterId = FILTER_BY_ID.has(id) ? id : 'all';
engine.setFilter(filterPredicate());
engine.fit();
const selected = selectedId ? map?.byId.get(selectedId) : null;
if (selected && selectedId !== map.focusId && filterPredicate() && !filterPredicate()(selected)) selectNode('');
syncFilters();
syncStateMessage();
if (viewMode === 'list') {
renderList();
list.scrollTop = 0;
}
persist();
}
function syncFilters() {
const counts = filterCounts();
for (const id of PRIMARY_FILTERS) {
const button = filterButtons.get(id);
const selected = id === filterId;
// Пустую группу не показываем (кроме выбранной и «Все»).
button.hidden = !selected && id !== 'all' && Boolean(map) && !counts.get(id);
button.setAttribute('aria-checked', selected ? 'true' : 'false');
}
const extra = EXTRA_FILTERS.find(({ id }) => id === filterId);
moreFilter.classList.toggle('active', Boolean(extra));
// Точка на «Ещё» – включено что-то из меню (друзья друзей), а на самой кнопке этого не видно.
moreFilter.classList.toggle('has-dot', !extra && friendsOfFriends);
moreFilter.innerHTML = `${iconHtml('chevron-down')}`;
moreFilter.querySelector('.net-filters__more-label').textContent = extra ? extra.short : 'Ещё';
moreFilter.setAttribute('aria-label', extra
? `${FILTER_BY_ID.get(extra.id).label}. Другие фильтры`
: `Другие фильтры${friendsOfFriends ? ', друзья друзей показаны' : ''}`);
}
// --- масштаб ---
const zoomBar = document.createElement('div');
zoomBar.className = 'net-zoom';
zoomBar.addEventListener('pointerdown', (event) => event.stopPropagation());
for (const [icon, label, onClick] of [
['plus', 'Приблизить', () => engine.zoomBy(1.35)],
['minus', 'Отдалить', () => engine.zoomBy(1 / 1.35)],
['fit', 'Показать всю карту', () => engine.fit()],
]) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'icon-btn net-zoom__btn';
button.innerHTML = iconHtml(icon);
button.setAttribute('aria-label', label);
button.title = label;
button.addEventListener('click', onClick);
zoomBar.append(button);
}
// --- карта / список ---
const modePill = document.createElement('button');
modePill.type = 'button';
modePill.className = 'net-mode-pill';
modePill.addEventListener('pointerdown', (event) => event.stopPropagation());
modePill.addEventListener('click', () => setViewMode(viewMode === 'map' ? 'list' : 'map'));
function syncModePill() {
const toList = viewMode === 'map';
modePill.innerHTML = `${iconHtml(toList ? 'list' : 'network')}${toList ? 'Списком' : 'На карте'}`;
modePill.setAttribute('aria-label', toList ? 'Показать списком' : 'Показать на карте');
}
function setViewMode(mode) {
viewMode = mode === 'list' ? 'list' : 'map';
setViewSetting('view', viewMode);
screen.dataset.view = viewMode;
list.hidden = viewMode !== 'list';
board.hidden = viewMode !== 'map';
zoomBar.hidden = viewMode !== 'map';
if (viewMode === 'list') {
renderList();
list.scrollTop = 0;
}
syncModePill();
renderCard();
syncStateMessage();
syncHeader({ force: true });
if (search) renderSearchResults();
}
// --- список ---
const rowMenuAnchor = document.createElement('span');
rowMenuAnchor.className = 'net-row-menu-anchor';
rowMenuAnchor.setAttribute('aria-hidden', 'true');
let rowMenuNode = null;
const rowMenu = createDropdownMenu({
anchorEl: rowMenuAnchor,
minWidth: 220,
transparent: true,
items: () => {
const node = rowMenuNode;
if (!node) return [];
return [
{ label: 'Профиль', iconHtml: iconHtml('profile'), action: () => navigate(profileRoute(node.login)) },
{ label: 'Заметка', iconHtml: iconHtml('edit'), action: () => openNoteEditor(node) },
{ label: 'Показать на карте', iconHtml: iconHtml('network'), action: () => showOnMap(node.id) },
{ label: 'Его связи', iconHtml: iconHtml('focus'), action: () => recenter(node.login) },
];
},
});
function openRowMenu(node, button) {
rowMenuNode = node;
const rect = button.getBoundingClientRect();
const host = stage.getBoundingClientRect();
rowMenuAnchor.style.top = `${rect.bottom - host.top - 6}px`;
rowMenuAnchor.style.left = `${rect.right - host.left - 8}px`;
rowMenu.open();
}
function showOnMap(id) {
if (search) closeSearch();
setViewMode('map');
// Карта только что стала видимой – камера двигается после того, как узнает размер.
window.requestAnimationFrame(() => {
if (disposed) return;
engine.reveal(id);
selectNode(id);
});
}
// Вторая строка – только то, чего не видно из раздела: тип связи нужен, когда список
// не разбит по типам, «взаимно» – обычный случай и не пишется.
function personRow(node, { onOpen = null, withType = false } = {}) {
const note = notes.get(node.id);
const sub = [];
if (normKey(node.name) !== node.id) sub.push(`@${node.login}`);
if (node.tier > 1) {
const via = map.byId.get(node.parentId);
if (via) sub.push(`через ${via.name}`);
} else {
if (withType) sub.push((RELATION_LABEL[node.relationType] || 'связь').toLowerCase());
if (node.direction === 'out') sub.push('без ответа');
}
if (node.shining) sub.push('сияющий');
return createPersonRow({
login: node.login,
name: node.name,
firstName: node.firstName,
lastName: node.lastName,
avatar: node.avatar,
official: node.official,
sub: sub.join(' · '),
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) : '',
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) },
],
});
}
function matchesQuery(node, query) {
if (!query) return true;
return matchesPeopleQuery(`${node.name} ${node.login} ${node.firstName || ''} ${node.lastName || ''}`, query);
}
function listGroups(people) {
const byName = (a, b) => a.name.localeCompare(b.name, 'ru');
if (listSort === 'name') {
const groups = new Map();
[...people].sort(byName).forEach((node) => {
const first = node.name.trim()[0]?.toUpperCase() || '#';
const letter = /\p{L}/u.test(first) ? first.replace('Ё', 'Е') : '#';
if (!groups.has(letter)) groups.set(letter, []);
groups.get(letter).push(node);
});
return [...groups.entries()].map(([title, items]) => ({ title, items, letter: true }));
}
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));
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);
}
function renderList() {
if (disposed || viewMode !== 'list') return;
const scrollTop = list.scrollTop;
list.replaceChildren();
if (!map) return;
const pred = filterPredicate();
const query = searchText(search?.query || '');
const people = map.nodes.filter((node) => node.id !== map.focusId && (!pred || pred(node)) && matchesQuery(node, query));
const frag = document.createDocumentFragment();
const withType = listSort === 'name' || Boolean(query);
for (const group of listGroups(people)) {
frag.append(createListSection(group.letter ? group.title : `${group.title} · ${group.items.length}`));
// Длинный «Добавили вас» не должен закрывать собой весь список: сначала трое.
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')}Показать всех · ${group.items.length}`;
more.addEventListener('click', () => { waitingExpanded = true; renderList(); });
frag.append(more);
}
}
if (query) appendRemoteResults(frag, new Set(people.map((node) => node.id)));
if (!people.length && map.nodes.length > 1 && !(query && search?.remote?.items?.length)) {
frag.append(createStateMessage(query
? { icon: 'search', title: 'Никого не нашлось', text: 'Проверьте имя или логин.' }
: { icon: 'search', title: 'Никого не нашлось', text: 'Под этот фильтр сейчас никто не подходит.', actionLabel: 'Показать всех', onAction: () => setFilter('all') }));
}
list.append(frag);
list.scrollTop = restoreListScroll || scrollTop;
restoreListScroll = 0;
}
// --- поиск ---
let remoteTimer = 0;
function openSearch() {
if (search) {
search.topbar.searchInput?.focus();
return;
}
selectNode('');
const topbar = createSearchTopBar({
placeholder: 'Имя или логин',
onInput: (value) => {
search.query = value;
scheduleRemoteSearch();
renderSearchResults();
},
onSubmit: () => {
const host = viewMode === 'list' ? list : searchPanel;
const first = host.querySelector('.person-row__main');
if (first instanceof HTMLElement) first.click();
},
onClose: () => closeSearch(),
});
search = {
query: '',
topbar,
layer: openHistoryLayer(() => closeSearch({ fromHistory: true })),
remote: { seq: 0, query: '', items: [], loading: false, failed: false },
};
chrome?.setTopbar(topbar);
topbar.searchInput?.focus();
renderSearchResults();
// На телефоне клавиатура может не открыться без повторного фокуса после отрисовки.
window.requestAnimationFrame(() => { if (search?.topbar === topbar) topbar.searchInput?.focus(); });
}
function closeSearch({ fromHistory = false } = {}) {
if (!search) return;
const { layer } = search;
window.clearTimeout(remoteTimer);
search = null;
if (!fromHistory) layer?.close();
searchPanel.hidden = true;
searchPanel.replaceChildren();
if (!disposed) {
syncHeader({ force: true });
if (viewMode === 'list') renderList();
}
}
function scheduleRemoteSearch() {
window.clearTimeout(remoteTimer);
const query = searchText(search?.query).replace(/^@/, '');
const remote = search.remote;
remote.seq += 1;
remote.items = [];
remote.failed = false;
remote.loading = query.length >= 2;
remote.query = query;
if (!remote.loading) return;
const seq = remote.seq;
remoteTimer = window.setTimeout(async () => {
try {
const users = await authService.searchPeople(query, { limit: 12 });
if (disposed || !search || search.remote.seq !== seq) return;
remote.items = Array.isArray(users) ? users : [];
} catch {
if (disposed || !search || search.remote.seq !== seq) return;
remote.failed = true;
}
remote.loading = false;
renderSearchResults();
}, 320);
}
// Люди со всей сети, которых нет на карте: выбранный становится её центром.
function appendRemoteResults(target, shownIds) {
const remote = search?.remote;
if (!remote || !remote.query) return;
const items = remote.items.filter((user) => {
const key = normKey(user?.login);
return key && !shownIds.has(key) && !map?.byId.has(key);
});
if (!remote.loading && !remote.failed && !items.length) return;
target.append(createListSection('Во всей сети'));
if (remote.loading) {
const loading = document.createElement('div');
loading.className = 'loading-state net-search-loading';
loading.style.setProperty('--loading-delay', '150ms');
loading.append(createSpinner({ size: 'sm', label: 'Ищу' }));
target.append(loading);
return;
}
if (remote.failed) {
const fail = document.createElement('p');
fail.className = 'net-search-note';
fail.textContent = 'Поиск по всей сети сейчас недоступен. Проверьте соединение.';
target.append(fail);
return;
}
for (const user of items) {
const login = normalizeLogin(user.login);
const name = String(user.displayName || '').trim();
target.append(createPersonRow({
login,
name: name || login,
avatar: user.avatarAr ? { ar: user.avatarAr } : null,
sub: name && normKey(name) !== normKey(login) ? `@${login} · показать его связи` : 'показать его связи',
onClick: () => recenter(login),
actions: [{ icon: 'profile', label: 'Профиль', onClick: () => { closeSearch(); navigate(profileRoute(login)); } }],
}));
}
}
function renderSearchResults() {
if (!search) return;
if (viewMode === 'list') {
searchPanel.hidden = true;
renderList();
return;
}
searchPanel.replaceChildren();
searchPanel.hidden = false;
const query = searchText(search.query);
const frag = document.createDocumentFragment();
if (!query) {
const hint = document.createElement('p');
hint.className = 'net-search-note';
hint.textContent = 'Найдите человека на этой карте или во всей сети.';
frag.append(hint);
searchPanel.append(frag);
return;
}
const found = (map?.nodes || [])
.filter((node) => node.id !== map.focusId && matchesQuery(node, query))
.sort((a, b) => {
const aStarts = searchText(a.name).startsWith(query) || a.id.startsWith(query) ? 0 : 1;
const bStarts = searchText(b.name).startsWith(query) || b.id.startsWith(query) ? 0 : 1;
return aStarts - bStarts || a.tier - b.tier || a.name.localeCompare(b.name, 'ru');
});
if (found.length) {
frag.append(createListSection(`На карте · ${found.length}`));
// На карте выбор – показать человека, а не уйти в профиль.
found.slice(0, 30).forEach((node) => frag.append(personRow(node, { onOpen: () => showOnMap(node.id), withType: true })));
}
appendRemoteResults(frag, new Set(found.map((node) => node.id)));
if (!found.length && !search.remote.loading && !search.remote.items.length) {
frag.append(createStateMessage({ icon: 'search', title: 'Никого не нашлось', text: 'Проверьте имя или логин.' }));
}
searchPanel.append(frag);
}
function onKeydown(event) {
const typing = event.target instanceof HTMLElement && event.target.closest('input, textarea, [contenteditable="true"]');
const overlayOpen = Boolean(noteSheet || legendSheet || document.querySelector('.dropdown-portal, .modal'));
if (event.key === 'Escape') {
if (!selectedId || overlayOpen || search) return;
selectNode('');
return;
}
// Клавиши для компьютера: «/» – поиск, «+»/«−» – масштаб, «0» – вся карта.
if (typing || overlayOpen || event.ctrlKey || event.metaKey || event.altKey) return;
if (event.key === '/') {
event.preventDefault();
openSearch();
} else if (viewMode === 'map' && (event.key === '+' || event.key === '=')) {
engine.zoomBy(1.35);
} else if (viewMode === 'map' && (event.key === '-' || event.key === '_')) {
engine.zoomBy(1 / 1.35);
} else if (viewMode === 'map' && event.key === '0') {
engine.fit();
}
}
document.addEventListener('keydown', onKeydown);
const overlayObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(() => placeOverlays()) : null;
overlayObserver?.observe(stage);
overlayObserver?.observe(filterBar);
screen.cleanup = () => {
if (disposed) return;
disposed = true;
if (map) {
persisted.view = engine.getView();
persisted.listScroll = viewMode === 'list' ? list.scrollTop : 0;
}
engine.destroy();
overlayObserver?.disconnect();
rowMenu.destroy();
moreMenu.destroy();
window.cancelAnimationFrame(listFrame);
window.clearTimeout(remoteTimer);
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
document.removeEventListener('keydown', onKeydown);
noteSheet?.close();
legendSheet?.close();
if (search) {
const { layer } = search;
search = null;
layer?.close();
}
};
syncModePill();
board.hidden = viewMode !== 'map';
zoomBar.hidden = viewMode !== 'map';
syncFilters();
syncHeader({ force: true });
stage.append(board, list, filterBar, overlay, busyPill, zoomBar, modePill, card, searchPanel, rowMenuAnchor, a11yList);
screen.append(stage);
persist();
if (centerLogin) void load(centerLogin);
else syncStateMessage();
return screen;
}