SHA256
Добавили связи V3
This commit is contained in:
@@ -0,0 +1,447 @@
|
||||
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,
|
||||
};
|
||||
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);
|
||||
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 * 84;
|
||||
const y = base.y + Math.sin(angle) * ring * 84;
|
||||
if (occupied.every((p) => Math.hypot(x - p.x, y - p.y) >= 66)) { 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;
|
||||
}
|
||||
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();
|
||||
});
|
||||
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 = `
|
||||
<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">${t('dialogs.modals.network_view.label_002')}</h3>
|
||||
<div class="row" style="gap:8px;">
|
||||
<input class="input" id="network-search-input" type="text" maxlength="30" placeholder="${t('dialogs.modals.network_view.label_001')}" />
|
||||
<button class="primary-btn" type="button" id="network-search-run">${t('dialogs.modals.network_view.label_003')}</button>
|
||||
</div>
|
||||
<div class="meta-muted" id="network-search-meta">${t('dialogs.modals.network_view.label_004')}</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;
|
||||
|
||||
let debouncedSearch = null;
|
||||
const close = () => {
|
||||
++searchSeq;
|
||||
debouncedSearch?.cancel();
|
||||
if (root.contains(modal)) root.innerHTML = '';
|
||||
searchClose = null;
|
||||
};
|
||||
searchClose = close;
|
||||
|
||||
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">${t('dialogs.remaining.pages.network_legacy.network_view.markup.kandidaty_ne_naydeny')}</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 () => {
|
||||
if (disposed || !root.contains(modal)) return;
|
||||
const query = normalizeLogin(inputEl.value);
|
||||
if (!query) {
|
||||
metaEl.textContent = t('dialogs.modals.network_view.label_006');
|
||||
renderCandidates([]);
|
||||
return;
|
||||
}
|
||||
const reqId = ++searchSeq;
|
||||
metaEl.textContent = t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.poisk_po_value1', { value1: query });
|
||||
if (runBtn instanceof HTMLButtonElement) runBtn.disabled = true;
|
||||
try {
|
||||
const found = await authService.searchUsers(query);
|
||||
if (disposed || reqId !== searchSeq || !root.contains(modal)) return;
|
||||
renderCandidates(found);
|
||||
const foundCount = Math.min(5, Array.isArray(found) ? found.length : 0);
|
||||
metaEl.textContent = foundCount > 0
|
||||
? t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.naydeno_kandidatov_value1_vyberite_odnogo', { value1: foundCount })
|
||||
: t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.kandidaty_ne_naydeny');
|
||||
} catch (error) {
|
||||
if (disposed || reqId !== searchSeq || !root.contains(modal)) return;
|
||||
renderCandidates([]);
|
||||
metaEl.textContent = t('dialogs.remaining.pages.network_legacy_network_view.opensearchmodal.oshibka_poiska_value1', { value1: 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(); });
|
||||
debouncedSearch = createDebounced(() => { if (!disposed && root.contains(modal)) 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();
|
||||
void load(nextLogin, true);
|
||||
});
|
||||
|
||||
window.setTimeout(() => { if (!disposed && root.contains(modal)) inputEl.focus(); }, 0);
|
||||
}
|
||||
|
||||
// SEARCH_MODAL
|
||||
|
||||
const header = createTopBar({
|
||||
title: t('screens.network_view.text_008'), className: 'topbar--root',
|
||||
actions: [{
|
||||
icon: 'moreVertical', title: t('screens.network_explorer.menu'),
|
||||
ariaLabel: t('screens.network_explorer.menu'),
|
||||
menu: {
|
||||
items: [
|
||||
{ iconHtml: iconHtml('search'), label: t('screens.network_explorer.search'), action: openSearchModal },
|
||||
{ iconHtml: iconHtml('trash'), label: t('screens.network_explorer.clear_cache'), action: () => void resetCache() },
|
||||
],
|
||||
},
|
||||
}],
|
||||
});
|
||||
chrome?.setTopbar(header);
|
||||
const onGraphChanged = () => { void resetCache(); };
|
||||
window.addEventListener(CONNECTIONS_GRAPH_CHANGED, onGraphChanged);
|
||||
const refreshTimer = window.setInterval(() => {
|
||||
if (!disposed && !document.hidden && centerLogin && !session.graph.isFresh(centerLogin))
|
||||
void load(centerLogin);
|
||||
}, 5 * 60 * 1000);
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
++loadSeq;
|
||||
if (drawTimer) window.clearTimeout(drawTimer);
|
||||
window.clearInterval(refreshTimer);
|
||||
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, onGraphChanged);
|
||||
engine?.destroy(); engine = null;
|
||||
searchClose?.();
|
||||
// TopBar lifetime owned by AppShell, not this screen.
|
||||
};
|
||||
// Восстановление уже открытых веток из IndexedDB (без сетевых запросов).
|
||||
// Первую карту показываем сразу, восстановление идёт параллельно.
|
||||
void readExplorerCachedGraphs(scope).then((entries) => {
|
||||
if (disposed || cacheWasCleared || session !== retained) return;
|
||||
entries.forEach((entry) => {
|
||||
const login = entry?.graph?.login || entry?.key?.slice(scope.length + 1);
|
||||
if (login && !session.graph.isFresh(login)) session.graph.add(entry.graph, login, entry.savedAt);
|
||||
});
|
||||
scheduleDraw();
|
||||
});
|
||||
if (centerLogin) void load(centerLogin);
|
||||
else window.setTimeout(() => { if (!disposed) openSearchModal(); }, 0);
|
||||
return screen;
|
||||
}
|
||||
Reference in New Issue
Block a user