SHA256
Добавили связи V3
This commit is contained in:
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
client.version=1.20.27
|
client.version=1.20.28
|
||||||
server.version=1.16.19
|
server.version=1.16.19
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Связи — версия 3: интерактивная карта исследования
|
||||||
|
|
||||||
|
Реализация: `shine-UI/js/pages/network-explorer/`, переключатель версии —
|
||||||
|
`shine-UI/js/pages/network-version-switcher.js`. V1 и V2 остаются отдельными режимами.
|
||||||
|
Новые серверные операции и форматы блокчейна **не вводились**.
|
||||||
|
|
||||||
|
## Управление
|
||||||
|
|
||||||
|
- `Близкие` — рёбра только типа `close_friend` (тип выбирается владельцем исходящего отношения).
|
||||||
|
- `Сияющие` — только сияющие пользователи; выбранный центр виден всегда.
|
||||||
|
- `X2` — для текущего пользователя дополнительно читаем друзей каждого непосредственного друга,
|
||||||
|
по четыре запроса одновременно. Чтение прогрессивное: текущий граф показывается сразу,
|
||||||
|
остальные ветки появляются после завершения запросов; ошибки не скрывают успешные ветки.
|
||||||
|
- `Глубина: 0–4` (старт `1`) — максимальное **кратчайшее** расстояние в уже исследованном
|
||||||
|
графе: `1 + глубина`, если X2 выключен, и `2 + глубина`, если X2 включён.
|
||||||
|
Для определения расстояния по известным исходящим дружеским рёбрам используется BFS без
|
||||||
|
учёта их направления; оригинальное направление сохраняется для отображения отношений.
|
||||||
|
- Верхнее меню `⋮`: «Искать пользователей» и «Очистить кэш».
|
||||||
|
Очистка удаляет **только кэш V3**, обнуляет исследованный граф и заново запрашивает
|
||||||
|
связи текущего пользователя. Поиск использует текущий серверный `searchUsers`.
|
||||||
|
|
||||||
|
В отличие от V1, V3 не хранит последовательность посещённых центров. При выборе
|
||||||
|
любого пользователя общая исследованная сеть сохраняется, но на экране остаются только
|
||||||
|
вершины в пределах заданной глубины. Совпадающие пользователи не дублируются;
|
||||||
|
между видимыми вершинами объединяются известные связи.
|
||||||
|
|
||||||
|
## Размеры и размещение
|
||||||
|
|
||||||
|
Размер кружочка определяется актуальной полнотой видимых исходящих дружеских связей:
|
||||||
|
|
||||||
|
- **Большой** (масштаб `1`) — его полный исходящий список известен и все друзья,
|
||||||
|
подходящие под текущие фильтры, видны на карте.
|
||||||
|
- **Маленький** (масштаб `0.5`) — список ещё не прочитан либо часть его друзей сейчас
|
||||||
|
за пределом глубины. Линии между двумя маленькими кружочками не рисуются.
|
||||||
|
|
||||||
|
Размер выбранного центра такой же, как у остальных (не `1.78`, как в V1).
|
||||||
|
Движок получает фиксированные мировые координаты, чтобы сохранять позицию при
|
||||||
|
пересчётах/фильтрах. Кружочки перетаскиваются вручную, сцена панорамируется и
|
||||||
|
масштабируется (колесо/щипок). Координаты сохраняются внутри активной вкладки
|
||||||
|
при переходах по V3; после перезагрузки раскладка строится заново.
|
||||||
|
|
||||||
|
## Кэш и обновление
|
||||||
|
|
||||||
|
В отличие от общего двухминутного кэша V1/V2 у V3 собственный IndexedDB
|
||||||
|
`shine-network-explorer-v3`. Запись хранит ответ `getUserConnectionsGraph`,
|
||||||
|
идентификатор сервера/аккаунта/логина и отметку времени. Время жизни — 24 часа;
|
||||||
|
просроченное повторно запрашивается при обращении, а просроченные рёбра исключаются
|
||||||
|
из исследованного графа. При открытии страницы до 1000 свежих изученных графов
|
||||||
|
восстанавливаются без сетевых запросов; память ограничена 800 горячими записями.
|
||||||
|
Если IndexedDB недоступен, работает временное кэширование в памяти.
|
||||||
|
|
||||||
|
Пока вкладка V3 открыта, раз в пять минут проверяется актуальность выбранного центра.
|
||||||
|
Подтверждённое изменение дружеских связей через UI также сбрасывает кэш V3, если
|
||||||
|
этот экран открыт. Операция очистки инвалидирует незавершённые загрузки.
|
||||||
|
|
||||||
|
## Проверка
|
||||||
|
|
||||||
|
`node --test shine-UI/tests/network-explorer-v3.test.mjs` проверяет BFS, глубину,
|
||||||
|
фильтры, дедупликацию, размеры, направление линий, TTL, изоляцию аккаунтов и очистку.
|
||||||
|
Не является заменой проверки с реальным сервером и на мобильном устройстве:
|
||||||
|
особенно нужно проверить производительность для пользователей с сотнями связей,
|
||||||
|
запросы X2 и сохранение координат при жестах.
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
Галерея сохранена без изменений и ещё не отражает итоговое сочетание решений. Для последующего переноса источником истины служит `DESIGN.md`, а не детали одного старого варианта. Эта галерея не является описанием текущего кода приложения.
|
Галерея сохранена без изменений и ещё не отражает итоговое сочетание решений. Для последующего переноса источником истины служит `DESIGN.md`, а не детали одного старого варианта. Эта галерея не является описанием текущего кода приложения.
|
||||||
|
|
||||||
- [Локализация UI (этап 1)](I18N.md) — языковой движок, приоритет системного языка и глобальные настройки.
|
- [Локализация UI (этап 1)](I18N.md) — языковой движок, приоритет системного языка и глобальные настройки.
|
||||||
|
- [Связи V3: исследование графа](NETWORK_EXPLORER_V3.md) — BFS-глубина, X2, размеры аватарок, кэш 24 часа.
|
||||||
- [PWA: масштабирование и аватар профиля](PWA_VIEWPORT_AND_AVATAR_PREVIEW.md) — поведение полноэкранного интерфейса и просмотра фотографии.
|
- [PWA: масштабирование и аватар профиля](PWA_VIEWPORT_AND_AVATAR_PREVIEW.md) — поведение полноэкранного интерфейса и просмотра фотографии.
|
||||||
- [Заявления о статусах и предупреждения о блокчейне](PROFILE_DECLARATIONS_AND_CONSENT.md) — действующие сценарии профиля, лайков и подтверждений на 06.11.2026.
|
- [Заявления о статусах и предупреждения о блокчейне](PROFILE_DECLARATIONS_AND_CONSENT.md) — действующие сценарии профиля, лайков и подтверждений на 06.11.2026.
|
||||||
|
|
||||||
|
|||||||
@@ -4170,7 +4170,8 @@
|
|||||||
"text_001": "<span>Version:</span>",
|
"text_001": "<span>Version:</span>",
|
||||||
"text_003": "Version 2",
|
"text_003": "Version 2",
|
||||||
"text_002": "Version 1",
|
"text_002": "Version 1",
|
||||||
"text_004": "Communications screen version"
|
"text_004": "Communications screen version",
|
||||||
|
"text_005": "Version 3"
|
||||||
},
|
},
|
||||||
"media_viewer": {
|
"media_viewer": {
|
||||||
"text_001": "Close",
|
"text_001": "Close",
|
||||||
@@ -4196,6 +4197,19 @@
|
|||||||
"open": "Enlarge avatar",
|
"open": "Enlarge avatar",
|
||||||
"dialog": "Avatar preview",
|
"dialog": "Avatar preview",
|
||||||
"close": "Close avatar preview"
|
"close": "Close avatar preview"
|
||||||
|
},
|
||||||
|
"network_explorer": {
|
||||||
|
"depth": "Depth: {value1}",
|
||||||
|
"depth_hint": "Up to {value1} links from the selected person. Tap to change depth.",
|
||||||
|
"menu": "Connections menu",
|
||||||
|
"search": "Find users",
|
||||||
|
"clear_cache": "Clear cache",
|
||||||
|
"loading": "Loading connections…",
|
||||||
|
"progress": "Loading connections: {value1}/{value2}",
|
||||||
|
"partial": "Could not load {value1} branches. The rest of the map is available.",
|
||||||
|
"error": "Could not load connections. Check your connection or try another user.",
|
||||||
|
"clearing": "Clearing cache…",
|
||||||
|
"a11y": "Center: {value1}. {value2} users shown on the map."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
|
|||||||
@@ -4151,7 +4151,8 @@
|
|||||||
"text_001": "<span>Версия:</span>",
|
"text_001": "<span>Версия:</span>",
|
||||||
"text_002": "Версия 1",
|
"text_002": "Версия 1",
|
||||||
"text_003": "Версия 2",
|
"text_003": "Версия 2",
|
||||||
"text_004": "Версия экрана Связи"
|
"text_004": "Версия экрана Связи",
|
||||||
|
"text_005": "Версия 3"
|
||||||
},
|
},
|
||||||
"node_menu": {
|
"node_menu": {
|
||||||
"text_001": "Контакт",
|
"text_001": "Контакт",
|
||||||
@@ -4196,6 +4197,19 @@
|
|||||||
"open": "Увеличить аватар",
|
"open": "Увеличить аватар",
|
||||||
"dialog": "Просмотр аватара",
|
"dialog": "Просмотр аватара",
|
||||||
"close": "Закрыть просмотр аватара"
|
"close": "Закрыть просмотр аватара"
|
||||||
|
},
|
||||||
|
"network_explorer": {
|
||||||
|
"depth": "Глубина: {value1}",
|
||||||
|
"depth_hint": "Максимум {value1} связей от выбранного пользователя. Нажмите, чтобы изменить глубину.",
|
||||||
|
"menu": "Меню связей",
|
||||||
|
"search": "Искать пользователей",
|
||||||
|
"clear_cache": "Очистить кэш",
|
||||||
|
"loading": "Загрузка связей…",
|
||||||
|
"progress": "Загрузка связей: {value1}/{value2}",
|
||||||
|
"partial": "Не удалось загрузить {value1} веток. Остальная карта доступна.",
|
||||||
|
"error": "Не удалось загрузить связи. Проверьте соединение или попробуйте другого пользователя.",
|
||||||
|
"clearing": "Очистка кэша…",
|
||||||
|
"a11y": "Центр: {value1}. На карте {value2} пользователей."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"errors": {
|
"errors": {
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// V3-only cache: IndexedDB + memory fallback, TTL 24 hours. V1/V2 retain 2-minute TTL.
|
||||||
|
export const EXPLORER_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const DB_NAME = 'shine-network-explorer-v3';
|
||||||
|
const STORE = 'connections';
|
||||||
|
let dbPromise = null;
|
||||||
|
const memory = new Map();
|
||||||
|
const inflight = new Map();
|
||||||
|
let epoch = 0;
|
||||||
|
|
||||||
|
function dbOpen() {
|
||||||
|
if (typeof indexedDB === 'undefined') return Promise.resolve(null);
|
||||||
|
if (!dbPromise) dbPromise = new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const request = indexedDB.open(DB_NAME, 1);
|
||||||
|
request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: 'key' });
|
||||||
|
request.onsuccess = () => resolve(request.result);
|
||||||
|
request.onerror = () => resolve(null);
|
||||||
|
request.onblocked = () => resolve(null);
|
||||||
|
} catch { resolve(null); }
|
||||||
|
});
|
||||||
|
return dbPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function read(key) {
|
||||||
|
const db = await dbOpen();
|
||||||
|
if (!db) return null;
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const req = db.transaction(STORE, 'readonly').objectStore(STORE).get(key);
|
||||||
|
req.onsuccess = () => resolve(req.result || null);
|
||||||
|
req.onerror = () => resolve(null);
|
||||||
|
} catch { resolve(null); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function write(record) {
|
||||||
|
const db = await dbOpen();
|
||||||
|
if (!db) return;
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const tx = db.transaction(STORE, 'readwrite');
|
||||||
|
tx.objectStore(STORE).put(record);
|
||||||
|
tx.oncomplete = resolve;
|
||||||
|
tx.onerror = resolve;
|
||||||
|
tx.onabort = resolve;
|
||||||
|
} catch { resolve(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Восстанавливаем ранее исследованную карту без сети. Просроченные графы не выдаём:
|
||||||
|
// их обновит обычный запрос, когда пользователь снова откроет соответствующую ветку.
|
||||||
|
export async function readExplorerCachedGraphs(scope, limit = 1000) {
|
||||||
|
const prefix = `${scope}|`;
|
||||||
|
const collected = new Map();
|
||||||
|
for (const row of memory.values()) {
|
||||||
|
if (row.key.startsWith(prefix) && row.savedAt <= Date.now() && Date.now() - row.savedAt < EXPLORER_CACHE_TTL_MS)
|
||||||
|
collected.set(row.key, row);
|
||||||
|
}
|
||||||
|
const db = await dbOpen();
|
||||||
|
if (!db) return [...collected.values()].slice(0, limit);
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const range = IDBKeyRange.bound(prefix, `${prefix}\uffff`);
|
||||||
|
const request = db.transaction(STORE, 'readonly').objectStore(STORE).openCursor(range);
|
||||||
|
request.onerror = () => resolve();
|
||||||
|
request.onsuccess = () => {
|
||||||
|
const cursor = request.result;
|
||||||
|
if (!cursor || collected.size >= limit) { resolve(); return; }
|
||||||
|
const row = cursor.value;
|
||||||
|
if (row?.savedAt <= Date.now() && Date.now() - row.savedAt < EXPLORER_CACHE_TTL_MS)
|
||||||
|
collected.set(row.key, row);
|
||||||
|
cursor.continue();
|
||||||
|
};
|
||||||
|
} catch { resolve(); }
|
||||||
|
});
|
||||||
|
return [...collected.values()].slice(0, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function explorerCacheScope(service, sessionLogin) {
|
||||||
|
return `${String(service?.serverUrl || '').trim().toLowerCase()}|${String(sessionLogin || '').trim()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getExplorerGraph(service, login, { scope, force = false } = {}) {
|
||||||
|
const key = `${scope || explorerCacheScope(service, '')}|${String(login || '').trim().toLowerCase()}`;
|
||||||
|
if (!login) throw new Error('LOGIN_REQUIRED');
|
||||||
|
const valid = (record) => record && record.graph && Date.now() - record.savedAt < EXPLORER_CACHE_TTL_MS && record.savedAt <= Date.now();
|
||||||
|
if (!force) {
|
||||||
|
const item = memory.get(key) || await read(key);
|
||||||
|
if (valid(item)) {
|
||||||
|
memory.set(key, item);
|
||||||
|
return item.graph;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (inflight.has(key)) return inflight.get(key);
|
||||||
|
const started = epoch;
|
||||||
|
const task = (async () => {
|
||||||
|
const graph = await service.getUserConnectionsGraph(login);
|
||||||
|
if (started !== epoch) throw new Error('EXPLORER_CACHE_INVALIDATED');
|
||||||
|
const record = { key, graph, savedAt: Date.now() };
|
||||||
|
memory.set(key, record);
|
||||||
|
// Ограничиваем горячий слой. Записи IndexedDB остаются до ручной очистки или перезаписи по TTL.
|
||||||
|
while (memory.size > 800) memory.delete(memory.keys().next().value);
|
||||||
|
await write(record);
|
||||||
|
return graph;
|
||||||
|
})();
|
||||||
|
inflight.set(key, task);
|
||||||
|
try { return await task; }
|
||||||
|
finally { if (inflight.get(key) === task) inflight.delete(key); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Модель V3 должна наследовать время фактического получения ответа, а не время
|
||||||
|
// очередного чтения его из IndexedDB: иначе повторные визиты продлевали бы TTL.
|
||||||
|
export function explorerGraphSavedAt(scope, login) {
|
||||||
|
const key = `${scope}|${String(login || '').trim().toLowerCase()}`;
|
||||||
|
return memory.get(key)?.savedAt || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function clearExplorerGraphCache() {
|
||||||
|
epoch += 1;
|
||||||
|
inflight.clear();
|
||||||
|
memory.clear();
|
||||||
|
const db = await dbOpen();
|
||||||
|
if (!db) return;
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const tx = db.transaction(STORE, 'readwrite');
|
||||||
|
tx.objectStore(STORE).clear();
|
||||||
|
tx.oncomplete = resolve;
|
||||||
|
tx.onerror = resolve;
|
||||||
|
tx.onabort = resolve;
|
||||||
|
} catch { resolve(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
// V3: исследованный (не ограниченный историей центров) граф и видимый BFS-срез.
|
||||||
|
// Храним исходящие дружеские связи с направлением; расстояние для карты считаем
|
||||||
|
// по неориентированному представлению только уже обнаруженных рёбер.
|
||||||
|
export const EXPLORER_MAX_DEPTH = 4;
|
||||||
|
export const EXPLORER_DEFAULT_DEPTH = 1;
|
||||||
|
export const keyOf = (value) => String(value || '').trim().toLowerCase();
|
||||||
|
|
||||||
|
const isFriend = (type) => type === 'friend' || type === 'close_friend';
|
||||||
|
|
||||||
|
function decorate(row, fallback) {
|
||||||
|
const login = String(row?.login || fallback || '').trim();
|
||||||
|
const avatar = row?.avatar?.ar || row?.avatar?.sha256Hex
|
||||||
|
? { ar: String(row.avatar.ar || ''), sha256Hex: String(row.avatar.sha256Hex || row.avatar.sha256 || '') }
|
||||||
|
: (row?.avatarTxId ? { ar: String(row.avatarTxId) } : null);
|
||||||
|
return {
|
||||||
|
login,
|
||||||
|
name: [row?.firstName, row?.lastName].filter(Boolean).join(' ').trim() || login,
|
||||||
|
avatar,
|
||||||
|
shining: row?.shine === true || row?.shine === 'true' || row?.shineStatus === 'shining',
|
||||||
|
official: row?.official === true || row?.official === 'true' || row?.accountRole === 'primary',
|
||||||
|
shineKnown: row?.shine !== undefined || row?.shineStatus !== undefined,
|
||||||
|
officialKnown: row?.official !== undefined || row?.accountRole !== undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createExplorerGraph() {
|
||||||
|
const graphs = new Map(); // известные полные исходящие списки
|
||||||
|
const people = new Map();
|
||||||
|
const edges = new Map(); // owner -> friend (направленные)
|
||||||
|
const updatedAt = new Map();
|
||||||
|
|
||||||
|
function remember(row, fallback) {
|
||||||
|
const data = decorate(row, fallback);
|
||||||
|
const id = keyOf(data.login);
|
||||||
|
if (!id) return;
|
||||||
|
const previous = people.get(id);
|
||||||
|
if (!previous) people.set(id, data);
|
||||||
|
else people.set(id, {
|
||||||
|
login: previous.login || data.login,
|
||||||
|
name: data.name && data.name !== data.login ? data.name : previous.name,
|
||||||
|
avatar: data.avatar || previous.avatar,
|
||||||
|
shining: data.shineKnown ? data.shining : previous.shining,
|
||||||
|
official: data.officialKnown ? data.official : previous.official,
|
||||||
|
shineKnown: previous.shineKnown || data.shineKnown,
|
||||||
|
officialKnown: previous.officialKnown || data.officialKnown,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function add(graph, fallbackLogin, savedAt = Date.now()) {
|
||||||
|
const login = String(graph?.login || fallbackLogin || '').trim();
|
||||||
|
const owner = keyOf(login);
|
||||||
|
if (!owner) return;
|
||||||
|
remember({ login }, login);
|
||||||
|
(Array.isArray(graph?.allUsers) ? graph.allUsers : []).forEach((row) => remember(row));
|
||||||
|
// Если граф обновился, старые исходящие рёбра этого владельца больше не действуют.
|
||||||
|
for (const edgeKey of edges.keys()) if (edgeKey.startsWith(`${owner}\u0000`)) edges.delete(edgeKey);
|
||||||
|
const close = new Set((graph?.outCloseFriends || []).map(keyOf));
|
||||||
|
const inbound = new Set([...(graph?.inFriends || []), ...(graph?.inCloseFriends || [])].map(keyOf));
|
||||||
|
// Сохраняем оригинальный регистр логина для серверного API (ключи графа
|
||||||
|
// нормализуем независимо, только для сопоставления вершин).
|
||||||
|
const friendNames = new Map();
|
||||||
|
for (const raw of [...(graph?.outFriends || []), ...(graph?.outCloseFriends || [])]) {
|
||||||
|
const id = keyOf(raw);
|
||||||
|
if (id && id !== owner && !friendNames.has(id)) friendNames.set(id, String(raw).trim());
|
||||||
|
}
|
||||||
|
const friends = new Set(friendNames.keys());
|
||||||
|
for (const id of friends) {
|
||||||
|
remember({ login: friendNames.get(id) }, id);
|
||||||
|
edges.set(`${owner}\u0000${id}`, {
|
||||||
|
from: owner, to: id, type: close.has(id) ? 'close_friend' : 'friend',
|
||||||
|
mutual: inbound.has(id),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
graphs.set(owner, { login, friends, friendLogins: [...friendNames.values()] });
|
||||||
|
updatedAt.set(owner, savedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clear() {
|
||||||
|
graphs.clear(); people.clear(); edges.clear(); updatedAt.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
function getFriends(login) {
|
||||||
|
return graphs.get(keyOf(login))?.friendLogins || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pruneExpired(now = Date.now()) {
|
||||||
|
for (const [id, savedAt] of updatedAt) {
|
||||||
|
if (savedAt <= now && now - savedAt < 24 * 60 * 60 * 1000) continue;
|
||||||
|
graphs.delete(id);
|
||||||
|
updatedAt.delete(id);
|
||||||
|
for (const edgeKey of edges.keys()) {
|
||||||
|
if (edgeKey.startsWith(`${id}\u0000`)) edges.delete(edgeKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function snapshot(centerLogin, { depth = EXPLORER_DEFAULT_DEPTH, x2 = false, close = false, shining = false } = {}) {
|
||||||
|
pruneExpired();
|
||||||
|
const center = keyOf(centerLogin);
|
||||||
|
if (!center) return { focusId: '', nodes: [], preserveHistory: true };
|
||||||
|
const radius = Math.max(0, Math.min(EXPLORER_MAX_DEPTH, Number(depth) || 0)) + (x2 ? 2 : 1);
|
||||||
|
const allowed = (id) => id === center || !shining || Boolean(people.get(id)?.shining);
|
||||||
|
const neighbors = new Map();
|
||||||
|
const eligibleEdges = [];
|
||||||
|
for (const edge of edges.values()) {
|
||||||
|
if (!isFriend(edge.type) || (close && edge.type !== 'close_friend')) continue;
|
||||||
|
if (!allowed(edge.from) || !allowed(edge.to)) continue;
|
||||||
|
eligibleEdges.push(edge);
|
||||||
|
if (!neighbors.has(edge.from)) neighbors.set(edge.from, new Set());
|
||||||
|
if (!neighbors.has(edge.to)) neighbors.set(edge.to, new Set());
|
||||||
|
neighbors.get(edge.from).add(edge.to);
|
||||||
|
neighbors.get(edge.to).add(edge.from);
|
||||||
|
}
|
||||||
|
const distances = new Map([[center, 0]]);
|
||||||
|
const queue = [center];
|
||||||
|
for (let i = 0; i < queue.length; i += 1) {
|
||||||
|
const from = queue[i];
|
||||||
|
const d = distances.get(from);
|
||||||
|
if (d >= radius) continue;
|
||||||
|
for (const to of neighbors.get(from) || []) {
|
||||||
|
if (distances.has(to)) continue;
|
||||||
|
distances.set(to, d + 1);
|
||||||
|
queue.push(to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Полностью раскрыт = его исходящий список известен, и ВСЕ разрешённые фильтрами
|
||||||
|
// друзья сейчас видимы. За границей глубины большой аватар становится маленьким.
|
||||||
|
const expanded = new Map();
|
||||||
|
const isExpanded = (id) => {
|
||||||
|
if (expanded.has(id)) return expanded.get(id);
|
||||||
|
const own = graphs.get(id);
|
||||||
|
if (!own) { expanded.set(id, false); return false; }
|
||||||
|
let complete = true;
|
||||||
|
for (const friend of own.friends) {
|
||||||
|
if (!allowed(friend)) continue;
|
||||||
|
if (close && edges.get(`${id}\u0000${friend}`)?.type !== 'close_friend') continue;
|
||||||
|
if (!distances.has(friend)) { complete = false; break; }
|
||||||
|
}
|
||||||
|
expanded.set(id, complete);
|
||||||
|
return complete;
|
||||||
|
};
|
||||||
|
|
||||||
|
const refs = new Map();
|
||||||
|
const edgePairs = new Set();
|
||||||
|
const immediateEdges = new Map();
|
||||||
|
for (const edge of eligibleEdges) {
|
||||||
|
if (!distances.has(edge.from) || !distances.has(edge.to)) continue;
|
||||||
|
if (!immediateEdges.has(edge.from)) immediateEdges.set(edge.from, edge);
|
||||||
|
if (!immediateEdges.has(edge.to)) immediateEdges.set(edge.to, edge);
|
||||||
|
const pair = [edge.from, edge.to].sort();
|
||||||
|
const pairKey = pair.join('\u0000');
|
||||||
|
if (edgePairs.has(pairKey)) continue;
|
||||||
|
edgePairs.add(pairKey);
|
||||||
|
// Линия одна на пару, направленность сохранена в исходном графе.
|
||||||
|
// Направленное ребро оставляем owner -> friend (не алфавитный порядок).
|
||||||
|
const child = edge.to;
|
||||||
|
const parent = edge.from;
|
||||||
|
const reverse = edges.get(`${edge.to}\u0000${edge.from}`);
|
||||||
|
// Периферийные маленькие пользователи не раскрывают собственные связи.
|
||||||
|
// Если оба конца сжаты из-за глубины, линия между ними не рисуется.
|
||||||
|
if (!isExpanded(edge.from) && !isExpanded(edge.to)) continue;
|
||||||
|
const detail = {
|
||||||
|
id: parent,
|
||||||
|
relationType: edge.type === 'close_friend' || reverse?.type === 'close_friend' ? 'close_friend' : 'friend',
|
||||||
|
mutual: Boolean(edge.mutual || reverse),
|
||||||
|
strength: edge.type === 'close_friend' ? 0.9 : 0.55,
|
||||||
|
};
|
||||||
|
if (!refs.has(child)) refs.set(child, []);
|
||||||
|
refs.get(child).push(detail);
|
||||||
|
}
|
||||||
|
const nodes = [...distances].map(([id, d]) => {
|
||||||
|
const person = people.get(id) || { login: id, name: id };
|
||||||
|
const ownEdge = immediateEdges.get(id);
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
login: person.login,
|
||||||
|
name: person.name,
|
||||||
|
avatar: person.avatar || null,
|
||||||
|
shining: Boolean(person.shining),
|
||||||
|
official: Boolean(person.official),
|
||||||
|
relationType: id === center ? 'self' : (ownEdge?.type || 'friend'),
|
||||||
|
mutual: Boolean(ownEdge?.mutual),
|
||||||
|
strength: ownEdge?.type === 'close_friend' ? 0.9 : 0.55,
|
||||||
|
distance: d,
|
||||||
|
tier: 1, // фиксированная карта; размер определяется visualSmall, НЕ tier.
|
||||||
|
visualSmall: !isExpanded(id),
|
||||||
|
edgeParents: refs.get(id) || [],
|
||||||
|
keepVisible: id === center,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return { focusId: center, nodes, preserveHistory: true, radius };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { add, clear, snapshot, getFriends, has: (login) => graphs.has(keyOf(login)),
|
||||||
|
isFresh: (login, now = Date.now()) => {
|
||||||
|
const saved = updatedAt.get(keyOf(login));
|
||||||
|
return saved != null && saved <= now && now - saved < 24 * 60 * 60 * 1000;
|
||||||
|
},
|
||||||
|
size: () => graphs.size };
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -265,7 +265,7 @@ function hash01(str) {
|
|||||||
* @param {Function} [opts.onGroupMoveEnd] - перемещение исторического кластера (nodes[]) => void
|
* @param {Function} [opts.onGroupMoveEnd] - перемещение исторического кластера (nodes[]) => void
|
||||||
* @returns {{ destroy: Function, recenter: Function, setModel: Function, getFocusNode: Function }}
|
* @returns {{ destroy: Function, recenter: Function, setModel: Function, getFocusNode: Function }}
|
||||||
*/
|
*/
|
||||||
export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeLongPress, onNodeMoveEnd, onGroupMoveEnd, onNodeHover, onDiveChange } = {}) {
|
export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeLongPress, onNodeMoveEnd, onGroupMoveEnd, onNodeHover, onDiveChange, explorerMode = false } = {}) {
|
||||||
// Слои DOM
|
// Слои DOM
|
||||||
const edgesSvg = document.createElementNS(SVGNS, 'svg');
|
const edgesSvg = document.createElementNS(SVGNS, 'svg');
|
||||||
edgesSvg.setAttribute('class', 'fg-edges');
|
edgesSvg.setAttribute('class', 'fg-edges');
|
||||||
@@ -458,7 +458,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
.filter((n) => String(n.id) !== fId && (Number(n.tier) || 1) === 1)
|
.filter((n) => String(n.id) !== fId && (Number(n.tier) || 1) === 1)
|
||||||
.sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0));
|
.sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0));
|
||||||
const deep = list.filter((n) => String(n.id) !== fId && (Number(n.tier) || 1) >= 2);
|
const deep = list.filter((n) => String(n.id) !== fId && (Number(n.tier) || 1) >= 2);
|
||||||
const dotCount = Math.max(0, tier1.length - MAX_FULL_NODES);
|
const dotCount = explorerMode ? 0 : Math.max(0, tier1.length - MAX_FULL_NODES);
|
||||||
if (dotCount > 0) {
|
if (dotCount > 0) {
|
||||||
console.info(t('screens.force_graph.text_008', { value1: tier1.length, value2: MAX_FULL_NODES, value3: dotCount }));
|
console.info(t('screens.force_graph.text_008', { value1: tier1.length, value2: MAX_FULL_NODES, value3: dotCount }));
|
||||||
}
|
}
|
||||||
@@ -472,7 +472,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
isFocus: false,
|
isFocus: false,
|
||||||
index: i,
|
index: i,
|
||||||
total: tier1.length,
|
total: tier1.length,
|
||||||
dotOnly: i >= MAX_FULL_NODES && !p.keepVisible,
|
dotOnly: !explorerMode && i >= MAX_FULL_NODES && !p.keepVisible,
|
||||||
orbit: p.fixedLayout ? null : tier1Orbit[i],
|
orbit: p.fixedLayout ? null : tier1Orbit[i],
|
||||||
}));
|
}));
|
||||||
// 3-й уровень рисуем точками (микрозвёзды), 2-й — маленькими аватарками
|
// 3-й уровень рисуем точками (микрозвёзды), 2-й — маленькими аватарками
|
||||||
@@ -498,7 +498,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
const targetR = fixedLayout ? Math.hypot(layoutX, layoutY) : (isFocus ? 0 : (orbit?.radius || ORBIT_FIRST_R));
|
const targetR = fixedLayout ? Math.hypot(layoutX, layoutY) : (isFocus ? 0 : (orbit?.radius || ORBIT_FIRST_R));
|
||||||
const angle = fixedLayout ? Math.atan2(layoutY, layoutX) : (isFocus ? 0 : (orbit?.angle ?? spreadAngle(index, total)));
|
const angle = fixedLayout ? Math.atan2(layoutY, layoutX) : (isFocus ? 0 : (orbit?.angle ?? spreadAngle(index, total)));
|
||||||
// масштаб/прозрачность по уровню глубины: 2-й — вдвое меньше и полупрозрачный, 3-й — микрозвезда.
|
// масштаб/прозрачность по уровню глубины: 2-й — вдвое меньше и полупрозрачный, 3-й — микрозвезда.
|
||||||
const scale = isFocus ? FOCUS_SCALE : (tier === 2 ? DEEP2_SCALE : (tier >= 3 ? 1 : PRIMARY_SCALE));
|
const scale = explorerMode ? (src.visualSmall ? 0.5 : 1) : (isFocus ? FOCUS_SCALE : (tier === 2 ? DEEP2_SCALE : (tier >= 3 ? 1 : PRIMARY_SCALE)));
|
||||||
const op = tier === 2 ? DEEP2_OPACITY : (tier >= 3 ? DEEP3_OPACITY : 1);
|
const op = tier === 2 ? DEEP2_OPACITY : (tier >= 3 ? DEEP3_OPACITY : 1);
|
||||||
const tx = fixedLayout ? layoutX : (isFocus ? 0 : Math.cos(angle) * targetR);
|
const tx = fixedLayout ? layoutX : (isFocus ? 0 : Math.cos(angle) * targetR);
|
||||||
const ty = fixedLayout ? layoutY : (isFocus ? 0 : Math.sin(angle) * targetR);
|
const ty = fixedLayout ? layoutY : (isFocus ? 0 : Math.sin(angle) * targetR);
|
||||||
@@ -698,8 +698,12 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
const tier1 = nodes.filter((n) => n.tier === 1 && !n.isFocus);
|
const tier1 = nodes.filter((n) => n.tier === 1 && !n.isFocus);
|
||||||
const rel = { family: t('screens.force_graph.text_001'), friend: t('screens.force_graph.text_002'), close_friend: t('screens.force_graph.text_003'), business: t('screens.force_graph.text_004'), contact: t('screens.force_graph.text_005') };
|
const rel = { family: t('screens.force_graph.text_001'), friend: t('screens.force_graph.text_002'), close_friend: t('screens.force_graph.text_003'), business: t('screens.force_graph.text_004'), contact: t('screens.force_graph.text_005') };
|
||||||
const items = tier1.map((n) => `<li>${escapeHtml(n.name || n.login || String(n.id))}${n.shining ? t('screens.force_graph.text_006') : ''} (${rel[n.relationType] || t('screens.force_graph.text_007')})</li>`).join('');
|
const items = tier1.map((n) => `<li>${escapeHtml(n.name || n.login || String(n.id))}${n.shining ? t('screens.force_graph.text_006') : ''} (${rel[n.relationType] || t('screens.force_graph.text_007')})</li>`).join('');
|
||||||
|
if (explorerMode) {
|
||||||
|
a11y.textContent = t('screens.network_explorer.a11y', { value1: focus?.name || focus?.login || '', value2: nodes.length - 1 });
|
||||||
|
} else {
|
||||||
a11y.innerHTML = `<p>Центр: ${escapeHtml(focus ? (focus.name || focus.login || '') : '')}. Связей 1-го уровня: ${tier1.length}.</p><ul>${items}</ul>`;
|
a11y.innerHTML = `<p>Центр: ${escapeHtml(focus ? (focus.name || focus.login || '') : '')}. Связей 1-го уровня: ${tier1.length}.</p><ul>${items}</ul>`;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
function escapeHtml(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); }
|
function escapeHtml(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); }
|
||||||
|
|
||||||
// Переиспользование узла при диффинге: сохраняем x/y/скорость, задаём новую роль и цель.
|
// Переиспользование узла при диффинге: сохраняем x/y/скорость, задаём новую роль и цель.
|
||||||
@@ -733,7 +737,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
node.orbitRing = spec.orbit?.ring || 0;
|
node.orbitRing = spec.orbit?.ring || 0;
|
||||||
node.tx = node.fixedLayout ? layoutX : Math.cos(node.angle) * node.targetR;
|
node.tx = node.fixedLayout ? layoutX : Math.cos(node.angle) * node.targetR;
|
||||||
node.ty = node.fixedLayout ? layoutY : Math.sin(node.angle) * node.targetR;
|
node.ty = node.fixedLayout ? layoutY : Math.sin(node.angle) * node.targetR;
|
||||||
node.targetScale = spec.isFocus ? FOCUS_SCALE : (tier === 2 ? DEEP2_SCALE : (tier >= 3 ? 1 : PRIMARY_SCALE));
|
node.targetScale = explorerMode ? (src.visualSmall ? 0.5 : 1) : (spec.isFocus ? FOCUS_SCALE : (tier === 2 ? DEEP2_SCALE : (tier >= 3 ? 1 : PRIMARY_SCALE)));
|
||||||
node.targetOpacity = tier === 2 ? DEEP2_OPACITY : (tier >= 3 ? DEEP3_OPACITY : 1);
|
node.targetOpacity = tier === 2 ? DEEP2_OPACITY : (tier >= 3 ? DEEP3_OPACITY : 1);
|
||||||
node.hidden = false;
|
node.hidden = false;
|
||||||
node.bloom = false;
|
node.bloom = false;
|
||||||
@@ -1307,13 +1311,13 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
target.ty = 0;
|
target.ty = 0;
|
||||||
target.vx = 0;
|
target.vx = 0;
|
||||||
target.vy = 0;
|
target.vy = 0;
|
||||||
to.set(target.id, { x: 0, y: 0, scale: FOCUS_SCALE });
|
to.set(target.id, { x: 0, y: 0, scale: explorerMode ? target.targetScale : FOCUS_SCALE });
|
||||||
|
|
||||||
applyOrbitTargets(peers);
|
applyOrbitTargets(peers);
|
||||||
peers.forEach((n) => {
|
peers.forEach((n) => {
|
||||||
n.vx = 0;
|
n.vx = 0;
|
||||||
n.vy = 0;
|
n.vy = 0;
|
||||||
const sc = n.tier >= 2 ? SECONDARY_SCALE : PRIMARY_SCALE;
|
const sc = explorerMode ? n.targetScale : (n.tier >= 2 ? SECONDARY_SCALE : PRIMARY_SCALE);
|
||||||
to.set(n.id, { x: n.tx, y: n.ty, scale: sc });
|
to.set(n.id, { x: n.tx, y: n.ty, scale: sc });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1403,12 +1407,12 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
};
|
};
|
||||||
|
|
||||||
const focus = nodes.find((n) => n.isFocus);
|
const focus = nodes.find((n) => n.isFocus);
|
||||||
if (focus) apply(focus, focus.tx || 0, focus.ty || 0, FOCUS_SCALE, 1);
|
if (focus) apply(focus, focus.tx || 0, focus.ty || 0, explorerMode ? focus.targetScale : FOCUS_SCALE, 1);
|
||||||
|
|
||||||
const fixedLayout = visiblePeers.some((n) => n.fixedLayout) || nodes.some((n) => n.fixedLayout);
|
const fixedLayout = visiblePeers.some((n) => n.fixedLayout) || nodes.some((n) => n.fixedLayout);
|
||||||
if (!fixedLayout) applyOrbitTargets(visiblePeers);
|
if (!fixedLayout) applyOrbitTargets(visiblePeers);
|
||||||
visiblePeers.forEach((n) => {
|
visiblePeers.forEach((n) => {
|
||||||
const sc = n.tier >= 2 ? SECONDARY_SCALE : PRIMARY_SCALE;
|
const sc = explorerMode ? n.targetScale : (n.tier >= 2 ? SECONDARY_SCALE : PRIMARY_SCALE);
|
||||||
apply(n, n.tx, n.ty, sc, 1);
|
apply(n, n.tx, n.ty, sc, 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1991,6 +1995,23 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
let node;
|
let node;
|
||||||
let isNew;
|
let isNew;
|
||||||
if (oldNode && oldNode.dotOnly === spec.dotOnly) {
|
if (oldNode && oldNode.dotOnly === spec.dotOnly) {
|
||||||
|
// V3 получает данные о фото/имени постепенно. Обновляем содержимое существующего
|
||||||
|
// узла при появлении нового аватара, не теряя его координаты и жесты.
|
||||||
|
if (explorerMode) {
|
||||||
|
const beforeAvatar = JSON.stringify(oldNode.avatar || null);
|
||||||
|
const afterAvatar = JSON.stringify(spec.src.avatar || null);
|
||||||
|
if (beforeAvatar !== afterAvatar && !oldNode.dotOnly) {
|
||||||
|
const replacement = buildNodeElement(spec.src, spec.isFocus, Number(spec.src.tier) || 1, false);
|
||||||
|
oldNode.el.replaceWith(replacement);
|
||||||
|
oldNode.el = replacement;
|
||||||
|
}
|
||||||
|
oldNode.avatar = spec.src.avatar || null;
|
||||||
|
oldNode.name = spec.src.name;
|
||||||
|
oldNode.login = spec.src.login;
|
||||||
|
oldNode.el.title = spec.src.name || spec.src.login || '';
|
||||||
|
const label = oldNode.el.querySelector('.fg-node-label');
|
||||||
|
if (label) label.textContent = spec.src.name || spec.src.login || '';
|
||||||
|
}
|
||||||
updateNodeRole(oldNode, spec); // непрерывность: тот же DOM, новая роль/орбита
|
updateNodeRole(oldNode, spec); // непрерывность: тот же DOM, новая роль/орбита
|
||||||
node = oldNode; isNew = false;
|
node = oldNode; isNew = false;
|
||||||
} else {
|
} else {
|
||||||
@@ -2015,7 +2036,7 @@ export function createForceGraph({ stage, model, onCenterTap, onNodeTap, onNodeL
|
|||||||
} else { fx = 0; fy = 0; fs = 0.3; fo = 0; } // первичная инициализация
|
} else { fx = 0; fy = 0; fs = 0.3; fo = 0; } // первичная инициализация
|
||||||
} else if (isNew) {
|
} else if (isNew) {
|
||||||
fx = Math.cos(node.angle) * 12; fy = Math.sin(node.angle) * 12; fs = 0.2; fo = 0; // из центрального круга
|
fx = Math.cos(node.angle) * 12; fy = Math.sin(node.angle) * 12; fs = 0.2; fo = 0; // из центрального круга
|
||||||
order += 1; delay = order * BLOOM_STAGGER; // каскад (волна)
|
order += 1; delay = Math.min(order, explorerMode ? 12 : 10000) * BLOOM_STAGGER; // каскад (волна)
|
||||||
} else {
|
} else {
|
||||||
fx = node.x; fy = node.y; fs = node.scale; fo = node.opacity; // непрерывность: с текущего места
|
fx = node.x; fy = node.y; fs = node.scale; fo = node.opacity; // непрерывность: с текущего места
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { t, th } from '../i18n/index.js';
|
import { t, th } from '../i18n/index.js';
|
||||||
import * as modernNetworkView from './network-view.js';
|
import * as modernNetworkView from './network-view.js';
|
||||||
import * as legacyNetworkView from './network-legacy/network-view.js';
|
import * as legacyNetworkView from './network-legacy/network-view.js';
|
||||||
|
import * as explorerNetworkView from './network-explorer/network-view.js';
|
||||||
|
|
||||||
const NETWORK_VERSION_STORAGE_KEY = 'shine.network.version';
|
const NETWORK_VERSION_STORAGE_KEY = 'shine.network.version';
|
||||||
const MODES = new Set(['legacy', 'modern']);
|
const MODES = new Set(['legacy', 'modern', 'explorer']);
|
||||||
|
|
||||||
export const pageMeta = modernNetworkView.pageMeta;
|
export const pageMeta = modernNetworkView.pageMeta;
|
||||||
|
|
||||||
@@ -34,6 +35,7 @@ function createModeSwitcher(mode, navigate) {
|
|||||||
select.innerHTML = `
|
select.innerHTML = `
|
||||||
<option value="legacy">${th('screens.network_version_switcher.text_002')}</option>
|
<option value="legacy">${th('screens.network_version_switcher.text_002')}</option>
|
||||||
<option value="modern">${th('screens.network_version_switcher.text_003')}</option>
|
<option value="modern">${th('screens.network_version_switcher.text_003')}</option>
|
||||||
|
<option value="explorer">${th('screens.network_version_switcher.text_005')}</option>
|
||||||
`;
|
`;
|
||||||
select.value = mode;
|
select.value = mode;
|
||||||
select.addEventListener('change', () => {
|
select.addEventListener('change', () => {
|
||||||
@@ -47,7 +49,7 @@ function createModeSwitcher(mode, navigate) {
|
|||||||
|
|
||||||
export function render(context = {}) {
|
export function render(context = {}) {
|
||||||
const mode = selectedMode();
|
const mode = selectedMode();
|
||||||
const implementation = mode === 'legacy' ? legacyNetworkView : modernNetworkView;
|
const implementation = mode === 'legacy' ? legacyNetworkView : (mode === 'explorer' ? explorerNetworkView : modernNetworkView);
|
||||||
const screen = implementation.render(context);
|
const screen = implementation.render(context);
|
||||||
screen.classList.add(`network-screen--${mode}`);
|
screen.classList.add(`network-screen--${mode}`);
|
||||||
|
|
||||||
|
|||||||
@@ -591,3 +591,26 @@
|
|||||||
border-color: transparent;
|
border-color: transparent;
|
||||||
box-shadow: 0 0 14px color-mix(in srgb, var(--rel-family) 40%, transparent);
|
box-shadow: 0 0 14px color-mix(in srgb, var(--rel-family) 40%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* V3 — только состояние загрузки; аватары/линии/панель принадлежат общему force-graph. */
|
||||||
|
.network-explorer__status {
|
||||||
|
position: absolute;
|
||||||
|
left: 50%;
|
||||||
|
bottom: 20px;
|
||||||
|
z-index: 10;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
max-width: min(88vw, 400px);
|
||||||
|
padding: 7px 13px;
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 999px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
background: var(--surface);
|
||||||
|
box-shadow: var(--shadow-sm);
|
||||||
|
font-size: 12px;
|
||||||
|
text-align: center;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.network-explorer__status[hidden] { display: none; }
|
||||||
|
|
||||||
|
/* В V3 центральный аватар имеет ровно тот же размер, что и раскрытые друзья. */
|
||||||
|
.network-explorer .fg-node.is-focus .node-dot { animation: none; }
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createExplorerGraph } from '../js/pages/network-explorer/graph-model.js';
|
||||||
|
import {
|
||||||
|
getExplorerGraph, clearExplorerGraphCache, readExplorerCachedGraphs,
|
||||||
|
EXPLORER_CACHE_TTL_MS, explorerGraphSavedAt,
|
||||||
|
} from '../js/pages/network-explorer/graph-cache.js';
|
||||||
|
|
||||||
|
function friends(login, links = [], close = [], inFriends = [], marked = []) {
|
||||||
|
return {
|
||||||
|
login, outFriends: links, outCloseFriends: close, inFriends,
|
||||||
|
allUsers: marked.map(([user, shine]) => ({ login: user, shine })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const find = (model, login) => model.nodes.find((node) => node.id === login);
|
||||||
|
|
||||||
|
test('V3: BFS, радиусы X2 + 0..4, переход в любую сторону без истории центров', () => {
|
||||||
|
const g = createExplorerGraph();
|
||||||
|
g.add(friends('a', ['b']));
|
||||||
|
g.add(friends('b', ['c']));
|
||||||
|
g.add(friends('c', ['d']));
|
||||||
|
g.add(friends('d', ['e']));
|
||||||
|
g.add(friends('e', ['f']));
|
||||||
|
g.add(friends('f', ['g']));
|
||||||
|
const zero = g.snapshot('a', { x2: true, depth: 0 });
|
||||||
|
assert.deepEqual(zero.nodes.map((n) => n.id), ['a', 'b', 'c']);
|
||||||
|
const one = g.snapshot('d', { x2: true, depth: 1 });
|
||||||
|
assert.deepEqual(one.nodes.map((n) => n.id), ['d', 'c', 'e', 'b', 'f', 'a', 'g']);
|
||||||
|
const two = g.snapshot('d', { x2: true, depth: 2 });
|
||||||
|
assert.equal(two.nodes.length, 7);
|
||||||
|
const back = g.snapshot('b', { x2: false, depth: 0 });
|
||||||
|
assert.deepEqual(back.nodes.map((n) => n.id), ['b', 'a', 'c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('V3: маленький при скрытом друге; раскрывается, когда все друзья видны', () => {
|
||||||
|
const g = createExplorerGraph();
|
||||||
|
g.add(friends('a', ['b']));
|
||||||
|
g.add(friends('b', ['c']));
|
||||||
|
g.add(friends('c', ['d']));
|
||||||
|
const shallow = g.snapshot('a', { x2: false, depth: 0 });
|
||||||
|
assert.equal(find(shallow, 'a').visualSmall, false);
|
||||||
|
assert.equal(find(shallow, 'b').visualSmall, true);
|
||||||
|
const deeper = g.snapshot('a', { x2: true, depth: 1 });
|
||||||
|
assert.equal(find(deeper, 'b').visualSmall, false);
|
||||||
|
assert.equal(find(deeper, 'c').visualSmall, false);
|
||||||
|
assert.equal(find(deeper, 'd').visualSmall, true); // список d пока не был загружен
|
||||||
|
assert.deepEqual(deeper.nodes.filter((n) => n.id === 'b').flatMap((n) => n.edgeParents).map((n) => n.id), ['a']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('V3: кратчайший путь через пересечение, без дубликатов; направление ребра', () => {
|
||||||
|
const g = createExplorerGraph();
|
||||||
|
g.add(friends('z', ['a', 'b']));
|
||||||
|
g.add(friends('a', ['z', 'b'], [], ['z']));
|
||||||
|
g.add(friends('b', ['c']));
|
||||||
|
g.add(friends('c', ['d']));
|
||||||
|
const m = g.snapshot('z', { x2: true, depth: 0 });
|
||||||
|
assert.equal(m.nodes.length, 4);
|
||||||
|
assert.equal(find(m, 'b').distance, 1);
|
||||||
|
assert.equal(find(m, 'c').distance, 2);
|
||||||
|
assert.ok(find(m, 'a').edgeParents.some((e) => e.id === 'z'));
|
||||||
|
assert.equal(m.nodes.length, new Set(m.nodes.map((n) => n.id)).size);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('V3: фильтры близкие/сияющие и полнота раскрытия', () => {
|
||||||
|
const g = createExplorerGraph();
|
||||||
|
g.add(friends('a', ['b'], ['c'], [], [['b', false], ['c', true]]));
|
||||||
|
g.add(friends('c', []));
|
||||||
|
const all = g.snapshot('a', { x2: false, depth: 0 });
|
||||||
|
assert.equal(all.nodes.length, 3);
|
||||||
|
assert.deepEqual(g.snapshot('a', { close: true, depth: 0 }).nodes.map((n) => n.id), ['a', 'c']);
|
||||||
|
const shiny = g.snapshot('a', { shining: true, depth: 0 });
|
||||||
|
assert.deepEqual(shiny.nodes.map((n) => n.id), ['a', 'c']);
|
||||||
|
assert.equal(find(shiny, 'a').visualSmall, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('V3: TTL 24h, ручная очистка, разделение серверов/аккаунтов и восстановление', async () => {
|
||||||
|
const clock = Date.now;
|
||||||
|
let now = 1_900_000_000_000;
|
||||||
|
Date.now = () => now;
|
||||||
|
try {
|
||||||
|
await clearExplorerGraphCache();
|
||||||
|
let count = 0;
|
||||||
|
const service = { serverUrl: 'wss://test', getUserConnectionsGraph: async (login) => ({ login, count: ++count }) };
|
||||||
|
const scope = 'wss://test|alice';
|
||||||
|
const scopeOther = 'wss://test|bob';
|
||||||
|
await getExplorerGraph(service, 'alice', { scope });
|
||||||
|
now += EXPLORER_CACHE_TTL_MS - 1;
|
||||||
|
await getExplorerGraph(service, 'alice', { scope });
|
||||||
|
assert.equal(count, 1);
|
||||||
|
assert.equal(explorerGraphSavedAt(scope, 'alice'), 1_900_000_000_000);
|
||||||
|
assert.equal((await readExplorerCachedGraphs(scope)).length, 1);
|
||||||
|
now += 1;
|
||||||
|
await getExplorerGraph(service, 'alice', { scope });
|
||||||
|
assert.equal(count, 2);
|
||||||
|
await getExplorerGraph(service, 'alice', { scope: scopeOther });
|
||||||
|
assert.equal(count, 3);
|
||||||
|
await clearExplorerGraphCache();
|
||||||
|
assert.equal((await readExplorerCachedGraphs(scope)).length, 0);
|
||||||
|
await getExplorerGraph(service, 'alice', { scope });
|
||||||
|
assert.equal(count, 4);
|
||||||
|
} finally { Date.now = clock; await clearExplorerGraphCache(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('V3: регистр логина для запросов, обновление списка и статуса сияния', () => {
|
||||||
|
const g = createExplorerGraph();
|
||||||
|
g.add(friends('Alice', ['BobUser', 'Carol'], [], [], [['BobUser', true]]));
|
||||||
|
assert.deepEqual(g.getFriends('ALICE'), ['BobUser', 'Carol']);
|
||||||
|
assert.equal(g.snapshot('Alice').nodes.find((n) => n.id === 'bobuser').shining, true);
|
||||||
|
g.add(friends('Alice', ['BobUser'], [], [], [['BobUser', false]]));
|
||||||
|
assert.deepEqual(g.getFriends('ALICE'), ['BobUser']);
|
||||||
|
assert.equal(g.snapshot('Alice').nodes.find((n) => n.id === 'bobuser').shining, false);
|
||||||
|
assert.equal(g.snapshot('Alice').nodes.some((n) => n.id === 'carol'), false);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user