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

This commit is contained in:
AidarKC
2026-10-21 11:47:27 +03:00
parent aa5addb5d9
commit 7a6ab3b35a
22 changed files with 723 additions and 678 deletions
+6 -6
View File
@@ -10,11 +10,10 @@ function normLogin(value) {
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
function relationTypeFromRelation(relation) {
const explicit = String(relation?.mark?.relationType || '').trim().toLowerCase();
if (explicit === 'close_friend' || explicit === 'friend' || explicit === 'contact') return explicit;
const role = relation?.role;
if (FAMILY_ROLES.includes(role)) return 'family';
if (role === 'friend') return 'friend';
// Тип отношения выбирает владелец рассматриваемого графа.
const ownType = String(relation?.relationType || '').trim().toLowerCase();
if (ownType === 'close_friend' || ownType === 'friend') return ownType;
if (relation?.role === 'friend') return 'friend';
return 'contact';
}
@@ -24,7 +23,7 @@ function relationTypeFromRelation(relation) {
// - взаимные дружеские связи ближе односторонних.
function deriveStrength(relation) {
if (relation.isRelative) return 0.9;
if (relation?.mark?.relationType === 'close_friend') return 0.9;
if (relation?.relationType === 'close_friend') return 0.9;
if (relation.role === 'contact') return 0.4;
if (relation.forward && relation.backward) return 0.8;
return 0.55;
@@ -69,6 +68,7 @@ export function engineModelFromGraphModel(graphModel) {
shining: Boolean(r?.mark?.shine),
official: Boolean(r?.mark?.official),
tier: 1,
mutual: Boolean(r?.forward && r?.backward),
};
})
.filter(Boolean);
@@ -716,6 +716,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
node.dotOnly = spec.dotOnly;
node.strength = strength;
node.relationType = src.relationType;
node.mutual = src.mutual !== false;
node.shining = Boolean(src.shining);
node.official = Boolean(src.official);
node.isHistoryCenter = Boolean(src.isHistoryCenter);
@@ -940,6 +941,28 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
n.dotRadius = full ? 12 : 5; // радиус для расчёта концов линий связей
}
// Четыре части одной дуги: толстый штрих → короткий штрих → точечки у адресата.
// Используется и обычным force-графом, и историей / «друзьями друзей».
function directedFriendEdgePaths(x1, y1, cx, cy, x2, y2, color, opacity, width = 1.2) {
const at = (t) => ({
x: (1 - t) ** 2 * x1 + 2 * t * (1 - t) * cx + t ** 2 * x2,
y: (1 - t) ** 2 * y1 + 2 * t * (1 - t) * cy + t ** 2 * y2,
});
const sections = [[20, 3], [12, 4], [6, 4], [1, 5]];
return sections.map(([dash, gap], index) => {
const start = index / sections.length;
const finish = (index + 1) / sections.length;
const a = at(start);
const b = at(finish);
const control = {
x: a.x + (finish - start) * ((1 - start) * (cx - x1) + start * (x2 - cx)),
y: a.y + (finish - start) * ((1 - start) * (cy - y1) + start * (y2 - cy)),
};
const d = `M${a.x.toFixed(1)} ${a.y.toFixed(1)} Q${control.x.toFixed(1)} ${control.y.toFixed(1)} ${b.x.toFixed(1)} ${b.y.toFixed(1)}`;
return `<path d="${d}" fill="none" stroke="${color}" stroke-width="${width}" stroke-linecap="round" stroke-dasharray="${dash} ${gap}" opacity="${opacity.toFixed(3)}" />`;
});
}
function renderHistoryEdges() {
const Z = zoom;
const parts = [];
@@ -990,6 +1013,10 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
const opacity = Math.min(childOpacity, parentOpacity);
const shine = Boolean(parent.shining && n.shining) && !n.hidden;
if (ref?.mutual === false) {
parts.push(...directedFriendEdgePaths(x1, y1, cpx, cpy, x2, y2, relationColor(relationType), opacity * 0.82));
continue;
}
if (shine) {
const pnx = -uy;
const pny = ux;
@@ -1112,6 +1139,11 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
dashAttr = ` stroke-dasharray="${L.toFixed(1)}" stroke-dashoffset="${(L * (1 - growP)).toFixed(1)}"`;
}
const pe = n.alwaysVisible ? 1 : (parent.expandP || 0); // X2 виден сразу; старые deep-ветки — по раскрытию
if (n.mutual === false) {
const opacity = nodeOpacity * sp * (n.tier > 1 ? pe : 1) * 0.82;
if (opacity > 0.02) parts.push(...directedFriendEdgePaths(x1, y1, cpx, cpy, x2, y2, relationColor(n.relationType), opacity));
continue;
}
if (n.tier >= 3) {
// 3-й уровень: тонкая нить В ЦВЕТЕ СВЯЗИ (видна при раскрытии). Сияющая — светится (ореол+ядро).
if (pe > 0.02) {
@@ -1,5 +1,6 @@
import { createTopBar } from '../../components/topbar.js';
import { authService, state } from '../../state.js';
import { getConnectionsGraphCached as loadSharedGraph, cachedConnectionsGraph as getCachedSharedGraph, CONNECTIONS_GRAPH_CHANGED, CONNECTIONS_GRAPH_TTL_MS } from '../../services/connections-graph-cache.js';
import { makeProfileRoute } from '../../services/shine-routes.js';
import { makeProfileLinksRoute } from '../../services/shine-routes.js';
import { createForceGraph } from './force-graph.js';
@@ -136,66 +137,29 @@ function getRelativeGenderMap(graph) {
function buildGraphModel(graph, centerLogin) {
const login = normalizeLogin(graph?.login || centerLogin || state.session.login);
const outFriends = toSet(graph?.outFriends);
const inFriends = toSet(graph?.inFriends);
const outCloseFriends = toSet(graph?.outCloseFriends);
const inFriends = toSet(graph?.inFriends);
const inCloseFriends = toSet(graph?.inCloseFriends);
const 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 || []),
...(graph?.outFriends || []),
]).filter((entry) => normKey(entry) !== normKey(login));
const relations = allLogins.map((targetLogin) => {
const friendOut = hasLogin(outFriends, targetLogin);
const friendIn = hasLogin(inFriends, targetLogin);
const closeFriendOut = hasLogin(outCloseFriends, targetLogin);
const closeFriendIn = hasLogin(inCloseFriends, targetLogin);
const contactOut = hasLogin(outContacts, targetLogin) || hasLogin(outFollows, targetLogin) || hasLogin(outOfficial, targetLogin);
const contactIn = hasLogin(inContacts, targetLogin) || hasLogin(inFollows, targetLogin) || hasLogin(inOfficial, targetLogin);
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,
};
});
const relations = allLogins.map((targetLogin) => ({
login: targetLogin,
key: normKey(targetLogin),
role: 'friend',
relationType: hasLogin(outCloseFriends, targetLogin) ? 'close_friend' : 'friend',
isRelative: false,
gender: GENDER_UNKNOWN,
forward: true,
backward: hasLogin(inCloseFriends, targetLogin) || hasLogin(inFriends, targetLogin),
mark: allMarks.get(normKey(targetLogin)) || null,
}));
return {
centerLogin: login,
@@ -296,6 +260,7 @@ function relationEdge(parentId, node) {
return {
id: normKey(parentId),
relationType: String(node?.relationType || 'contact'),
mutual: node?.mutual !== false,
strength: Math.max(0, Math.min(1, Number(node?.strength) || 0.5)),
};
}
@@ -412,48 +377,7 @@ async function buildSecondLevelEngineModel(baseModel, getGraph) {
return { ...baseModel, nodes: [...byKey.values()] };
}
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);
}
}
const getConnectionsGraphCached = (login, options) => loadSharedGraph(authService, login, options);
function historyNodeClearance(node) {
return (Number(node?.tier) || 1) >= 2 ? HISTORY_TIER2_CLEARANCE : HISTORY_NODE_CLEARANCE;
@@ -738,6 +662,7 @@ function buildStableHistoryEngineModel(history, historyDepth = HISTORY_MAX_PREVI
parent: parentKey,
child: key,
relationType: String(ref?.relationType || rawNode?.relationType || 'contact'),
mutual: ref?.mutual !== false,
strength: Math.max(0, Math.min(1, Number(ref?.strength) || Number(rawNode?.strength) || 0.5)),
});
});
@@ -753,7 +678,7 @@ function buildStableHistoryEngineModel(history, historyDepth = HISTORY_MAX_PREVI
if (!nodeMap.has(edge.parent) || !nodeMap.has(edge.child)) continue;
const list = edgeParentsByChild.get(edge.child) || [];
if (!list.some((row) => normKey(row?.id) === edge.parent)) {
list.push({ id: edge.parent, relationType: edge.relationType, strength: edge.strength });
list.push({ id: edge.parent, relationType: edge.relationType, mutual: edge.mutual, strength: edge.strength });
}
edgeParentsByChild.set(edge.child, list);
}
@@ -1302,8 +1227,21 @@ export function render({ navigate, route, chrome } = {}) {
],
});
function refreshConnectionsView() {
if (!centerLogin) return;
// После записи полностью пересобираем историю/X2 из общего кэша, сохраняя по возможности позиции.
void load(centerLogin, { pushHistory: false });
}
window.addEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
const graphRefreshTimer = window.setInterval(() => {
if (engine && !document.hidden) refreshConnectionsView();
}, CONNECTIONS_GRAPH_TTL_MS);
// Ресайз и перерисовку рёбер движок обрабатывает сам (window resize + ResizeObserver внутри).
screen.cleanup = () => {
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
window.clearInterval(graphRefreshTimer);
loadSeq += 1;
if (engine) engine.destroy();
engine = null;
};