import { t } from '../../i18n/index.js'; import { createTopBar } from '../../components/topbar.js'; import { iconHtml } from '../../components/ui-icon.js'; import { authService, state } from '../../state.js'; import { makeProfileRoute, makeProfileLinksRoute } from '../../services/shine-routes.js'; import { CONNECTIONS_GRAPH_CHANGED } from '../../services/connections-graph-cache.js'; import { createForceGraph } from '../network-legacy/force-graph.js'; import { openNodeMenu } from '../network-legacy/node-menu.js'; import { createExplorerGraph, keyOf, EXPLORER_DEFAULT_DEPTH, EXPLORER_MAX_DEPTH } from './graph-model.js'; import { getExplorerGraph, readExplorerCachedGraphs, clearExplorerGraphCache, explorerCacheScope, explorerGraphSavedAt } from './graph-cache.js'; export const pageMeta = { id: 'network-view', get title() { return t('screens.network_view.text_001'); }, shellMode: { topFade: true, bottomFade: true, bottomFadeAnchor: 'toolbar', fadeProfile: 'edge', contentUnderTopbar: true, scrollContainer: 'locked', }, }; const normalizeLogin = (value) => String(value || '').trim(); const escapeHtml = (text) => String(text || '').replaceAll('&', '&').replaceAll('<', '<') .replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", '''); function createDebounced(fn, ms = 2000) { let timer = 0; const debounced = (...args) => { if (timer) window.clearTimeout(timer); timer = window.setTimeout(() => { timer = 0; fn(...args); }, ms); }; debounced.cancel = () => { if (timer) window.clearTimeout(timer); timer = 0; }; return debounced; } function hash01(value) { let h = 2166136261; for (const ch of String(value)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 16777619); } return (h >>> 0) / 4294967296; } // V3 state survives switching between tabs; long-term graph responses reside in IndexedDB. let retained = null; export function render({ navigate, route, chrome } = {}) { const screen = document.createElement('section'); screen.className = 'network-screen network-explorer'; const stage = document.createElement('div'); stage.className = 'network-stage'; const board = document.createElement('div'); board.className = 'network-board network-board--full fg-stage'; const toolbar = document.createElement('div'); toolbar.className = 'fg-filter-bar app-top-tabs'; toolbar.addEventListener('pointerdown', (event) => event.stopPropagation()); const status = document.createElement('div'); status.className = 'network-explorer__status'; status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite'); stage.append(board, toolbar, status); screen.append(stage); const scope = explorerCacheScope(authService, state.session.login); if (!retained || retained.scope !== scope) retained = { scope, graph: createExplorerGraph(), positions: new Map(), center: '', depth: EXPLORER_DEFAULT_DEPTH, x2: false, close: false, shining: false, compact: false, }; const session = retained; let centerLogin = normalizeLogin(route?.params?.login || session.center || state.session.login); session.center = centerLogin; let engine = null; let disposed = false; let loadSeq = 0; let drawTimer = 0; let searchClose = null; let cacheWasCleared = false; function profileRoute(login) { if (keyOf(login) === keyOf(state.session.login)) return 'profile-view'; return makeProfileRoute(login); } function updateStatus(text = '') { if (disposed) return; status.textContent = text; status.hidden = !text; } function getSnapshot() { return session.graph.snapshot(centerLogin, session); } function shiftToCenter(login) { const pivot = session.positions.get(keyOf(login)); if (!pivot) return; for (const [key, p] of session.positions) { session.positions.set(key, { x: p.x - pivot.x, y: p.y - pivot.y }); } } // Расставляем только новые узлы. Старые координаты не меняются при загрузке/фильтрах. function placeNodes(nodes) { const occupied = [...session.positions.values()]; const byId = new Map(nodes.map((node) => [node.id, node])); const adjacency = new Map(); for (const node of nodes) { for (const edge of node.edgeParents || []) { const parent = edge.id; if (!adjacency.has(node.id)) adjacency.set(node.id, []); if (!adjacency.has(parent)) adjacency.set(parent, []); adjacency.get(node.id).push(parent); adjacency.get(parent).push(node.id); } } const center = keyOf(centerLogin); if (!session.positions.has(center)) session.positions.set(center, { x: 0, y: 0 }); const pending = nodes.filter((node) => !session.positions.has(node.id)).sort((a, b) => a.distance - b.distance); const spacing = session.compact ? 62 : 84; const minNodeGap = session.compact ? 48 : 66; for (const node of pending) { const connected = (adjacency.get(node.id) || []).filter((id) => session.positions.has(id)); const nearest = connected.sort((a, b) => (byId.get(a)?.distance ?? 99) - (byId.get(b)?.distance ?? 99))[0]; const base = session.positions.get(nearest) || { x: 0, y: 0 }; let point = null; const phase = hash01(node.id) * Math.PI * 2; for (let ring = 1; ring <= 35 && !point; ring += 1) { const count = Math.max(8, Math.round(6 * ring)); for (let i = 0; i < count; i += 1) { const angle = phase + Math.PI * 2 * i / count; const x = base.x + Math.cos(angle) * ring * spacing; const y = base.y + Math.sin(angle) * ring * spacing; if (occupied.every((p) => Math.hypot(x - p.x, y - p.y) >= minNodeGap)) { point = { x, y }; break; } } } point ||= { x: base.x + 300, y: base.y + 300 }; session.positions.set(node.id, point); occupied.push(point); } } function draw() { if (disposed || !centerLogin) return; const model = getSnapshot(); placeNodes(model.nodes); model.nodes = model.nodes.map((node) => ({ ...node, layoutX: session.positions.get(node.id)?.x || 0, layoutY: session.positions.get(node.id)?.y || 0, fixedLayout: true, })); if (engine) engine.setModel(model); else engine = createForceGraph({ stage: board, model, explorerMode: true, onNodeTap: (node) => { void load(node.login, true); }, onCenterTap: (node) => nodeMenu(node, false), onNodeLongPress: (node, point) => nodeMenu(node, true, point), onNodeMoveEnd: (node, point) => savePositions([{ id: node.id, ...point }]), onGroupMoveEnd: savePositions, }); } function scheduleDraw() { if (drawTimer || disposed) return; drawTimer = window.setTimeout(() => { drawTimer = 0; draw(); }, 120); } function savePositions(rows) { (rows || []).forEach((row) => { const x = Number(row?.x); const y = Number(row?.y); if (keyOf(row?.id) && Number.isFinite(x) && Number.isFinite(y)) session.positions.set(keyOf(row.id), { x, y }); }); } function nodeMenu(node, long = false, point = null) { const rect = node?.el?.getBoundingClientRect?.(); openNodeMenu({ login: normalizeLogin(node?.login), displayName: String(node?.name || '').trim(), relationType: node?.relationType, point: point || (rect ? { x: rect.left + rect.width / 2, y: rect.top, rect } : undefined), actions: [ { label: t(long ? 'screens.network_view.text_006' : 'screens.network_view.text_004'), onClick: () => navigate?.(profileRoute(node?.login)) }, { label: t(long ? 'screens.network_view.text_007' : 'screens.network_view.text_005'), onClick: () => navigate?.(`chat/${encodeURIComponent(normalizeLogin(node?.login))}`) }, ], }); } function updateUrl(login, push = false) { const nextPath = `/${makeProfileLinksRoute(login)}`; if (window.location.pathname === nextPath) return; if (push) window.history.pushState({}, '', nextPath); else window.history.replaceState({}, '', nextPath); } async function fetchGraph(login, currentSeq) { const key = keyOf(login); if (session.graph.isFresh(key)) return true; try { const graph = await getExplorerGraph(authService, login, { scope }); if (disposed || currentSeq !== loadSeq) return false; session.graph.add(graph, login, explorerGraphSavedAt(scope, login) || Date.now()); scheduleDraw(); return true; } catch (error) { if (!disposed && currentSeq === loadSeq) console.warn('[Network V3] Failed to load', login, error); return false; } } async function load(nextLogin, push = false) { const next = normalizeLogin(nextLogin); if (!next || disposed) return; const seq = ++loadSeq; if (keyOf(next) !== keyOf(centerLogin)) { if (session.positions.has(keyOf(next))) shiftToCenter(next); else { // Поиск неизвестного ранее человека: сдвигаем старую карту от нового центра. for (const [id, p] of session.positions) session.positions.set(id, { x: p.x - 190, y: p.y }); } } centerLogin = next; session.center = next; updateUrl(next, push); draw(); // мгновенно показать уже исследованную карту, ещё до завершения сетевых запросов updateStatus(t('screens.network_explorer.loading')); const ok = await fetchGraph(next, seq); if (disposed || seq !== loadSeq) return; if (!ok) { updateStatus(t('screens.network_explorer.error')); return; } draw(); if (!session.x2) { updateStatus(); return; } const friends = [...(session.graph.getFriends(next) || [])]; let index = 0; let finished = 0; let failed = 0; const workers = Array.from({ length: Math.min(4, friends.length) }, async () => { while (index < friends.length && !disposed && seq === loadSeq && session.x2) { const friend = friends[index++]; if (!await fetchGraph(friend, seq)) failed += 1; finished += 1; if (!disposed && seq === loadSeq) updateStatus(t('screens.network_explorer.progress', { value1: finished, value2: friends.length })); } }); await Promise.all(workers); if (disposed || seq !== loadSeq) return; draw(); updateStatus(failed ? t('screens.network_explorer.partial', { value1: failed }) : ''); } function chip(label, fn, selected = false) { const element = document.createElement('button'); element.type = 'button'; element.className = `fg-filter-chip${selected ? ' is-active' : ''}`; element.textContent = label; element.setAttribute('aria-pressed', selected ? 'true' : 'false'); element.addEventListener('click', fn); toolbar.append(element); return element; } function actionChip(label, fn) { const element = document.createElement('button'); element.type = 'button'; element.className = 'fg-filter-chip'; element.textContent = label; element.addEventListener('click', fn); toolbar.append(element); return element; } const closeChip = chip(t('screens.network_view.text_002'), () => { session.close = !session.close; closeChip.classList.toggle('is-active', session.close); closeChip.setAttribute('aria-pressed', String(session.close)); draw(); }, session.close); const shineChip = chip(t('screens.network_view.text_003'), () => { session.shining = !session.shining; shineChip.classList.toggle('is-active', session.shining); shineChip.setAttribute('aria-pressed', String(session.shining)); draw(); }, session.shining); const x2Chip = chip('X2', () => { session.x2 = !session.x2; x2Chip.classList.toggle('is-active', session.x2); x2Chip.setAttribute('aria-pressed', String(session.x2)); void load(centerLogin); }, session.x2); const depthChip = chip('', () => { session.depth = (session.depth + 1) % (EXPLORER_MAX_DEPTH + 1); syncDepth(); draw(); }); actionChip(t('screens.network_explorer.compact'), () => { session.compact = true; session.positions.clear(); draw(); }); function syncDepth() { depthChip.textContent = t('screens.network_explorer.depth', { value1: session.depth }); depthChip.title = t('screens.network_explorer.depth_hint', { value1: session.depth + (session.x2 ? 2 : 1) }); depthChip.setAttribute('aria-label', depthChip.title); } syncDepth(); async function resetCache() { ++loadSeq; cacheWasCleared = true; updateStatus(t('screens.network_explorer.clearing')); await clearExplorerGraphCache(); session.graph.clear(); session.positions.clear(); if (!disposed) void load(centerLogin); } function openSearchModal() { const root = document.getElementById('modal-root'); if (!(root instanceof HTMLElement)) return; root.innerHTML = `