SHA256
Личные сообщения: - поиск по переписке с подсветкой, переход к дате по календарю; - экран «Медиа и файлы» (/chat/<login>/media); - «без звука» и закрепление чатов (на устройстве), push от заглушённых не показывается; - новая нижняя панель ввода, круглый спиннер истории, медиа-карусель; - история загружается в ~16 раз быстрее: ключ расшифровки достаётся один раз на страницу; - исправлены прозрачные окна подтверждения в чате. Связи: - карта переписана на canvas (graph-canvas.js вместо force-graph.js): плавная анимация без дёрганья, панорама, масштаб щипком/колесом/кнопками, перетаскивание людей; - ручная раскладка и режимы «По близости»/«По группам» запоминаются на устройстве; - цвет нити – тип связи, пунктир – связь с одной стороны, аура только у сияющих; - карточка человека: раскрыть связи на месте, в центр, профиль, написать, заметка; - «Недавние» заменены раскрытием связей; фильтр «Заметки». Личные заметки о людях (текст и цветная метка, только на устройстве) – на карте и в профиле.
984 lines
39 KiB
JavaScript
984 lines
39 KiB
JavaScript
// Экран «Связи»: карта людей вокруг выбранного человека.
|
||
// Данные – GetUserConnectionsGraph (только чтение). Рисует карту graph-canvas.js, здесь –
|
||
// состав карты (центр, раскрытые связи), фильтры, карточка выбранного человека и заметки.
|
||
import { createTopBar } from '../components/topbar.js';
|
||
import { createOverflowDots } from '../components/overflow-dots.js';
|
||
import { iconHtml } from '../components/ui-icon.js';
|
||
import { openSheet } from '../components/sheet.js';
|
||
import { authService, state } from '../state.js';
|
||
import { makeProfileRoute, makeProfileLinksRoute } from '../services/shine-routes.js';
|
||
import { userDisplayName } from '../services/user-display.js';
|
||
import { showToast } from '../services/channels-ux.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, getLayoutMode, getManualLayout, setLayoutMode, setManualPoint,
|
||
} 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',
|
||
},
|
||
};
|
||
|
||
const GENDER_MALE = 'male';
|
||
const GENDER_FEMALE = 'female';
|
||
const GENDER_UNKNOWN = 'unknown';
|
||
|
||
function normalizeLogin(value) {
|
||
return String(value || '').trim();
|
||
}
|
||
|
||
function createDebounced(fn, delayMs = 2000) {
|
||
let timer = 0;
|
||
return (...args) => {
|
||
if (timer) window.clearTimeout(timer);
|
||
timer = window.setTimeout(() => fn(...args), delayMs);
|
||
};
|
||
}
|
||
|
||
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 escapeHtml(text) {
|
||
return String(text || '')
|
||
.replaceAll('&', '&')
|
||
.replaceAll('<', '<')
|
||
.replaceAll('>', '>')
|
||
.replaceAll('"', '"')
|
||
.replaceAll("'", ''');
|
||
}
|
||
|
||
function normalizeGender(value) {
|
||
const clean = String(value || '').trim().toLowerCase();
|
||
if (clean === GENDER_MALE) return GENDER_MALE;
|
||
if (clean === GENDER_FEMALE) return GENDER_FEMALE;
|
||
return GENDER_UNKNOWN;
|
||
}
|
||
|
||
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',
|
||
officialLabel: String(row?.officialLabel || (row?.official ? 'официальный' : 'неофициальный')),
|
||
shineLabel: String(row?.shineLabel || (row?.shine ? 'сияющий' : 'несияющий')),
|
||
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 applyRelativeGender(map, rows) {
|
||
(Array.isArray(rows) ? rows : []).forEach((row) => {
|
||
const login = normalizeLogin(row?.login);
|
||
if (!login) return;
|
||
const key = normKey(login);
|
||
const gender = normalizeGender(row?.gender);
|
||
const prev = map.get(key) || GENDER_UNKNOWN;
|
||
if (prev === GENDER_UNKNOWN || gender !== GENDER_UNKNOWN) map.set(key, gender);
|
||
});
|
||
}
|
||
|
||
function getRelativeGenderMap(graph) {
|
||
const map = new Map();
|
||
// Родственные связи пока скрыты из UI, хотя сервер продолжает хранить их коды.
|
||
void graph;
|
||
return map;
|
||
}
|
||
|
||
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 outParents = toSet(graph?.outParents);
|
||
const inParents = toSet(graph?.inParents);
|
||
const outChildren = toSet(graph?.outChildren);
|
||
const inChildren = toSet(graph?.inChildren);
|
||
const outSiblings = toSet(graph?.outSiblings);
|
||
const inSiblings = toSet(graph?.inSiblings);
|
||
const outSpouses = toSet(graph?.outSpouses);
|
||
const inSpouses = toSet(graph?.inSpouses);
|
||
// контакты/подписки/знакомые — для слоя «Все контакты» (Фаза 3)
|
||
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 relativesGender = getRelativeGenderMap(graph);
|
||
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);
|
||
|
||
let role = 'contact';
|
||
if (closeFriendOut || closeFriendIn || friendOut || friendIn) role = 'friend';
|
||
|
||
let forward = role === 'friend' ? (closeFriendOut || friendOut) : contactOut;
|
||
let backward = role === 'friend' ? (closeFriendIn || friendIn) : contactIn;
|
||
|
||
return {
|
||
login: targetLogin,
|
||
key: normKey(targetLogin),
|
||
role,
|
||
isRelative: false,
|
||
gender: normalizeGender(relativesGender.get(normKey(targetLogin))),
|
||
forward: Boolean(forward),
|
||
backward: Boolean(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();
|
||
|
||
async function getConnectionsGraphCached(login, { force = false, retries = 0 } = {}) {
|
||
const clean = normalizeLogin(login);
|
||
const key = normKey(clean);
|
||
if (!key) throw new Error('LOGIN_REQUIRED');
|
||
const now = Date.now();
|
||
const cached = networkGraphCache.get(key);
|
||
if (!force && cached && now - cached.savedAt < NETWORK_GRAPH_CACHE_TTL_MS) return cached.graph;
|
||
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 openUserSearchModal(onPick) {
|
||
const root = document.getElementById('modal-root');
|
||
if (!(root instanceof HTMLElement)) return;
|
||
root.innerHTML = `
|
||
<div class="modal" id="network-search-modal">
|
||
<div class="modal-card stack">
|
||
<button class="icon-btn" type="button" id="network-search-close" style="justify-self:end;">✕</button>
|
||
<h3 class="modal-title">Найти пользователя</h3>
|
||
<div class="row" style="gap:8px;">
|
||
<input class="input" id="network-search-input" type="text" maxlength="30" placeholder="Введите логин" />
|
||
<button class="primary-btn" type="button" id="network-search-run">Искать</button>
|
||
</div>
|
||
<div class="meta-muted" id="network-search-meta">Введите логин. Поиск начнётся автоматически через 2 секунды.</div>
|
||
<div class="stack" id="network-search-results"></div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
|
||
const modal = root.querySelector('#network-search-modal');
|
||
const closeBtn = root.querySelector('#network-search-close');
|
||
const inputEl = root.querySelector('#network-search-input');
|
||
const runBtn = root.querySelector('#network-search-run');
|
||
const metaEl = root.querySelector('#network-search-meta');
|
||
const resultsEl = root.querySelector('#network-search-results');
|
||
if (!(modal instanceof HTMLElement) || !(inputEl instanceof HTMLInputElement) || !(resultsEl instanceof HTMLElement)) {
|
||
root.innerHTML = '';
|
||
return;
|
||
}
|
||
|
||
let selectedLogin = '';
|
||
let searchSeq = 0;
|
||
|
||
const close = () => {
|
||
root.innerHTML = '';
|
||
};
|
||
|
||
const applySelection = (login) => {
|
||
selectedLogin = normalizeLogin(login);
|
||
const rows = resultsEl.querySelectorAll('[data-candidate]');
|
||
rows.forEach((row) => {
|
||
if (!(row instanceof HTMLElement)) return;
|
||
row.classList.toggle('is-selected', String(row.dataset.candidate || '') === selectedLogin);
|
||
});
|
||
};
|
||
|
||
const renderCandidates = (logins) => {
|
||
const items = (Array.isArray(logins) ? logins : [])
|
||
.map((item) => normalizeLogin(item))
|
||
.filter(Boolean)
|
||
.slice(0, 5);
|
||
if (!items.length) {
|
||
resultsEl.innerHTML = '<div class="meta-muted">Кандидаты не найдены.</div>';
|
||
applySelection('');
|
||
return;
|
||
}
|
||
resultsEl.innerHTML = items.map((login) => (
|
||
`<button type="button" class="ghost-btn network-search-candidate" data-candidate="${escapeHtml(login)}">${escapeHtml(login)}</button>`
|
||
)).join('');
|
||
applySelection('');
|
||
};
|
||
|
||
const runSearch = async () => {
|
||
const query = normalizeLogin(inputEl.value);
|
||
if (!query) {
|
||
metaEl.textContent = 'Введите логин.';
|
||
renderCandidates([]);
|
||
return;
|
||
}
|
||
const reqId = ++searchSeq;
|
||
metaEl.textContent = `Поиск по «${query}»...`;
|
||
if (runBtn instanceof HTMLButtonElement) runBtn.disabled = true;
|
||
try {
|
||
const found = await authService.searchUsers(query);
|
||
if (reqId !== searchSeq) return;
|
||
renderCandidates(found);
|
||
const foundCount = Math.min(5, Array.isArray(found) ? found.length : 0);
|
||
metaEl.textContent = foundCount > 0
|
||
? `Найдено кандидатов: ${foundCount}. Выберите одного.`
|
||
: 'Кандидаты не найдены.';
|
||
} catch (error) {
|
||
if (reqId !== searchSeq) return;
|
||
renderCandidates([]);
|
||
metaEl.textContent = `Ошибка поиска: ${error?.message || 'unknown'}`;
|
||
} finally {
|
||
if (runBtn instanceof HTMLButtonElement) runBtn.disabled = false;
|
||
}
|
||
};
|
||
|
||
modal.addEventListener('click', (event) => {
|
||
if (event.target === modal) close();
|
||
});
|
||
closeBtn?.addEventListener('click', close);
|
||
runBtn?.addEventListener('click', () => { void runSearch(); });
|
||
const debouncedSearch = createDebounced(() => { void runSearch(); }, 2000);
|
||
inputEl.addEventListener('input', debouncedSearch);
|
||
inputEl.addEventListener('keydown', (event) => {
|
||
if (event.key === 'Enter') {
|
||
event.preventDefault();
|
||
void runSearch();
|
||
}
|
||
});
|
||
resultsEl.addEventListener('click', (event) => {
|
||
const target = event.target;
|
||
if (!(target instanceof HTMLElement)) return;
|
||
const button = target.closest('[data-candidate]');
|
||
if (!(button instanceof HTMLElement)) return;
|
||
const nextLogin = String(button.dataset.candidate || '');
|
||
applySelection(nextLogin);
|
||
if (!nextLogin) return;
|
||
close();
|
||
onPick(nextLogin);
|
||
});
|
||
|
||
window.setTimeout(() => inputEl.focus(), 0);
|
||
return close;
|
||
}
|
||
|
||
// --- Состав карты ---------------------------------------------------------------------------
|
||
|
||
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: 'Контакт' };
|
||
|
||
// Переживает уход с экрана: возврат по «Связям» из профиля показывает ту же карту.
|
||
const persisted = { centerLogin: '', expanded: [], filters: [], friendsOfFriends: false };
|
||
|
||
const FILTERS = {
|
||
close: { label: 'Близкие', pred: (node) => node.relationType === 'close_friend' },
|
||
shining: { label: 'Сияющие', pred: (node) => Boolean(node.shining) },
|
||
notes: { label: 'Заметки', pred: (node) => Boolean(node.mark || node.hasNote) },
|
||
};
|
||
const FILTER_ORDER = ['close', 'shining', 'notes'];
|
||
|
||
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: '' });
|
||
for (const peer of peers) {
|
||
add({ ...peer.person, relationType: peer.relationType, mutual: peer.mutual, 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, 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 selfKey = normKey(state.session.login);
|
||
|
||
let centerLogin = routeLogin || (keepHistory && persisted.centerLogin) || normalizeLogin(state.session.login || '');
|
||
const restore = keepHistory && normKey(persisted.centerLogin) === normKey(centerLogin);
|
||
const expanded = new Set(restore ? persisted.expanded : []);
|
||
const activeFilters = new Set(keepHistory ? persisted.filters : []);
|
||
let friendsOfFriends = restore && persisted.friendsOfFriends;
|
||
let layoutMode = getLayoutMode();
|
||
let notes = getAllPersonNotes();
|
||
const graphs = new Map();
|
||
const expanding = new Set();
|
||
let map = null;
|
||
let selectedId = '';
|
||
let disposed = false;
|
||
let loadSeq = 0;
|
||
let closeSearch = null;
|
||
let noteSheet = null;
|
||
let legendSheet = null;
|
||
|
||
const screen = document.createElement('section');
|
||
screen.className = 'network-screen';
|
||
const stage = document.createElement('div');
|
||
stage.className = 'network-stage';
|
||
const board = document.createElement('div');
|
||
board.className = 'network-board network-board--full net-board';
|
||
const status = document.createElement('div');
|
||
status.className = 'net-status';
|
||
status.hidden = true;
|
||
const a11yList = document.createElement('ul');
|
||
a11yList.className = 'sr-only';
|
||
a11yList.setAttribute('aria-label', 'Люди на карте');
|
||
|
||
function persist() {
|
||
persisted.centerLogin = centerLogin;
|
||
persisted.expanded = [...expanded];
|
||
persisted.filters = [...activeFilters];
|
||
persisted.friendsOfFriends = friendsOfFriends;
|
||
}
|
||
|
||
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 filterPredicate() {
|
||
if (!activeFilters.size) return null;
|
||
return (node) => [...activeFilters].every((key) => FILTERS[key].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 ? 0 : card.offsetHeight + 12) + 8;
|
||
return { top, bottom };
|
||
}
|
||
|
||
function placeOverlays() {
|
||
const overlap = toolbarOverlap();
|
||
card.style.bottom = `${overlap + 12}px`;
|
||
zoomBar.style.bottom = `${overlap + 12 + (card.hidden ? 0 : card.offsetHeight + 10)}px`;
|
||
}
|
||
|
||
const engine = createGraphCanvas({
|
||
stage: board,
|
||
getInsets: insets,
|
||
onSelect: (node) => selectNode(node ? node.id : ''),
|
||
onNodeMoved: (node, point) => {
|
||
setManualPoint(normKey(centerLogin), node.id, point);
|
||
},
|
||
});
|
||
|
||
function renderMap({ fit = false, relayout = false } = {}) {
|
||
if (disposed) return;
|
||
map = composeMap(centerLogin, graphs, expanded, notes);
|
||
if (!map) return;
|
||
engine.setGraph(map, { manual: getManualLayout(normKey(centerLogin)), mode: layoutMode, relayout, fit });
|
||
renderA11y();
|
||
if (selectedId && !map.byId.has(selectedId)) selectNode('');
|
||
else if (selectedId) renderCard();
|
||
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);
|
||
}
|
||
}
|
||
|
||
function showStatus(text) {
|
||
status.textContent = text;
|
||
status.hidden = !text;
|
||
}
|
||
|
||
async function load(login, { push = false } = {}) {
|
||
const clean = normalizeLogin(login);
|
||
if (!clean) return;
|
||
const seq = ++loadSeq;
|
||
if (!graphs.has(normKey(clean))) showStatus('Загружаю связи…');
|
||
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;
|
||
syncFilterChips();
|
||
selectNode('');
|
||
}
|
||
centerLogin = normalizeLogin(graph?.login || clean);
|
||
syncLinksUrl(centerLogin, { push });
|
||
showStatus('');
|
||
renderMap({ fit: true });
|
||
if (friendsOfFriends) void expandFriends();
|
||
} catch (error) {
|
||
if (disposed || seq !== loadSeq) return;
|
||
showStatus(map ? '' : 'Не удалось загрузить связи.');
|
||
showToast(`Не удалось загрузить связи: ${error?.message || 'ошибка сети'}`, { kind: 'error', timeoutMs: 2400 });
|
||
}
|
||
}
|
||
|
||
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: 2000 });
|
||
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 expandFriends() {
|
||
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) {
|
||
showToast('У этого человека пока нет друзей на карте', { timeoutMs: 1800 });
|
||
return;
|
||
}
|
||
showStatus('Загружаю друзей друзей…');
|
||
const failed = await fetchGraphs(friends.map((node) => node.login));
|
||
if (disposed || normKey(centerLogin) !== centerAtStart || !friendsOfFriends) return;
|
||
showStatus('');
|
||
friends.forEach((node) => { if (graphs.has(node.id)) expanded.add(node.id); });
|
||
renderMap({ fit: true });
|
||
if (failed) showToast(`Не удалось загрузить связи: ${failed} из ${friends.length}`, { kind: 'error', timeoutMs: 2400 });
|
||
}
|
||
|
||
function toggleFriendsOfFriends() {
|
||
friendsOfFriends = !friendsOfFriends;
|
||
syncFilterChips();
|
||
if (friendsOfFriends) {
|
||
void expandFriends();
|
||
} else {
|
||
showStatus('');
|
||
expanded.clear();
|
||
renderMap({ fit: true });
|
||
}
|
||
persist();
|
||
}
|
||
|
||
function recenter(login) {
|
||
selectNode('');
|
||
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();
|
||
}
|
||
|
||
function cardAction(icon, label, onClick, { disabled = false, pressed = null } = {}) {
|
||
const button = document.createElement('button');
|
||
button.type = 'button';
|
||
button.className = 'ui-button net-card__action';
|
||
button.innerHTML = `${iconHtml(icon)}<span>${escapeHtml(label)}</span>`;
|
||
button.disabled = disabled;
|
||
if (pressed !== null) button.setAttribute('aria-pressed', pressed ? 'true' : 'false');
|
||
button.addEventListener('click', onClick);
|
||
return button;
|
||
}
|
||
|
||
function renderCard() {
|
||
const node = selectedId ? map?.byId.get(selectedId) : null;
|
||
card.replaceChildren();
|
||
card.hidden = !node;
|
||
if (node) {
|
||
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 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 (node.name !== node.login) parts.push(node.login);
|
||
if (isCenter) parts.push(isSelf ? 'это вы' : 'в центре карты');
|
||
else {
|
||
parts.push(RELATION_LABEL[node.relationType] || 'Связь');
|
||
if (node.tier === 1) parts.push(node.mutual ? 'взаимно' : 'с одной стороны');
|
||
else {
|
||
const via = map.byId.get(node.parentId);
|
||
if (via) parts.push(`через ${via.name}`);
|
||
}
|
||
}
|
||
if (node.shining) parts.push('сияющий');
|
||
if (node.official) 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(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', busy ? 'Загрузка…' : (node.expanded ? 'Скрыть' : 'Связи'), () => {
|
||
if (node.expanded) collapseNode(node.id);
|
||
else void expandNode(node.id);
|
||
}, { disabled: busy, pressed: node.expanded }));
|
||
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 (node.hiddenCount > 0) {
|
||
const more = document.createElement('p');
|
||
more.className = 'net-card__hint';
|
||
more.textContent = `Ещё ${node.hiddenCount} – откройте его карту кнопкой «В центр».`;
|
||
card.append(more);
|
||
}
|
||
}
|
||
placeOverlays();
|
||
}
|
||
|
||
// --- заметка ---
|
||
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 list = document.createElement('ul');
|
||
list.className = 'net-legend';
|
||
const rows = [
|
||
['line', 'close_friend', 'Близкий друг'],
|
||
['line', 'friend', 'Друг'],
|
||
['line', 'contact', 'Контакт или подписка'],
|
||
['line', 'family', 'Семья'],
|
||
['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);
|
||
list.append(li);
|
||
}
|
||
const tips = document.createElement('p');
|
||
tips.className = 'meta-muted net-legend__tips';
|
||
tips.textContent = 'Нажмите на человека – откроется карточка. Точку можно перетащить пальцем, раскладка запомнится. Двойное нажатие по пустому месту – показать всю карту.';
|
||
const box = document.createElement('div');
|
||
box.className = 'stack';
|
||
box.append(list, tips);
|
||
return box;
|
||
},
|
||
});
|
||
}
|
||
|
||
// --- шапка ---
|
||
const header = createTopBar({
|
||
title: 'Связи',
|
||
className: 'topbar--root',
|
||
actions: [
|
||
{
|
||
icon: 'search',
|
||
title: 'Найти пользователя',
|
||
ariaLabel: 'Найти пользователя',
|
||
className: 'network-search-btn',
|
||
onClick: () => { closeSearch = openUserSearchModal((login) => recenter(login)) || null; },
|
||
},
|
||
{
|
||
iconNode: createOverflowDots(),
|
||
title: 'Настройки карты',
|
||
ariaLabel: 'Настройки карты',
|
||
className: 'topbar-overflow-action--raised',
|
||
menu: {
|
||
minWidth: 240,
|
||
items: () => {
|
||
const hasManual = getManualLayout(normKey(centerLogin)).size > 0;
|
||
return [
|
||
{ label: 'По близости', selected: layoutMode === 'rings', iconHtml: iconHtml(layoutMode === 'rings' ? 'check' : 'network'), action: () => changeLayoutMode('rings') },
|
||
{ label: 'По группам', selected: layoutMode === 'groups', iconHtml: iconHtml(layoutMode === 'groups' ? 'check' : 'list'), action: () => changeLayoutMode('groups') },
|
||
{ divider: true },
|
||
{ label: 'Показать всю карту', iconHtml: iconHtml('fit'), action: () => engine.fit() },
|
||
{
|
||
label: 'Сбросить мою раскладку',
|
||
iconHtml: iconHtml('refresh'),
|
||
disabled: !hasManual,
|
||
action: () => {
|
||
clearManualLayout(normKey(centerLogin));
|
||
renderMap({ relayout: true, fit: true });
|
||
},
|
||
},
|
||
{ divider: true },
|
||
{ label: 'Как читать карту', iconHtml: iconHtml('info'), action: openLegend },
|
||
];
|
||
},
|
||
},
|
||
},
|
||
],
|
||
});
|
||
|
||
function changeLayoutMode(mode) {
|
||
if (mode === layoutMode) return;
|
||
layoutMode = mode;
|
||
setLayoutMode(mode);
|
||
renderMap({ relayout: true, fit: true });
|
||
}
|
||
|
||
// --- фильтры ---
|
||
const filterBar = document.createElement('div');
|
||
filterBar.className = 'fg-filter-bar app-top-tabs';
|
||
filterBar.addEventListener('pointerdown', (event) => event.stopPropagation());
|
||
const filterTabs = document.createElement('div');
|
||
filterTabs.className = 'tabs tabs--dense fg-filter-tabs';
|
||
filterBar.append(filterTabs);
|
||
const filterChips = {};
|
||
const makeToggle = (label, onClick) => {
|
||
const button = document.createElement('button');
|
||
button.type = 'button';
|
||
button.className = 'tab-btn';
|
||
button.textContent = label;
|
||
button.addEventListener('click', onClick);
|
||
filterTabs.append(button);
|
||
return button;
|
||
};
|
||
const syncToggle = (button, pressed) => {
|
||
button.classList.toggle('active', pressed);
|
||
button.setAttribute('aria-pressed', pressed ? 'true' : 'false');
|
||
};
|
||
FILTER_ORDER.forEach((key) => {
|
||
filterChips[key] = makeToggle(FILTERS[key].label, () => {
|
||
if (activeFilters.has(key)) activeFilters.delete(key);
|
||
else activeFilters.add(key);
|
||
syncFilterChips();
|
||
engine.setFilter(filterPredicate());
|
||
engine.fit();
|
||
if (selectedId && filterPredicate() && map?.byId.get(selectedId) && selectedId !== map.focusId
|
||
&& !filterPredicate()(map.byId.get(selectedId))) selectNode('');
|
||
persist();
|
||
});
|
||
});
|
||
const fofChip = makeToggle('Друзья друзей', toggleFriendsOfFriends);
|
||
function syncFilterChips() {
|
||
FILTER_ORDER.forEach((key) => syncToggle(filterChips[key], activeFilters.has(key)));
|
||
syncToggle(fofChip, friendsOfFriends);
|
||
}
|
||
syncFilterChips();
|
||
engine.setFilter(filterPredicate());
|
||
|
||
// --- масштаб ---
|
||
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);
|
||
}
|
||
|
||
function onKeydown(event) {
|
||
if (event.key !== 'Escape' || !selectedId || noteSheet || legendSheet) return;
|
||
if (document.querySelector('.dropdown-portal, #network-search-modal')) return;
|
||
selectNode('');
|
||
}
|
||
document.addEventListener('keydown', onKeydown);
|
||
const overlayObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(() => placeOverlays()) : null;
|
||
overlayObserver?.observe(stage);
|
||
|
||
screen.cleanup = () => {
|
||
if (disposed) return;
|
||
disposed = true;
|
||
engine.destroy();
|
||
overlayObserver?.disconnect();
|
||
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||
document.removeEventListener('keydown', onKeydown);
|
||
noteSheet?.close();
|
||
legendSheet?.close();
|
||
if (document.getElementById('network-search-modal')) closeSearch?.();
|
||
};
|
||
|
||
chrome?.setTopbar(header);
|
||
stage.append(board, filterBar, status, zoomBar, card, a11yList);
|
||
screen.append(stage);
|
||
|
||
persist();
|
||
if (centerLogin) void load(centerLogin);
|
||
else window.setTimeout(() => { if (!disposed) closeSearch = openUserSearchModal((login) => recenter(login)) || null; }, 0);
|
||
return screen;
|
||
}
|