SHA256
Поправил пуши для личных сообщений
This commit is contained in:
+20
-8
@@ -15,6 +15,7 @@ import {
|
||||
import { attachScrollToBottomButton } from './components/scroll-to-bottom-button.js';
|
||||
import { initPwaInstallPromptHandling } from './services/pwa-install-service.js';
|
||||
import { initPwaPush } from './services/pwa-push-service.js';
|
||||
import { dmNotificationTag, dmUnreadLabel } from './services/dm-push-notifications.js';
|
||||
import { initCallUiOverlay } from './services/call-ui-service.js';
|
||||
import { showToast } from './services/channels-ux.js';
|
||||
import { toUserMessage } from './services/ui-error-texts.js';
|
||||
@@ -49,6 +50,7 @@ import {
|
||||
deleteConversationMessagesBefore,
|
||||
deleteSignedMessageByBaseKey,
|
||||
markIncomingReadByBaseKey,
|
||||
getChatMessages,
|
||||
markOutgoingDeliveryState,
|
||||
markOutgoingReadByBaseKey,
|
||||
normalizeDmChatId,
|
||||
@@ -718,19 +720,24 @@ async function tryLockPortraitOrientation() {
|
||||
}
|
||||
}
|
||||
|
||||
async function notifyHiddenIncomingMessage(fromLogin, text) {
|
||||
const body = String(text || '').trim() || `Вам пришло сообщение от ${fromLogin}`;
|
||||
async function notifyHiddenIncomingMessage(fromLogin, toLogin, unreadCount, messageKey, notificationVersionMs) {
|
||||
const title = `Сообщение от ${fromLogin}`;
|
||||
const body = dmUnreadLabel(unreadCount);
|
||||
try {
|
||||
const registration = await navigator.serviceWorker?.getRegistration?.();
|
||||
if (registration?.showNotification) {
|
||||
await registration.showNotification(title, {
|
||||
body,
|
||||
tag: `shine-hidden-dm-${String(fromLogin || '').trim().toLowerCase() || 'unknown'}`,
|
||||
renotify: true,
|
||||
tag: dmNotificationTag(toLogin, fromLogin),
|
||||
renotify: true, // каждое новое DM — отдельный сигнал, но одна карточка на собеседника
|
||||
silent: false,
|
||||
data: {
|
||||
kind: 'new_message',
|
||||
fromLogin,
|
||||
toLogin,
|
||||
messageKey,
|
||||
unreadCount,
|
||||
notificationVersionMs,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
@@ -1849,14 +1856,19 @@ async function init() {
|
||||
// Чат «без звука»: сообщение и счётчик непрочитанных приходят как обычно, но без сигнала и уведомления.
|
||||
if (added && isIncomingForCurrent && !payload.backlog && !isDmChatMuted(chatId)) {
|
||||
const parsedText = parseDmTechBlocks(text);
|
||||
const displayText = String(parsedText.displayText || '');
|
||||
const suppressHiddenNotification = parsedText.callSummary?.status === 'completed';
|
||||
const toLogin = String(state.session.login || payload.toLogin || '').trim();
|
||||
const serverUnread = Number(payload.unreadCount);
|
||||
const localUnread = getChatMessages(chatId)
|
||||
.filter((row) => row?.from === 'in' && row?.unread && Number(row?.messageType) === 1).length;
|
||||
const unreadCount = Number.isFinite(serverUnread) && serverUnread > 0
|
||||
? serverUnread : Math.max(1, localUnread);
|
||||
if (document.visibilityState === 'visible') {
|
||||
void playDmSignal({ extended: false });
|
||||
} else if (Notification.permission === 'granted' && !suppressHiddenNotification) {
|
||||
try {
|
||||
void notifyHiddenIncomingMessage(fromLogin, displayText || '');
|
||||
} catch {}
|
||||
void notifyHiddenIncomingMessage(
|
||||
fromLogin, toLogin, unreadCount, messageKey, Number(payload.notificationVersionMs || 0),
|
||||
);
|
||||
} else if (!suppressHiddenNotification) {
|
||||
void playDmSignal({ extended: true });
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@ 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 { getConnectionsGraphCached as loadSharedGraph, cachedConnectionsGraph as getCachedSharedGraph, CONNECTIONS_GRAPH_CHANGED, CONNECTIONS_GRAPH_TTL_MS } from '../services/connections-graph-cache.js';
|
||||
import { openHistoryLayer } from '../router.js';
|
||||
import { makeProfileRoute, makeProfileLinksRoute, makeShineChannelRootRoute } from '../services/shine-routes.js';
|
||||
import { userDisplayName } from '../services/user-display.js';
|
||||
@@ -30,7 +31,7 @@ import {
|
||||
updateCompanySnapshots,
|
||||
} from './network/companies-store.js';
|
||||
import {
|
||||
PEOPLE_DATA_FRESH_MS, channelInfo, channelKey, getCities, getSubs, getTies, saveCities, saveSubs, saveTies,
|
||||
PEOPLE_DATA_FRESH_MS, peopleDataGeneration, channelInfo, channelKey, getCities, getSubs, getTies, saveCities, saveSubs, saveTies,
|
||||
} from './network/people-data-store.js';
|
||||
import {
|
||||
clearManualLayout, getAutoLayoutMode, getLayoutMode, getManualBase, getManualLayout, getViewSetting, hasManualLayout,
|
||||
@@ -119,52 +120,28 @@ function normalizeAvatar(row) {
|
||||
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 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 || []),
|
||||
...(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);
|
||||
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,
|
||||
};
|
||||
});
|
||||
const relations = allLogins.map((targetLogin) => ({
|
||||
login: targetLogin,
|
||||
key: normKey(targetLogin),
|
||||
role: 'friend',
|
||||
relationType: hasLogin(outCloseFriends, targetLogin) ? 'close_friend' : 'friend',
|
||||
isRelative: false,
|
||||
forward: true,
|
||||
backward: hasLogin(inCloseFriends, targetLogin) || hasLogin(inFriends, targetLogin),
|
||||
mark: allMarks.get(normKey(targetLogin)) || null,
|
||||
}));
|
||||
|
||||
return {
|
||||
centerLogin: login,
|
||||
@@ -188,52 +165,8 @@ async function mapWithConcurrency(items, concurrency, worker) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
const cachedGraph = (login) => getCachedSharedGraph(authService, login);
|
||||
const getConnectionsGraphCached = (login, options) => loadSharedGraph(authService, login, options);
|
||||
|
||||
// Поиск без учёта регистра и «ё».
|
||||
function searchText(value) {
|
||||
@@ -247,24 +180,19 @@ 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 'взаимно';
|
||||
return node.direction === 'out' ? 'без ответа' : 'взаимно';
|
||||
}
|
||||
|
||||
// Переживает уход с экрана: возврат по «Связям» из профиля показывает ту же карту.
|
||||
const persisted = { centerLogin: '', expanded: [], filter: 'all', friendsOfFriends: false, interest: '', 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) },
|
||||
];
|
||||
@@ -396,7 +324,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
let noteSheet = null;
|
||||
let legendSheet = null;
|
||||
let search = null; // { query, topbar, layer, remote: { seq, query, items, loading, failed } }
|
||||
let waitingExpanded = false; // «Добавили вас» в списке: сначала несколько, по кнопке – все
|
||||
let groupsModel = null; // острова «Компаний» / «Интересов»: { lens, groups, byId, byPerson }
|
||||
let selectedGroupId = '';
|
||||
let groupSheet = null;
|
||||
@@ -905,16 +832,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
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';
|
||||
@@ -925,40 +842,6 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
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();
|
||||
@@ -984,8 +867,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
const rows = [
|
||||
['line', 'close_friend', 'Близкий друг'],
|
||||
['line', 'friend', 'Друг'],
|
||||
['line', 'contact', 'Контакт'],
|
||||
['dash', 'friend', 'Пунктир – связь только с одной стороны'],
|
||||
['dash', 'friend', 'Пунктир → точки – вы добавили друга, ответа пока нет'],
|
||||
['aura', '', 'Свечение вокруг – сияющий'],
|
||||
['badge', '', 'Синяя галочка – официальный аккаунт'],
|
||||
['mark', '', 'Цветная точка – ваша заметка или метка'],
|
||||
@@ -1005,7 +887,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
const tips = document.createElement('ul');
|
||||
tips.className = 'net-legend__tips';
|
||||
for (const tip of [
|
||||
'«По близости»: ближе к центру – близкие, дальше – друзья, снаружи – контакты. Знакомые между собой стоят рядом.',
|
||||
'«По близости»: ближе к центру – близкие друзья, дальше – друзья. Знакомые между собой стоят рядом.',
|
||||
'«Компании» (в меню «•••») собирают вместе тех, кто знаком между собой: школа, работа, друзья по увлечению. Нить между компаниями – сколько в них знакомых друг с другом. Нажмите на название компании – откроется её карточка, там её можно назвать.',
|
||||
'Человека можно перетащить в другую компанию – он останется в ней. Или нажмите «Перенести…» в его карточке.',
|
||||
'«Интересы» собирают людей у каналов, которые они читают; нажмите на канал – подсветятся все его читатели. «Города» – кто где живёт (по полю «Город» в профиле). Знакомства, подписки и города узнаются один раз и хранятся на этом устройстве.',
|
||||
@@ -1226,6 +1108,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
async function loadPeopleData(kind, { quiet = false, force = false } = {}) {
|
||||
if (disposed || !map) return false;
|
||||
const centerKey = normKey(centerLogin);
|
||||
const generationAtStart = peopleDataGeneration();
|
||||
const jobKey = `${kind}|${centerKey}`;
|
||||
if (lensLoads.has(jobKey) || (!force && (lensBlockedUntil.get(jobKey) || 0) > Date.now())) return false;
|
||||
const people = directPeople().slice(0, PEOPLE_DATA_LIMIT);
|
||||
@@ -1259,7 +1142,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
const near = new Map();
|
||||
for (const relation of buildGraphModel(graph, node.login).relations) {
|
||||
if (relation.key === node.id || !directIds.has(relation.key)) continue;
|
||||
near.set(relation.key, { type: relationTypeFromRelation(relation), mutual: relation.forward && relation.backward });
|
||||
if (relation.forward) near.set(relation.key, { type: relationTypeFromRelation(relation), mutual: relation.backward });
|
||||
}
|
||||
entry.people.set(node.id, near);
|
||||
} else if (kind === 'subs') {
|
||||
@@ -1277,7 +1160,9 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
job.done += 1;
|
||||
if (job.foreground && !disposed) syncLensProgress();
|
||||
});
|
||||
lensLoads.delete(jobKey);
|
||||
if (lensLoads.get(jobKey) === job) lensLoads.delete(jobKey);
|
||||
// Прежняя пачка данных могла закончиться уже после изменения дружбы.
|
||||
if (disposed || generationAtStart !== peopleDataGeneration()) return false;
|
||||
if (failed) lensBlockedUntil.set(jobKey, Date.now() + 60 * 1000);
|
||||
else lensBlockedUntil.delete(jobKey);
|
||||
// Освежили всех – отметка времени; если большинство не ответило, попробуем в следующий раз.
|
||||
@@ -1486,19 +1371,17 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
persist();
|
||||
}
|
||||
|
||||
// Состав по близости: «3 близких, 8 друзей, 15 контактов».
|
||||
// Состав по близости: здесь считаются только друзья.
|
||||
function compositionText(members) {
|
||||
const counts = { close: 0, friend: 0, contact: 0 };
|
||||
const counts = { close: 0, friend: 0 };
|
||||
members.forEach((id) => {
|
||||
const type = map?.byId.get(id)?.relationType;
|
||||
if (type === 'close_friend' || type === 'family') counts.close += 1;
|
||||
else if (type === 'friend') counts.friend += 1;
|
||||
else counts.contact += 1;
|
||||
});
|
||||
const parts = [];
|
||||
if (counts.close) parts.push(`${counts.close} ${pluralRu(counts.close, 'близкий', 'близких', 'близких')}`);
|
||||
if (counts.friend) parts.push(`${counts.friend} ${pluralRu(counts.friend, 'друг', 'друга', 'друзей')}`);
|
||||
if (counts.contact) parts.push(`${counts.contact} ${pluralRu(counts.contact, 'контакт', 'контакта', 'контактов')}`);
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
@@ -1922,11 +1805,9 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
ensureLensData();
|
||||
}
|
||||
|
||||
// --- фильтры: «Все / Близкие / Друзья / Контакты» – тем же переключателем, что в чатах;
|
||||
// реже нужное («Добавили вас», «Сияющие», «С заметкой», «Друзья друзей») – в «Ещё».
|
||||
const PRIMARY_FILTERS = ['all', 'close', 'friends', 'contacts'];
|
||||
// Дружеский круг: все, близкие, друзья; остальные условия – в меню «Ещё».
|
||||
const PRIMARY_FILTERS = ['all', 'close', 'friends'];
|
||||
const EXTRA_FILTERS = [
|
||||
{ id: 'incoming', short: 'Добавили', icon: 'user-plus' },
|
||||
{ id: 'shining', short: 'Сияющие', icon: 'sparkle' },
|
||||
{ id: 'notes', short: 'С заметкой', icon: 'edit' },
|
||||
];
|
||||
@@ -2204,15 +2085,12 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
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) : '',
|
||||
tag: '',
|
||||
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) },
|
||||
],
|
||||
@@ -2254,13 +2132,10 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
].filter((section) => section.items.length);
|
||||
}
|
||||
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));
|
||||
const rest = direct;
|
||||
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);
|
||||
}
|
||||
@@ -2285,18 +2160,7 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
section.prepend(groupDot(group.group));
|
||||
}
|
||||
frag.append(section);
|
||||
// Длинный «Добавили вас» не должен закрывать собой весь список: сначала трое.
|
||||
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')}<span>Показать всех · ${group.items.length}</span>`;
|
||||
more.addEventListener('click', () => { waitingExpanded = true; renderList(); });
|
||||
frag.append(more);
|
||||
}
|
||||
group.items.forEach((node) => frag.append(personRow(node, { withType })));
|
||||
}
|
||||
if (query) appendRemoteResults(frag, new Set(people.map((node) => node.id)));
|
||||
if (!people.length && map.nodes.length > 1 && !(query && search?.remote?.items?.length)) {
|
||||
@@ -2490,6 +2354,22 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
overlayObserver?.observe(stage);
|
||||
overlayObserver?.observe(filterBar);
|
||||
|
||||
function refreshConnectionsView() {
|
||||
if (disposed || !centerLogin) return;
|
||||
// Полный сброс отображаемых графов; запросы заново заполняют общий кэш.
|
||||
graphs.clear();
|
||||
lensLoads.clear();
|
||||
lensBlockedUntil.clear();
|
||||
groupsModel = null;
|
||||
if (map) restoreView = engine.getView();
|
||||
void load(centerLogin);
|
||||
}
|
||||
window.addEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
|
||||
const graphRefreshTimer = window.setInterval(() => {
|
||||
// TTL сам по себе не перерисовывает уже открытую карту — обновляем её при активности вкладки.
|
||||
if (!disposed && !document.hidden) refreshConnectionsView();
|
||||
}, CONNECTIONS_GRAPH_TTL_MS);
|
||||
|
||||
screen.cleanup = () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
@@ -2505,6 +2385,8 @@ export function render({ navigate, route, chrome } = {}) {
|
||||
window.cancelAnimationFrame(listFrame);
|
||||
window.clearTimeout(remoteTimer);
|
||||
window.removeEventListener(PEOPLE_NOTES_EVENT, onNotesChanged);
|
||||
window.removeEventListener(CONNECTIONS_GRAPH_CHANGED, refreshConnectionsView);
|
||||
window.clearInterval(graphRefreshTimer);
|
||||
document.removeEventListener('keydown', onKeydown);
|
||||
noteSheet?.close();
|
||||
legendSheet?.close();
|
||||
|
||||
@@ -12,11 +12,10 @@ function normKey(value) {
|
||||
const FAMILY_ROLES = ['parent', 'child', 'spouse', 'sibling'];
|
||||
|
||||
export 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';
|
||||
}
|
||||
|
||||
@@ -45,7 +44,7 @@ export function peopleFromGraphModel(graphModel) {
|
||||
for (const relation of Array.isArray(graphModel?.relations) ? graphModel.relations : []) {
|
||||
const login = normLogin(relation?.login);
|
||||
const key = normKey(login);
|
||||
if (!login || seen.has(key)) continue;
|
||||
if (!login || seen.has(key) || !relation?.forward) continue;
|
||||
seen.add(key);
|
||||
const forward = Boolean(relation?.forward);
|
||||
const backward = Boolean(relation?.backward);
|
||||
|
||||
@@ -1604,6 +1604,20 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
|
||||
return !edge.tie;
|
||||
}
|
||||
|
||||
// Подотрезок квадратичной Безье по параметру t (направление: добавивший → добавленный).
|
||||
function quadraticPart(g, from, to) {
|
||||
const point = (t) => ({
|
||||
x: (1 - t) ** 2 * g.x1 + 2 * t * (1 - t) * g.cx + t ** 2 * g.x2,
|
||||
y: (1 - t) ** 2 * g.y1 + 2 * t * (1 - t) * g.cy + t ** 2 * g.y2,
|
||||
});
|
||||
const first = point(from);
|
||||
const last = point(to);
|
||||
const dx = 2 * ((1 - from) * (g.cx - g.x1) + from * (g.x2 - g.cx));
|
||||
const dy = 2 * ((1 - from) * (g.cy - g.y1) + from * (g.y2 - g.cy));
|
||||
const dt = (to - from) / 2;
|
||||
return { first, ctrl: { x: first.x + dx * dt, y: first.y + dy * dt }, last };
|
||||
}
|
||||
|
||||
// Нити рисуются пачками одного вида: сотни отдельных штрихов со сменой пунктира – это
|
||||
// и была главная цена кадра на «друзьях друзей».
|
||||
function drawEdges(inView, widthScale) {
|
||||
@@ -1660,13 +1674,29 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
|
||||
for (const batch of ordered) {
|
||||
ctx.strokeStyle = rgba(colors.edge[batch.type], batch.alpha);
|
||||
ctx.lineWidth = EDGE_WIDTH[batch.type] * widthScale * (batch.incident ? 1.5 : 1);
|
||||
ctx.setLineDash(batch.mutual ? [] : [5 * widthScale, 4 * widthScale]);
|
||||
ctx.beginPath();
|
||||
for (const g of batch.list) {
|
||||
ctx.moveTo(g.x1, g.y1);
|
||||
ctx.quadraticCurveTo(g.cx, g.cy, g.x2, g.y2);
|
||||
if (batch.mutual) {
|
||||
ctx.setLineDash([]);
|
||||
ctx.beginPath();
|
||||
for (const g of batch.list) {
|
||||
ctx.moveTo(g.x1, g.y1);
|
||||
ctx.quadraticCurveTo(g.cx, g.cy, g.x2, g.y2);
|
||||
}
|
||||
ctx.stroke();
|
||||
} else {
|
||||
// От инициатора дружбы линия почти сплошная; возле адресата превращается в точки.
|
||||
// Делим кривую, сохраняя геометрию и пакетную отрисовку внутри каждого сегмента.
|
||||
const patterns = [[20, 3], [12, 4], [6, 4], [1, 5]];
|
||||
patterns.forEach(([dash, gap], section) => {
|
||||
ctx.setLineDash([dash * widthScale, gap * widthScale]);
|
||||
ctx.beginPath();
|
||||
for (const g of batch.list) {
|
||||
const part = quadraticPart(g, section / 4, (section + 1) / 4);
|
||||
ctx.moveTo(part.first.x, part.first.y);
|
||||
ctx.quadraticCurveTo(part.ctrl.x, part.ctrl.y, part.last.x, part.last.y);
|
||||
}
|
||||
ctx.stroke();
|
||||
});
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
|
||||
@@ -5,14 +5,29 @@
|
||||
// Сервер не трогаем: знакомства – из графа связей каждого человека, подписки – из списка
|
||||
// «Подписки» его профиля (публичные каналы), город – из параметра city его профиля.
|
||||
import { state } from '../../state.js';
|
||||
import { CONNECTIONS_GRAPH_CHANGED } from '../../services/connections-graph-cache.js';
|
||||
|
||||
const PREFIX = { ties: 'shine-network-ties-v1:', subs: 'shine-network-subs-v1:', cities: 'shine-network-cities-v1:' };
|
||||
const PREFIX = { ties: 'shine-network-ties-v2:', subs: 'shine-network-subs-v1:', cities: 'shine-network-cities-v1:' };
|
||||
export const PEOPLE_DATA_FRESH_MS = 12 * 60 * 60 * 1000; // старше – освежаются в фоне
|
||||
const TYPE_CODE = { close_friend: 3, family: 3, friend: 2, contact: 1 };
|
||||
const CODE_TYPE = { 3: 'close_friend', 2: 'friend', 1: 'contact' };
|
||||
|
||||
const memory = new Map(); // `${kind}|${owner}|${center}` → запись
|
||||
|
||||
let peopleGeneration = 0;
|
||||
export function peopleDataGeneration() { return peopleGeneration; }
|
||||
|
||||
export function invalidatePeopleData() {
|
||||
peopleGeneration += 1;
|
||||
memory.clear();
|
||||
const owner = ownerLogin();
|
||||
if (!owner) return;
|
||||
for (const prefix of Object.values(PREFIX)) {
|
||||
try { localStorage.removeItem(prefix + owner); } catch { /* хранилище может быть недоступно */ }
|
||||
}
|
||||
}
|
||||
if (typeof window !== 'undefined') window.addEventListener(CONNECTIONS_GRAPH_CHANGED, invalidatePeopleData);
|
||||
|
||||
function ownerLogin() {
|
||||
return String(state.session?.login || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createTopBar } from '../components/topbar.js';
|
||||
import { actionErrorText, toUserMessage } from '../services/ui-error-texts.js';
|
||||
import { confirmDialog } from '../components/confirm-dialog.js';
|
||||
import { showToast } from '../services/channels-ux.js';
|
||||
import { profile } from '../mock-data.js';
|
||||
import { authService, state } from '../state.js';
|
||||
@@ -18,7 +17,7 @@ import {
|
||||
saveProfileParamBlock,
|
||||
saveProfileStatus,
|
||||
} from '../services/user-profile-params.js';
|
||||
import { buildIdentityLines, loadUserProfileCard } from '../services/user-connections.js';
|
||||
import { buildIdentityLines } from '../services/user-connections.js';
|
||||
import { openAvatarWizard } from '../components/avatar-wizard.js';
|
||||
import { renderUserAvatar } from '../components/avatar-image.js';
|
||||
|
||||
@@ -55,45 +54,6 @@ const GENDER_OPTIONS = Object.freeze([
|
||||
{ value: PROFILE_GENDER_UNKNOWN, label: 'Не указан' },
|
||||
]);
|
||||
|
||||
// Родственные типы сохранены в протоколе, но пока намеренно скрыты из UI.
|
||||
const RELATIVE_RELATION_OPTIONS = Object.freeze([
|
||||
{ value: 'friend', label: 'Друг' },
|
||||
{ value: 'close_friend', label: 'Близкий друг' },
|
||||
]);
|
||||
|
||||
function normalizeGender(value) {
|
||||
const v = String(value || '').trim().toLowerCase();
|
||||
if (v === PROFILE_GENDER_MALE) return PROFILE_GENDER_MALE;
|
||||
if (v === PROFILE_GENDER_FEMALE) return PROFILE_GENDER_FEMALE;
|
||||
return PROFILE_GENDER_UNKNOWN;
|
||||
}
|
||||
|
||||
function relationAccusativeLabel(type, targetGender) {
|
||||
const gender = normalizeGender(targetGender);
|
||||
if (type === 'parent') {
|
||||
if (gender === PROFILE_GENDER_MALE) return 'отца';
|
||||
if (gender === PROFILE_GENDER_FEMALE) return 'мать';
|
||||
return 'родителя';
|
||||
}
|
||||
if (type === 'child') {
|
||||
if (gender === PROFILE_GENDER_MALE) return 'сына';
|
||||
if (gender === PROFILE_GENDER_FEMALE) return 'дочь';
|
||||
return 'ребёнка';
|
||||
}
|
||||
if (type === 'sibling') {
|
||||
if (gender === PROFILE_GENDER_MALE) return 'брата';
|
||||
if (gender === PROFILE_GENDER_FEMALE) return 'сестру';
|
||||
return 'брата/сестру';
|
||||
}
|
||||
if (type === 'spouse') {
|
||||
if (gender === PROFILE_GENDER_MALE) return 'мужа';
|
||||
if (gender === PROFILE_GENDER_FEMALE) return 'жену';
|
||||
return 'жену/мужа';
|
||||
}
|
||||
if (type === 'friend') return 'друга';
|
||||
return 'близкого друга';
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
return String(text || '')
|
||||
.replaceAll('&', '&')
|
||||
@@ -147,18 +107,9 @@ export function render({ navigate, chrome }) {
|
||||
const listWrap = document.createElement('div');
|
||||
listWrap.className = 'nav-list profile-param-list';
|
||||
|
||||
const relativesCard = document.createElement('div');
|
||||
relativesCard.className = 'card stack';
|
||||
relativesCard.innerHTML = `
|
||||
<div class="profile-param-value"><b>Друзья</b></div>
|
||||
<div class="meta-muted">Добавьте человека в друзья или в близкие друзья.</div>
|
||||
<button class="secondary-btn" type="button" data-add-relative="true">Добавить друга</button>
|
||||
`;
|
||||
|
||||
const reloadBtn = topRow.querySelector('[data-reload="true"]');
|
||||
const accountRoleBtn = badgesRow.querySelector('[data-status="account_role"]');
|
||||
const shineBtn = badgesRow.querySelector('[data-status="shine"]');
|
||||
const addRelativeBtn = relativesCard.querySelector('[data-add-relative="true"]');
|
||||
const avatarActionEl = topRow.querySelector('[data-change-avatar="true"]');
|
||||
|
||||
let currentFields = [];
|
||||
@@ -363,224 +314,6 @@ export function render({ navigate, chrome }) {
|
||||
});
|
||||
}
|
||||
|
||||
function openAddRelativeModal({ contacts = [] } = {}) {
|
||||
const root = document.getElementById('modal-root');
|
||||
if (!root) return Promise.resolve(null);
|
||||
const preparedContacts = Array.isArray(contacts)
|
||||
? contacts
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const uniqueContacts = Array.from(new Set(preparedContacts.map((item) => item.toLowerCase())))
|
||||
.map((key) => preparedContacts.find((item) => item.toLowerCase() === key))
|
||||
.filter(Boolean);
|
||||
|
||||
root.innerHTML = `
|
||||
<div class="modal" id="profile-add-relative-modal">
|
||||
<div class="modal-card stack">
|
||||
<h3 class="modal-title">Добавить связь</h3>
|
||||
<label class="meta-muted" for="profile-relative-kind">Какой тип связи вы хотите добавить?</label>
|
||||
<select class="input profile-relation-select" id="profile-relative-kind">
|
||||
${RELATIVE_RELATION_OPTIONS.map((item) => (
|
||||
`<option value="${item.value}">${item.label}</option>`
|
||||
)).join('')}
|
||||
</select>
|
||||
<label class="meta-muted" for="profile-relative-login">Логин пользователя</label>
|
||||
<input
|
||||
class="input"
|
||||
id="profile-relative-login"
|
||||
type="text"
|
||||
maxlength="30"
|
||||
placeholder="Введите логин пользователя"
|
||||
/>
|
||||
<div class="meta-muted profile-relative-search-meta" id="profile-relative-search-meta">
|
||||
Начните вводить логин. Поиск запустится через 2 секунды паузы или по Enter.
|
||||
</div>
|
||||
<div class="profile-relative-search-suggest" id="profile-relative-search-suggest" hidden></div>
|
||||
<div class="meta-muted inline-error" id="profile-relative-error"></div>
|
||||
<div class="form-actions-grid">
|
||||
<button class="secondary-btn" id="profile-relative-cancel" type="button">Отмена</button>
|
||||
<button class="primary-btn" id="profile-relative-submit" type="button">Продолжить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const modal = root.querySelector('#profile-add-relative-modal');
|
||||
const kindEl = root.querySelector('#profile-relative-kind');
|
||||
const loginEl = root.querySelector('#profile-relative-login');
|
||||
const submitEl = root.querySelector('#profile-relative-submit');
|
||||
const cancelEl = root.querySelector('#profile-relative-cancel');
|
||||
const errorEl = root.querySelector('#profile-relative-error');
|
||||
const searchMetaEl = root.querySelector('#profile-relative-search-meta');
|
||||
const suggestEl = root.querySelector('#profile-relative-search-suggest');
|
||||
|
||||
if (!(modal instanceof HTMLElement) || !(kindEl instanceof HTMLSelectElement) || !(loginEl instanceof HTMLInputElement)) {
|
||||
root.innerHTML = '';
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
let closed = false;
|
||||
let searchTimerId = 0;
|
||||
let searchSeq = 0;
|
||||
|
||||
const clearSearchTimer = () => {
|
||||
if (!searchTimerId) return;
|
||||
window.clearTimeout(searchTimerId);
|
||||
searchTimerId = 0;
|
||||
};
|
||||
|
||||
const uniqueCaseInsensitive = (list) => {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
(Array.isArray(list) ? list : []).forEach((item) => {
|
||||
const value = String(item || '').trim();
|
||||
if (!value) return;
|
||||
const key = value.toLowerCase();
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
out.push(value);
|
||||
});
|
||||
return out;
|
||||
};
|
||||
|
||||
const renderSuggestions = (list) => {
|
||||
if (!(suggestEl instanceof HTMLElement)) return;
|
||||
const values = uniqueCaseInsensitive(list).slice(0, 5);
|
||||
if (!values.length) {
|
||||
suggestEl.hidden = true;
|
||||
suggestEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
suggestEl.hidden = false;
|
||||
suggestEl.innerHTML = values.map((value) => (
|
||||
`<button type="button" class="ui-button profile-relative-suggest-item" data-login="${escapeHtml(value)}">${escapeHtml(value)}</button>`
|
||||
)).join('');
|
||||
};
|
||||
|
||||
const searchContactsFallback = (prefix) => {
|
||||
const query = String(prefix || '').trim().toLowerCase();
|
||||
if (!query) return [];
|
||||
return uniqueContacts
|
||||
.filter((entry) => entry.toLowerCase().startsWith(query))
|
||||
.slice(0, 5);
|
||||
};
|
||||
|
||||
const runSearch = async ({ withErrorMessage = false } = {}) => {
|
||||
const prefix = String(loginEl.value || '').trim();
|
||||
if (!prefix) {
|
||||
renderSuggestions([]);
|
||||
if (searchMetaEl) {
|
||||
searchMetaEl.textContent = 'Начните вводить логин. Поиск запустится через 2 секунды паузы или по Enter.';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (searchMetaEl) searchMetaEl.textContent = `Поиск пользователей по префиксу «${prefix}»...`;
|
||||
const reqId = ++searchSeq;
|
||||
let found = [];
|
||||
let searchFailed = false;
|
||||
|
||||
try {
|
||||
const payload = await authService.searchUsers(prefix);
|
||||
found = Array.isArray(payload) ? payload : [];
|
||||
} catch {
|
||||
searchFailed = true;
|
||||
found = [];
|
||||
}
|
||||
|
||||
if (closed || reqId !== searchSeq) return;
|
||||
|
||||
const query = prefix.toLowerCase();
|
||||
const candidateList = uniqueCaseInsensitive([
|
||||
...found,
|
||||
...searchContactsFallback(prefix),
|
||||
])
|
||||
.filter((entry) => entry.toLowerCase().startsWith(query))
|
||||
.slice(0, 5);
|
||||
|
||||
renderSuggestions(candidateList);
|
||||
|
||||
if (candidateList.length > 0) {
|
||||
if (searchMetaEl) searchMetaEl.textContent = `Найдено ${candidateList.length} пользователей. Выберите пользователя из списка.`;
|
||||
return;
|
||||
}
|
||||
|
||||
if (searchFailed) {
|
||||
if (searchMetaEl) searchMetaEl.textContent = 'Не удалось получить список пользователей. Уточните логин вручную.';
|
||||
if (withErrorMessage && errorEl) errorEl.textContent = 'Ошибка поиска пользователей.';
|
||||
return;
|
||||
}
|
||||
if (searchMetaEl) searchMetaEl.textContent = 'Пользователи с таким префиксом не найдены.';
|
||||
};
|
||||
|
||||
const close = (payload = null) => {
|
||||
closed = true;
|
||||
clearSearchTimer();
|
||||
root.innerHTML = '';
|
||||
resolve(payload);
|
||||
};
|
||||
|
||||
const submit = () => {
|
||||
const relationType = String(kindEl.value || '').trim();
|
||||
const toLogin = String(loginEl.value || '').trim();
|
||||
if (!relationType) {
|
||||
if (errorEl) errorEl.textContent = 'Выберите тип связи.';
|
||||
return;
|
||||
}
|
||||
if (!toLogin) {
|
||||
if (errorEl) errorEl.textContent = 'Введите логин пользователя.';
|
||||
return;
|
||||
}
|
||||
close({ relationType, toLogin });
|
||||
};
|
||||
|
||||
modal.addEventListener('click', (event) => {
|
||||
if (event.target === modal) close(null);
|
||||
});
|
||||
cancelEl?.addEventListener('click', () => close(null));
|
||||
submitEl?.addEventListener('click', submit);
|
||||
suggestEl?.addEventListener('click', (event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
const button = target.closest('[data-login]');
|
||||
if (!(button instanceof HTMLElement)) return;
|
||||
const pickedLogin = String(button.dataset.login || '').trim();
|
||||
if (!pickedLogin) return;
|
||||
loginEl.value = pickedLogin;
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
if (searchMetaEl) searchMetaEl.textContent = `Выбран пользователь «${pickedLogin}». Нажмите «Продолжить».`;
|
||||
renderSuggestions([]);
|
||||
});
|
||||
loginEl.addEventListener('input', () => {
|
||||
if (errorEl) errorEl.textContent = '';
|
||||
clearSearchTimer();
|
||||
const value = String(loginEl.value || '').trim();
|
||||
if (!value) {
|
||||
renderSuggestions([]);
|
||||
if (searchMetaEl) {
|
||||
searchMetaEl.textContent = 'Начните вводить логин. Поиск запустится через 2 секунды паузы или по Enter.';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (searchMetaEl) searchMetaEl.textContent = 'Ожидание паузы 2 секунды для поиска...';
|
||||
searchTimerId = window.setTimeout(() => {
|
||||
runSearch({ withErrorMessage: false });
|
||||
}, 2000);
|
||||
});
|
||||
loginEl.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
clearSearchTimer();
|
||||
runSearch({ withErrorMessage: true });
|
||||
}
|
||||
});
|
||||
window.setTimeout(() => loginEl.focus(), 0);
|
||||
});
|
||||
}
|
||||
|
||||
function renderFields(fields) {
|
||||
listWrap.innerHTML = '';
|
||||
fields.forEach((field) => {
|
||||
@@ -611,7 +344,6 @@ export function render({ navigate, chrome }) {
|
||||
reloadBtn.disabled = true;
|
||||
accountRoleBtn.disabled = true;
|
||||
shineBtn.disabled = true;
|
||||
if (addRelativeBtn instanceof HTMLButtonElement) addRelativeBtn.disabled = true;
|
||||
|
||||
try {
|
||||
const snapshot = await loadProfileSnapshot(login);
|
||||
@@ -637,7 +369,6 @@ export function render({ navigate, chrome }) {
|
||||
reloadBtn.disabled = false;
|
||||
accountRoleBtn.disabled = false;
|
||||
shineBtn.disabled = false;
|
||||
if (addRelativeBtn instanceof HTMLButtonElement) addRelativeBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -750,86 +481,6 @@ export function render({ navigate, chrome }) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onAddRelativeClick() {
|
||||
const sessionLogin = String(login || '').trim();
|
||||
if (!sessionLogin) {
|
||||
showToast('Для добавления связи нужен вход в аккаунт.', { kind: 'error' });
|
||||
return;
|
||||
}
|
||||
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Подготовка окна добавления связи...';
|
||||
|
||||
let contacts = [];
|
||||
try {
|
||||
const payload = await authService.listContacts();
|
||||
contacts = Array.isArray(payload?.contacts) ? payload.contacts : [];
|
||||
} catch {
|
||||
contacts = [];
|
||||
}
|
||||
|
||||
const picked = await openAddRelativeModal({ contacts });
|
||||
if (!picked) {
|
||||
status.className = 'status-line is-available';
|
||||
status.textContent = 'Добавление связи отменено.';
|
||||
return;
|
||||
}
|
||||
|
||||
const relationType = String(picked.relationType || '').trim().toLowerCase();
|
||||
const inputLogin = String(picked.toLogin || '').trim();
|
||||
if (!relationType || !inputLogin) return;
|
||||
if (inputLogin.toLowerCase() === sessionLogin.toLowerCase()) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = 'Нельзя добавить связь с самим собой.';
|
||||
return;
|
||||
}
|
||||
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Проверка пользователя...';
|
||||
|
||||
let targetCard;
|
||||
try {
|
||||
targetCard = await loadUserProfileCard(inputLogin);
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = actionErrorText('Не удалось найти пользователя', error);
|
||||
showLocalErrorAlert('Не удалось выбрать пользователя', error);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetLogin = String(targetCard?.login || inputLogin).trim();
|
||||
const targetGender = normalizeGender(targetCard?.gender || PROFILE_GENDER_UNKNOWN);
|
||||
const relationLabel = relationAccusativeLabel(relationType, targetGender);
|
||||
const confirmed = await confirmDialog({
|
||||
title: 'Добавить связь?',
|
||||
text: `Добавить ${targetLogin} как ${relationLabel}?`,
|
||||
confirmLabel: 'Добавить',
|
||||
});
|
||||
if (!confirmed) return;
|
||||
|
||||
status.className = 'status-line';
|
||||
status.textContent = 'Сохранение связи...';
|
||||
|
||||
try {
|
||||
if (!state.session.storagePwdInMemory) {
|
||||
throw new Error('Нет storagePwd в памяти сессии. Выполните вход заново.');
|
||||
}
|
||||
await authService.setUserRelation({
|
||||
login: sessionLogin,
|
||||
toLogin: targetLogin,
|
||||
kind: relationType,
|
||||
enabled: true,
|
||||
storagePwd: state.session.storagePwdInMemory,
|
||||
});
|
||||
status.className = 'status-line is-available';
|
||||
status.textContent = `Связь добавлена: ${targetLogin} как ${relationLabel}.`;
|
||||
} catch (error) {
|
||||
status.className = 'status-line is-unavailable';
|
||||
status.textContent = actionErrorText('Не удалось добавить связь', error);
|
||||
showLocalErrorAlert('Не удалось добавить связь', error);
|
||||
}
|
||||
}
|
||||
|
||||
listWrap.addEventListener('click', (event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
@@ -847,10 +498,9 @@ export function render({ navigate, chrome }) {
|
||||
reloadBtn.addEventListener('click', refreshProfileSnapshot);
|
||||
accountRoleBtn.addEventListener('click', () => onStatusClick('account_role'));
|
||||
shineBtn.addEventListener('click', () => onStatusClick('shine'));
|
||||
addRelativeBtn?.addEventListener('click', onAddRelativeClick);
|
||||
avatarActionEl?.addEventListener('click', () => { void onChangeAvatarClick(); });
|
||||
|
||||
card.append(topRow, badgesRow, status, listWrap, relativesCard);
|
||||
card.append(topRow, badgesRow, status, listWrap);
|
||||
screen.append(card);
|
||||
|
||||
updateAvatarUi();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WsJsonClient } from './ws-client.js';
|
||||
import { invalidateConnectionsGraphCache } from './connections-graph-cache.js';
|
||||
import {
|
||||
base64ToBytes,
|
||||
bytesToBase64,
|
||||
@@ -3368,7 +3369,9 @@ export class AuthService {
|
||||
const kinds = CONNECTION_SUBTYPES[cleanKind];
|
||||
if (!kinds) throw new Error(`Неподдерживаемый тип связи: ${kind}`);
|
||||
const subType = enabled ? kinds.on : kinds.off;
|
||||
return this.addBlockConnection({ login, toLogin, subType, storagePwd });
|
||||
const result = await this.addBlockConnection({ login, toLogin, subType, storagePwd });
|
||||
invalidateConnectionsGraphCache();
|
||||
return result;
|
||||
}
|
||||
|
||||
async addBlockUserParam({ login, param, value, storagePwd }) {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// Единый кэш графов для обеих версий экрана «Связи».
|
||||
// Через две минуты запись устаревает; пока экран открыт, он сам перечитывает граф.
|
||||
// После любого подтверждённого изменения отношения кэш целиком сбрасывается.
|
||||
export const CONNECTIONS_GRAPH_CHANGED = 'shine:connections-graph-changed';
|
||||
export const CONNECTIONS_GRAPH_TTL_MS = 2 * 60 * 1000;
|
||||
const CACHE_LIMIT = 240;
|
||||
const cache = new Map();
|
||||
const inflight = new Map();
|
||||
let generation = 0;
|
||||
|
||||
function cacheKey(service, login) {
|
||||
const server = String(service?.serverUrl || '').trim().toLowerCase();
|
||||
return `${server}|${String(login || '').trim().toLowerCase()}`;
|
||||
}
|
||||
|
||||
export function cachedConnectionsGraph(service, login) {
|
||||
const entry = cache.get(cacheKey(service, login));
|
||||
return entry && Date.now() - entry.savedAt < CONNECTIONS_GRAPH_TTL_MS ? entry.graph : null;
|
||||
}
|
||||
|
||||
// invalidate делается после подтверждения записи, но до любого повторного запроса графа.
|
||||
// generation не даёт устаревшему ответу незавершённого запроса вернуться в кэш.
|
||||
export function invalidateConnectionsGraphCache() {
|
||||
generation += 1;
|
||||
cache.clear();
|
||||
inflight.clear();
|
||||
// Сбрасываем и локальные снимки дополнительного слоя (12 ч), даже если Modern UI
|
||||
// ещё не открывали в этой вкладке. Старые versions удаляются одновременно.
|
||||
try {
|
||||
for (let index = localStorage.length - 1; index >= 0; index -= 1) {
|
||||
const key = localStorage.key(index);
|
||||
if (/^shine-network-(ties|subs|cities)-v\d+:/.test(key)) localStorage.removeItem(key);
|
||||
}
|
||||
} catch { /* storage может быть недоступен */ }
|
||||
if (typeof window !== 'undefined') window.dispatchEvent(new Event(CONNECTIONS_GRAPH_CHANGED));
|
||||
}
|
||||
|
||||
export async function getConnectionsGraphCached(service, login, { force = false, retries = 0 } = {}) {
|
||||
const clean = String(login || '').trim();
|
||||
if (!clean) throw new Error('LOGIN_REQUIRED');
|
||||
const key = cacheKey(service, clean);
|
||||
if (!force) {
|
||||
const graph = cachedConnectionsGraph(service, clean);
|
||||
if (graph) return graph;
|
||||
}
|
||||
// Включая принудительную загрузку: не запускаем параллельных запросов одного графа.
|
||||
if (inflight.has(key)) return inflight.get(key);
|
||||
|
||||
const startedAtGeneration = generation;
|
||||
const request = (async () => {
|
||||
let lastError = null;
|
||||
for (let attempt = 0; attempt <= Math.max(0, retries); attempt += 1) {
|
||||
try {
|
||||
const graph = await service.getUserConnectionsGraph(clean);
|
||||
if (startedAtGeneration !== generation) {
|
||||
// Запись произошла во время запроса: нельзя возвращать старый снимок.
|
||||
return getConnectionsGraphCached(service, clean, { force: true, retries });
|
||||
}
|
||||
cache.delete(key);
|
||||
cache.set(key, { graph, savedAt: Date.now() });
|
||||
while (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
|
||||
return graph;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt < retries) await new Promise((resolve) => setTimeout(resolve, 120 * (attempt + 1)));
|
||||
}
|
||||
}
|
||||
throw lastError || new Error('GRAPH_LOAD_FAILED');
|
||||
})();
|
||||
|
||||
inflight.set(key, request);
|
||||
try { return await request; }
|
||||
finally { if (inflight.get(key) === request) inflight.delete(key); }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Один tag на пару (получатель, отправитель); одинаковый для фонового WS и Web Push.
|
||||
export function dmNotificationTag(toLogin, fromLogin) {
|
||||
const to = encodeURIComponent(String(toLogin || '').trim().toLowerCase());
|
||||
const from = encodeURIComponent(String(fromLogin || '').trim().toLowerCase());
|
||||
return `shine-dm:${to}:${from}`;
|
||||
}
|
||||
|
||||
export function dmUnreadLabel(count) {
|
||||
const n = Math.max(1, Math.trunc(Number(count) || 1));
|
||||
const lastTwo = n % 100;
|
||||
const last = n % 10;
|
||||
if (!(lastTwo >= 11 && lastTwo <= 14) && last === 1) return `${n} непрочитанное сообщение`;
|
||||
if (!(lastTwo >= 11 && lastTwo <= 14) && last >= 2 && last <= 4) return `${n} непрочитанных сообщения`;
|
||||
return `${n} непрочитанных сообщений`;
|
||||
}
|
||||
|
||||
// Локальное прочтение: закрываем notification и сообщаем SW, чтобы старый push его не вернул.
|
||||
export async function closeDmNotification(toLogin, fromLogin) {
|
||||
if (!toLogin || !fromLogin || !('serviceWorker' in navigator)) return;
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.getRegistration();
|
||||
if (!registration) return;
|
||||
const tag = dmNotificationTag(toLogin, fromLogin);
|
||||
const notifications = await registration.getNotifications({ tag });
|
||||
const latestSeenVersionMs = notifications.reduce((latest, notification) =>
|
||||
Math.max(latest, Number(notification.data?.notificationVersionMs || 0)), 0);
|
||||
notifications.forEach((notification) => notification.close());
|
||||
const worker = navigator.serviceWorker.controller || registration.active;
|
||||
worker?.postMessage({ type: 'SHINE_DM_READ', toLogin, fromLogin, latestSeenVersionMs });
|
||||
} catch {
|
||||
// Недоступность браузерного API не мешает прочтению сообщений.
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { AuthService } from './services/auth-service.js';
|
||||
import { closeDmNotification } from './services/dm-push-notifications.js';
|
||||
import { listStoredMessages, putStoredMessage, deleteStoredMessage, clearStoredMessages } from './services/message-store.js';
|
||||
import { rpcEndpointFromShineHttp, setSolanaCluster } from './services/solana-rpc-gateway.js';
|
||||
import {
|
||||
@@ -956,6 +957,11 @@ export function markChatRead(chatId) {
|
||||
changed += 1;
|
||||
}
|
||||
});
|
||||
// Вызывается только когда чат действительно просматривается; даже если локальный счётчик уже 0,
|
||||
// надо снять системное уведомление, полученное до открытия страницы.
|
||||
if (state.session?.login && normalizedChatId) {
|
||||
void closeDmNotification(state.session.login, normalizedChatId);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user