Files
SHiNE-server/shine-UI/js/pages/network/graph-canvas.js
T
q 68eec2b28b Связи: подписи островов по месту, карта остаётся вписанной
- Подписи групп: на общем виде (людей не различить) – прямо на острове, как название
  района; когда люди видны – рядом с островом, чтобы их не закрывать.
- Пока карту не трогали, она остаётся вписанной целиком: догрузились знакомства, подписи
  или открылась чужая карта по ссылке – вписывается заново. Первое касание, масштаб или
  выбор человека это выключают. Раньше на чужой карте крайний остров уезжал за край экрана.
- Если групп нет совсем (связи не знакомы между собой, общих подписок нет, город никто не
  указал) – одна подсказка, почему доска пустая.
2026-10-13 14:16:44 +03:00

2648 lines
120 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Карта связей на canvas: точки-люди, нити-связи, перетаскивание, масштаб и панорама.
//
// Почему canvas, а не DOM: прежний движок держал на каждого человека DOM-узел с PNG-«стеклом»,
// SVG-фильтрами размытия и CSS-анимациями. Уже на 4 точках это грузило ноутбук, а карта должна
// выдерживать сотни людей. Здесь кадр – это пачка штрихов и drawImage готовых картинок, а кадры
// рисуются только пока что-то движется.
//
// Два слоя: нижний – сетка, кольца групп и аура сияющих (аура «дышит» и перерисовывается
// ~20 раз в секунду), верхний – нити, точки и подписи (только когда что-то изменилось).
// Мелкие на экране точки рисуются простыми кружками без картинок; подписи не налезают друг
// на друга – каждая занимает место, только если оно свободно.
//
// Раскладка считается сразу до конца (без живой физики) и проигрывается одной плавной
// анимацией. Знакомые между собой люди ставятся рядом на кольцах, поэтому нити между ними
// короткие, а не клубок через всю карту. Уже стоящие точки при добавлении новых не сдвигаются,
// перетащенные вручную остаются там, куда их положили.
//
// Раскладки: «по близости» – кольца близкие / друзья / контакты; «острова» – группы людей
// (компании по знакомствам, интересы по подпискам, города), их считает страница (communities.js).
// У острова – подложка по оболочке его людей, подпись (нажатие – карточка группы) и мостики
// к другим островам: сколько знакомств между группами. Отдельные нити между островами и
// «спицы» к центру видны только у выбранного человека – иначе вместо картины клубок.
//
// Модель: { focusId, nodes: [{ id, login, name, firstName, lastName, avatar, relationType,
// shining, official, tier, parentId, mark, hasNote }], edges: [{ a, b, type, mutual, tie }] }.
// tie – знакомство людей первого круга между собой (из их графов): рисуется в островах и у
// выбранного человека, а раскладке «по близости» подсказывает, кого ставить рядом.
import { buildAvatarInitials } from '../../components/avatar-image.js';
import { state } from '../../state.js';
import { buildArweaveDataUrl } from '../../services/arweave-file-service.js';
import { resolvePublicFileUrl } from '../../services/public-file-service.js';
import { ISLAND_COLORS, layoutIslands, tieWeight } from './communities.js';
const NODE_R = { focus: 30, 1: 22, 2: 15, 3: 11 };
const LABEL_FONT = { focus: 13, 1: 12, 2: 10.5, 3: 10 };
const ZOOM_MIN = 0.12;
const ZOOM_MAX = 3;
const FIT_ZOOM_MAX = 1.35; // небольшая карта не раздувается на весь экран
const MOVE_MS = 620; // перестройка раскладки
const FADE_MS = 260; // появление и исчезновение точек
const CAMERA_MS = 460;
const TAP_SLOP = 7; // px: дальше – уже движение, а не нажатие
const LONG_PRESS_MS = 320; // палец задержался на человеке – можно его перетаскивать
const DOUBLE_TAP_MS = 300;
const AURA_PERIOD_MS = 4200; // медленное «дыхание» ауры сияющих
const AURA_FRAME_MS = 50; // для одной только ауры хватает ~20 кадров в секунду
const EDGE_WIDTH = { family: 2.4, close_friend: 2.4, friend: 1.6, contact: 1.1 };
const GROUP_ORDER = ['family', 'close_friend', 'friend', 'contact'];
const GROUP_CAPTION = { 0: 'Близкие', 1: 'Друзья', 2: 'Контакты' };
const ISLAND_MODES = new Set(['companies', 'interests', 'cities']);
const HULL_PAD = 40; // подложка острова: от центра крайней точки до края
const MAX_LABEL_CHARS = 18;
const LOD_SCREEN_R = 7.5; // px: меньше – точка без картинки и инициалов
const SPRITE_BUILDS_PER_FRAME = 14;
const LABEL_GRID = 48; // px: ячейка сетки, по которой подписи ищут свободное место
const LABEL_FADE_MS = 200; // подписи проявляются, когда точки встали
function easeOutCubic(t) {
const x = 1 - t;
return 1 - x * x * x;
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
// Детерминированное число 0..1 по строке: раскладка не «прыгает» между открытиями экрана.
function hash01(text) {
let h = 2166136261;
const s = String(text || '');
for (let i = 0; i < s.length; i += 1) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return ((h >>> 0) % 100000) / 100000;
}
function nodeRadius(node, focusId) {
if (node.id === focusId) return NODE_R.focus;
return NODE_R[clamp(Number(node.tier) || 1, 1, 3)];
}
function groupOf(node) {
const type = String(node?.relationType || 'contact');
return GROUP_ORDER.includes(type) ? type : 'contact';
}
function compareByName(a, b) {
return String(a.name || a.login || a.id).localeCompare(String(b.name || b.login || b.id), 'ru');
}
function angleDiff(a, b) {
const d = Math.abs(a - b) % (Math.PI * 2);
return d > Math.PI ? Math.PI * 2 - d : d;
}
// --- Раскладка ------------------------------------------------------------------------------
// Кто с кем знаком среди первого круга: такие люди должны стоять рядом. Сообщества ищутся
// распространением меток (быстро и детерминированно), каждому сообществу – свой сектор.
// Без данных о знакомствах (карта ещё не раскрыта) возвращает null – порядок по имени.
export function communityAngles(firstLevel, nodes, edges, focusId, seed) {
const ids = new Set(firstLevel.map((node) => node.id));
const weights = new Map(); // id → Map(id → вес)
const link = (a, b, w) => {
if (a === b) return;
if (!weights.has(a)) weights.set(a, new Map());
if (!weights.has(b)) weights.set(b, new Map());
weights.get(a).set(b, (weights.get(a).get(b) || 0) + w);
weights.get(b).set(a, (weights.get(b).get(a) || 0) + w);
};
let total = 0;
const viaDeeper = new Map(); // человек второго круга → его знакомые из первого
for (const edge of edges) {
if (edge.a === focusId || edge.b === focusId) continue;
const inA = ids.has(edge.a);
const inB = ids.has(edge.b);
if (inA && inB) { link(edge.a, edge.b, 1); total += 1; }
else if (inA || inB) {
const deep = inA ? edge.b : edge.a;
if (!viaDeeper.has(deep)) viaDeeper.set(deep, []);
viaDeeper.get(deep).push(inA ? edge.a : edge.b);
}
}
// Общий знакомый из второго круга тоже сближает (слабее прямой связи).
for (const list of viaDeeper.values()) {
if (list.length < 2 || list.length > 6) continue;
for (let i = 0; i < list.length; i += 1) {
for (let j = i + 1; j < list.length; j += 1) { link(list[i], list[j], 1 / list.length); total += 0.5; }
}
}
if (total < 3) return null;
const order = [...firstLevel].sort((a, b) => (a.id < b.id ? -1 : 1));
const label = new Map(order.map((node) => [node.id, node.id]));
for (let iter = 0; iter < 14; iter += 1) {
let changed = false;
for (const node of order) {
const near = weights.get(node.id);
if (!near) continue;
const score = new Map();
near.forEach((w, other) => {
const l = label.get(other);
score.set(l, (score.get(l) || 0) + w);
});
let best = label.get(node.id);
let bestScore = score.get(best) || 0;
score.forEach((s, l) => {
if (s > bestScore + 1e-9 || (Math.abs(s - bestScore) < 1e-9 && l < best)) { best = l; bestScore = s; }
});
if (best !== label.get(node.id)) { label.set(node.id, best); changed = true; }
}
if (!changed) break;
}
const groups = new Map();
for (const node of order) {
const l = label.get(node.id);
if (!groups.has(l)) groups.set(l, []);
groups.get(l).push(node);
}
const rest = [];
const communities = [];
groups.forEach((members) => {
if (members.length < 2) rest.push(...members);
else communities.push(members);
});
if (!communities.length) return null;
// Соседние сектора – у самых связанных между собой сообществ.
const between = (a, b) => {
let sum = 0;
const inB = new Set(b.map((node) => node.id));
for (const node of a) weights.get(node.id)?.forEach((w, other) => { if (inB.has(other)) sum += w; });
return sum;
};
communities.sort((a, b) => b.length - a.length || (a[0].id < b[0].id ? -1 : 1));
const placed = [communities.shift()];
while (communities.length) {
const last = placed[placed.length - 1];
let bestIndex = 0;
let bestScore = -1;
communities.forEach((c, i) => {
const s = between(last, c) / Math.sqrt(c.length);
if (s > bestScore + 1e-9) { bestScore = s; bestIndex = i; }
});
placed.push(communities.splice(bestIndex, 1)[0]);
}
if (rest.length) placed.push(rest);
const angles = new Map();
const count = firstLevel.length;
let start = -Math.PI / 2 + (hash01(`${seed}|communities`) - 0.5) * 0.4;
for (const members of placed) {
const span = (Math.PI * 2 * members.length) / count;
[...members].sort(compareByName).forEach((node, i) => {
angles.set(node.id, start + (span * (i + 0.5)) / members.length);
});
start += span;
}
return angles;
}
// Места на кольце вокруг желаемых углов: люди стоят как можно ближе к своему углу, но не
// ближе minGap друг к другу. Плотные группы раздвигаются блоком (как подписи на оси).
function packAngles(items, minGap) {
const out = new Map();
const n = items.length;
if (!n) return out;
const TAU = Math.PI * 2;
const norm = (a) => ((a % TAU) + TAU) % TAU;
const sorted = items.map((item) => ({ id: item.id, a: norm(item.pref) })).sort((x, y) => x.a - y.a || (x.id < y.id ? -1 : 1));
if (n * minGap >= TAU * 0.98) {
// Кольцо заполнено – ровный шаг с лучшим поворотом.
const step = TAU / n;
let best = 0;
let bestCost = Infinity;
for (let c = 0; c < n; c += 1) {
const phase = sorted[c].a - c * step;
let cost = 0;
for (let i = 0; i < n; i += 1) cost += angleDiff(sorted[i].a, phase + i * step);
if (cost < bestCost) { bestCost = cost; best = phase; }
}
sorted.forEach((item, i) => out.set(item.id, best + i * step));
return out;
}
// Разрезаем круг по самому большому промежутку и раскладываем на прямой.
let cut = 0;
let widest = -1;
for (let i = 0; i < n; i += 1) {
const next = i + 1 < n ? sorted[i + 1].a : sorted[0].a + TAU;
if (next - sorted[i].a > widest) { widest = next - sorted[i].a; cut = (i + 1) % n; }
}
const line = [];
for (let i = 0; i < n; i += 1) {
const item = sorted[(cut + i) % n];
line.push({ id: item.id, a: item.a + ((cut + i) >= n ? TAU : 0) });
}
// Блоки: у каждого центр = среднее желаемых углов, шаг minGap; пересекающиеся сливаются.
const blocks = [];
for (const item of line) {
blocks.push({ items: [item], sum: item.a });
for (;;) {
if (blocks.length < 2) break;
const b = blocks[blocks.length - 1];
const a = blocks[blocks.length - 2];
const aEnd = a.sum / a.items.length + ((a.items.length - 1) / 2) * minGap;
const bStart = b.sum / b.items.length - ((b.items.length - 1) / 2) * minGap;
if (aEnd + minGap <= bStart + 1e-9) break;
blocks.splice(blocks.length - 2, 2, { items: [...a.items, ...b.items], sum: a.sum + b.sum });
}
}
for (const block of blocks) {
const center = block.sum / block.items.length;
block.items.forEach((item, i) => out.set(item.id, center + (i - (block.items.length - 1) / 2) * minGap));
}
return out;
}
// Раскладывает людей по кольцам. Группа на нескольких кольцах заполняет их вперемешку по
// углу: сообщество занимает свой сектор на всех кольцах сразу, а не одно кольцо целиком.
// С желаемыми углами (preferred) каждый стоит как можно ближе к своему углу.
function fillRings(members, radii, out, stretch, preferred, seed, ringIndex) {
const total = members.length;
const capacity = radii.map((r) => Math.max(3, Math.floor((Math.PI * 2 * r) / 74)));
const counts = [];
let left = total;
for (const cap of capacity) {
const n = Math.min(cap, left);
counts.push(n);
left -= n;
}
const sorted = [...members];
if (preferred) sorted.sort((a, b) => (preferred.get(a.id) ?? 0) - (preferred.get(b.id) ?? 0) || compareByName(a, b));
else sorted.sort(compareByName);
const buckets = counts.map(() => []);
const taken = counts.map(() => 0);
sorted.forEach((node, i) => {
let best = 0;
let bestLag = -Infinity;
counts.forEach((n, k) => {
if (taken[k] >= n) return;
const lag = ((i + 1) * n) / total - taken[k];
if (lag > bestLag) { bestLag = lag; best = k; }
});
buckets[best].push(node);
taken[best] += 1;
});
buckets.forEach((ring, k) => {
const n = ring.length;
if (!n) return;
let angles;
if (preferred) {
angles = packAngles(ring.map((node) => ({ id: node.id, pref: preferred.get(node.id) ?? 0 })), (Math.PI * 2) / capacity[k]);
} else {
const step = (Math.PI * 2) / n;
const phase = hash01(`${seed}|ring${ringIndex + k}`) * Math.PI * 2;
angles = new Map(ring.map((node, i) => [node.id, phase + i * step]));
}
ring.forEach((node) => {
const angle = angles.get(node.id);
out.set(node.id, { x: Math.cos(angle) * radii[k] * stretch.x, y: Math.sin(angle) * radii[k] * stretch.y });
});
});
return counts.filter((n) => n > 0).length;
}
// Кольца подряд от radius наружу, пока все не поместятся.
function ringRadii(count, radius) {
const radii = [];
let room = 0;
let r = radius;
while (room < count) {
radii.push(r);
room += Math.max(3, Math.floor((Math.PI * 2 * r) / 74));
r += 64;
}
return radii;
}
// Первый круг «по близости»: семья и близкие ближе всех, дальше друзья, снаружи контакты.
// Семья и близкие друзья – один «близкий круг» и делят кольцо.
const RING_BAND = { family: 0, close_friend: 0, friend: 1, contact: 2 };
function placeRings(list, out, seed, stretch, preferred) {
const bands = [];
let radius = 100;
let ringIndex = 0;
for (const band of [0, 1, 2]) {
const members = list.filter((node) => RING_BAND[groupOf(node)] === band);
if (!members.length) continue;
const radii = ringRadii(members.length, radius);
const used = fillRings(members, radii, out, stretch, preferred, seed, ringIndex);
ringIndex += used;
radius = radii[radii.length - 1] + 64;
bands.push({ key: band, caption: GROUP_CAPTION[band], count: members.length, from: radii[0], to: radii[used - 1] });
}
return bands;
}
// Друзья друзей – веером «наружу» от того, через кого они пришли.
function placeChildren(parentPos, awayAngle, children, out, seed) {
const ordered = [...children].sort(compareByName);
let radius = 78;
let placed = 0;
let row = 0;
while (placed < ordered.length) {
const spread = clamp(ordered.length * 0.5, Math.PI / 3, Math.PI * 1.25);
const capacity = Math.max(2, Math.floor((spread * radius) / 46));
const count = Math.min(capacity, ordered.length - placed);
const jitter = (hash01(`${seed}|${row}`) - 0.5) * 0.2;
for (let i = 0; i < count; i += 1) {
const t = count === 1 ? 0.5 : i / (count - 1);
const a = awayAngle + jitter + (t - 0.5) * spread * (count === 1 ? 0 : 1);
out.set(ordered[placed + i].id, { x: parentPos.x + Math.cos(a) * radius, y: parentPos.y + Math.sin(a) * radius });
}
placed += count;
radius += 46;
row += 1;
}
}
// Раздвигает пересечения (с запасом под подписи) только у свободных точек и тянет их обратно
// к исходному месту, чтобы общая форма раскладки сохранилась. Соседей ищет по сетке, поэтому
// на сотнях точек это миллисекунды, а не сотни миллисекунд.
function relaxOverlaps(items, anchors) {
const CELL = 2 * NODE_R.focus + 30;
for (let iter = 0; iter < 90; iter += 1) {
const grid = new Map();
items.forEach((item, index) => {
const key = `${Math.floor(item.p.x / CELL)}|${Math.floor(item.p.y / CELL)}`;
if (!grid.has(key)) grid.set(key, []);
grid.get(key).push(index);
});
let moved = false;
items.forEach((a, i) => {
if (!a.free) return;
const cx = Math.floor(a.p.x / CELL);
const cy = Math.floor(a.p.y / CELL);
for (let gx = cx - 1; gx <= cx + 1; gx += 1) {
for (let gy = cy - 1; gy <= cy + 1; gy += 1) {
const cell = grid.get(`${gx}|${gy}`);
if (!cell) continue;
for (const j of cell) {
const b = items[j];
if (j === i || (b.free && j < i)) continue;
const minD = a.r + b.r + 30;
let dx = b.p.x - a.p.x;
let dy = b.p.y - a.p.y;
let d = Math.hypot(dx, dy);
if (d >= minD) continue;
if (d < 0.01) {
const angle = hash01(`${a.id}|${b.id}`) * Math.PI * 2;
dx = Math.cos(angle); dy = Math.sin(angle); d = 1;
}
const push = (minD - d) / d;
if (b.free) {
a.p.x -= dx * push * 0.5; a.p.y -= dy * push * 0.5;
b.p.x += dx * push * 0.5; b.p.y += dy * push * 0.5;
} else {
a.p.x -= dx * push; a.p.y -= dy * push;
}
moved = true;
}
}
}
});
for (const item of items) {
if (!item.free) continue;
const anchor = anchors.get(item.id);
item.p.x += (anchor.x - item.p.x) * 0.04;
item.p.y += (anchor.y - item.p.y) * 0.04;
}
if (!moved && iter > 4) break;
}
}
/**
* Считает итоговые координаты. focus всегда в (0, 0).
* fixed – точки, которые нельзя двигать (ручные и уже стоящие на карте).
* stretch – растяжение колец под форму экрана ({ x, y }, на телефоне карта выше, чем шире).
* Возвращает Map id → {x, y}; в поле guides – подписи групп для фона (кольца или сектора).
*/
// Первый круг островами. Свободные точки встают по раскладке островов; если часть людей
// острова уже стоит (своя раскладка, добавление без перестройки), новые встают рядом с ними:
// весь остров сдвигается туда, где его уже поставили.
function placeIslands(allFirst, pos, locked, edges, groups, stretch) {
const firstIds = new Set(allFirst.map((node) => node.id));
const seen = new Set();
const list = [];
for (const group of groups) {
const members = (group.members || []).filter((id) => firstIds.has(id) && !seen.has(id));
members.forEach((id) => seen.add(id));
if (members.length) list.push({ ...group, members });
}
// Кого страница не отнесла ни к одной группе (появился только что) – к остальным.
const orphans = allFirst.filter((node) => !seen.has(node.id)).map((node) => node.id);
if (orphans.length) {
const rest = list.find((group) => group.kind === 'rest');
if (rest) rest.members.push(...orphans);
else list.push({ id: 'rest', kind: 'rest', caption: '', color: -1, members: orphans });
}
const guides = {
kind: 'islands',
stretch,
items: list.map((group) => ({
key: group.id,
kind: group.kind,
caption: String(group.caption || ''),
short: String(group.short || group.caption || ''),
color: Number.isInteger(group.color) ? group.color : -1,
members: group.members,
count: group.members.length,
})),
};
// Все уже стоят (обновление без перестройки, своя раскладка) – раскладку не пересчитываем.
if (list.every((group) => group.members.every((id) => locked.has(id)))) return guides;
const weights = new Map();
for (const edge of edges) {
if (!firstIds.has(edge.a) || !firstIds.has(edge.b)) continue;
const w = tieWeight(edge.type, edge.mutual !== false);
for (const [a, b] of [[edge.a, edge.b], [edge.b, edge.a]]) {
if (!weights.has(a)) weights.set(a, new Map());
weights.get(a).set(b, Math.max(weights.get(a).get(b) || 0, w));
}
}
const rankById = new Map(allFirst.map((node) => [node.id, RING_BAND[groupOf(node)] ?? 2]));
const { positions } = layoutIslands({
groups: list, weights, rankOf: (id) => rankById.get(id) ?? 2, focusRadius: NODE_R.focus + 96, stretch,
});
for (const group of list) {
const fixedHere = group.members.filter((id) => locked.has(id) && positions.has(id));
let dx = 0;
let dy = 0;
if (fixedHere.length) {
for (const id of fixedHere) {
dx += pos.get(id).x - positions.get(id).x;
dy += pos.get(id).y - positions.get(id).y;
}
dx /= fixedHere.length;
dy /= fixedHere.length;
}
for (const id of group.members) {
if (locked.has(id) || !positions.has(id)) continue;
const p = positions.get(id);
pos.set(id, { x: p.x + dx, y: p.y + dy });
}
}
return guides;
}
export function computeLayout({ focusId, nodes, edges, fixed = new Map(), mode = 'rings', stretch = { x: 1, y: 1 }, groups = null }) {
const pos = new Map();
const locked = new Set();
const byId = new Map(nodes.map((node) => [node.id, node]));
pos.set(focusId, { x: 0, y: 0 });
locked.add(focusId);
for (const [id, point] of fixed) {
if (id === focusId || !byId.has(id)) continue;
pos.set(id, { x: point.x, y: point.y });
locked.add(id);
}
const neighbours = new Map();
for (const edge of edges) {
if (!neighbours.has(edge.a)) neighbours.set(edge.a, []);
if (!neighbours.has(edge.b)) neighbours.set(edge.b, []);
neighbours.get(edge.a).push(edge.b);
neighbours.get(edge.b).push(edge.a);
}
const allFirst = nodes.filter((node) => node.id !== focusId && (Number(node.tier) || 1) <= 1);
const firstLevel = allFirst.filter((node) => !pos.has(node.id));
let guides = null;
if (ISLAND_MODES.has(mode) && Array.isArray(groups) && groups.length && allFirst.length) {
guides = placeIslands(allFirst, pos, locked, edges, groups, stretch);
} else {
const preferred = communityAngles(allFirst, nodes, edges, focusId, focusId);
const place = (members, out) => ({ kind: 'rings', stretch, items: placeRings(members, out, focusId, stretch, preferred) });
const ringSlots = new Map();
// Все уже на своих местах (своя раскладка) – подписи групп как у базовой раскладки.
if (firstLevel.length) guides = place(firstLevel, ringSlots);
else if (allFirst.length) guides = place(allFirst, new Map());
ringSlots.forEach((point, id) => pos.set(id, point));
}
// Второй круг (друзья друзей) – на внешней орбите, у угла тех, через кого пришли:
// внутри колец им нет места, а вперемешку с первым кругом получался клубок.
const second = nodes.filter((node) => node.id !== focusId && (Number(node.tier) || 1) === 2 && !pos.has(node.id));
if (second.length) {
const flat = (p) => ({ x: p.x / stretch.x, y: p.y / stretch.y });
let outer = 0;
for (const node of allFirst) {
const p = pos.get(node.id);
if (p) outer = Math.max(outer, Math.hypot(flat(p).x, flat(p).y));
}
const prefs = new Map();
for (const node of second) {
const ids = (neighbours.get(node.id) || []).filter((id) => id !== focusId && pos.has(id) && (Number(byId.get(id)?.tier) || 1) <= 1);
if (node.parentId && pos.has(node.parentId) && !ids.includes(node.parentId)) ids.push(node.parentId);
let sx = 0;
let sy = 0;
for (const id of ids) {
const p = flat(pos.get(id));
const len = Math.hypot(p.x, p.y) || 1;
sx += p.x / len;
sy += p.y / len;
}
prefs.set(node.id, sx || sy ? Math.atan2(sy, sx) : hash01(node.id) * Math.PI * 2);
}
const radii = ringRadii(second.length, Math.max(outer, 100) + 96);
fillRings(second, radii, pos, stretch, prefs, focusId, 100);
if (guides?.kind === 'rings') {
guides.items.push({ key: 'fof', caption: 'Друзья друзей', count: second.length, from: radii[0], to: radii[radii.length - 1] });
}
}
// Глубже – по уровням, чтобы родитель всегда был размещён раньше детей.
const deeper = nodes.filter((node) => node.id !== focusId && (Number(node.tier) || 1) > 1 && !pos.has(node.id))
.sort((a, b) => (Number(a.tier) || 1) - (Number(b.tier) || 1));
const tiers = [...new Set(deeper.map((node) => Number(node.tier) || 2))];
for (const tier of tiers) {
const byParent = new Map();
for (const node of deeper.filter((row) => (Number(row.tier) || 2) === tier)) {
let parentId = node.parentId && pos.has(node.parentId) ? node.parentId : '';
if (!parentId) parentId = (neighbours.get(node.id) || []).find((id) => pos.has(id) && (Number(byId.get(id)?.tier) || 1) < tier) || focusId;
if (!byParent.has(parentId)) byParent.set(parentId, []);
byParent.get(parentId).push(node);
}
for (const [parentId, children] of byParent) {
const parentPos = pos.get(parentId) || { x: 0, y: 0 };
const parentNode = byId.get(parentId);
const grandId = parentNode?.parentId && pos.has(parentNode.parentId) ? parentNode.parentId : focusId;
const grandPos = pos.get(grandId) || { x: 0, y: 0 };
let away = Math.atan2(parentPos.y - grandPos.y, parentPos.x - grandPos.x);
if (parentId === focusId || (parentPos.x === grandPos.x && parentPos.y === grandPos.y)) away = hash01(parentId) * Math.PI * 2;
placeChildren(parentPos, away, children, pos, `${focusId}|${parentId}`);
}
}
const free = nodes.filter((node) => !locked.has(node.id) && pos.has(node.id));
if (free.length) {
const anchors = new Map(free.map((node) => [node.id, { ...pos.get(node.id) }]));
const items = nodes.filter((node) => pos.has(node.id)).map((node) => ({
id: node.id,
r: nodeRadius(node, focusId),
p: pos.get(node.id),
free: !locked.has(node.id),
}));
relaxOverlaps(items, anchors);
}
pos.guides = guides;
return pos;
}
// --- Аватарки -------------------------------------------------------------------------------
// Общий на всё приложение кэш картинок: повторный заход на экран не качает их заново.
const imageCache = new Map();
function loadImage(url) {
if (!url) return null;
let entry = imageCache.get(url);
if (!entry) {
entry = { img: new Image(), ready: false, failed: false, waiters: new Set() };
entry.img.decoding = 'async';
entry.img.onload = () => { entry.ready = true; entry.waiters.forEach((fn) => fn()); entry.waiters.clear(); };
entry.img.onerror = () => { entry.failed = true; entry.waiters.clear(); };
entry.img.src = url;
imageCache.set(url, entry);
}
return entry;
}
function avatarUrlSync(node) {
const raw = node?.avatar;
if (!raw) return '';
if (typeof raw === 'string') return raw.trim();
const txId = String(raw.ar || '').trim();
if (!txId) return '';
try {
return buildArweaveDataUrl({ gateway: state?.entrySettings?.arweaveServer, txId });
} catch {
return '';
}
}
async function avatarUrlFromServer(node) {
const raw = node?.avatar;
if (!raw || typeof raw !== 'object') return '';
const sha256 = String(raw.sha256Hex || raw.sha256 || '').trim().toLowerCase();
const authorLogin = String(node?.login || node?.id || '').trim();
if (String(raw.ar || '').trim() || !sha256 || !authorLogin) return '';
try {
return await resolvePublicFileUrl({
sha256,
authorLogin,
solanaEndpoint: state?.entrySettings?.solanaServer,
fallbackServerLogin: state?.entrySettings?.shineServerLogin,
});
} catch {
return '';
}
}
// --- Цвета из темы --------------------------------------------------------------------------
function parseRgb(text) {
const m = String(text || '').match(/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/);
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : [128, 128, 128];
}
function rgba(rgb, alpha) {
return `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, ${alpha})`;
}
function mix(a, b, t) {
return [0, 1, 2].map((i) => Math.round(a[i] + (b[i] - a[i]) * t));
}
function luminance(rgb) {
return (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255;
}
// --- Движок ---------------------------------------------------------------------------------
/**
* @param {Object} opts
* @param {HTMLElement} opts.stage – контейнер, в который ляжет canvas (на всю его площадь)
* @param {Function} [opts.onSelect] – (node | null) выбор точки или нажатие мимо
* @param {Function} [opts.onNodeMoved] – (node, {x, y}) точку перетащили; координаты относительно центра
* @param {Function} [opts.getInsets] – () => ({ top, bottom }) экранные поля, занятые панелями поверх карты
*/
// Цвета подложек островов – токены --net-island-N (styles/network-graph.css), здесь – запасные
// значения на случай, если токен не прочитался.
const ISLAND_RGB = {
dark: [[168, 145, 255], [86, 178, 255], [255, 190, 86], [255, 122, 152], [74, 208, 190], [255, 150, 96], [132, 144, 255], [236, 132, 218]],
light: [[106, 76, 214], [22, 118, 206], [176, 120, 0], [204, 58, 100], [0, 140, 122], [210, 96, 30], [66, 78, 206], [180, 58, 160]],
};
// Выпуклая оболочка (против часовой в координатах карты) – для подложки острова.
function convexHull(points) {
const pts = points.slice().sort((a, b) => a.x - b.x || a.y - b.y);
const unique = pts.filter((p, i) => i === 0 || p.x !== pts[i - 1].x || p.y !== pts[i - 1].y);
if (unique.length <= 2) return unique;
const cross = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower = [];
for (const p of unique) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
lower.push(p);
}
const upper = [];
for (let i = unique.length - 1; i >= 0; i -= 1) {
const p = unique[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
upper.push(p);
}
upper.pop();
lower.pop();
return lower.concat(upper);
}
// Оболочка с отступом pad и скруглёнными углами: дуга у каждой вершины между нормалями
// соседних сторон. Одна точка – круг, две – «капсула».
function traceHull(c, hull, pad) {
if (hull.length === 1) {
c.moveTo(hull[0].x + pad, hull[0].y);
c.arc(hull[0].x, hull[0].y, pad, 0, Math.PI * 2);
return;
}
const n = hull.length;
for (let i = 0; i < n; i += 1) {
const p = hull[i];
const prev = hull[(i - 1 + n) % n];
const next = hull[(i + 1) % n];
const a1 = Math.atan2(p.y - prev.y, p.x - prev.x) - Math.PI / 2;
const a2 = Math.atan2(next.y - p.y, next.x - p.x) - Math.PI / 2;
c.arc(p.x, p.y, pad, a1, a2, false);
}
c.closePath();
}
export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect, getInsets, getObstacles } = {}) {
const backCanvas = document.createElement('canvas');
backCanvas.className = 'net-canvas net-canvas--back';
backCanvas.setAttribute('aria-hidden', 'true');
const canvas = document.createElement('canvas');
canvas.className = 'net-canvas';
canvas.setAttribute('aria-hidden', 'true');
const bctx = backCanvas.getContext('2d');
const ctx = canvas.getContext('2d');
const probe = document.createElement('span');
probe.className = 'net-color-probe';
stage.append(backCanvas, canvas, probe);
let width = 0;
let height = 0;
let dpr = 1;
let destroyed = false;
let focusId = '';
let nodes = new Map(); // id → состояние точки
let leaving = []; // точки, которые плавно исчезают
let edges = [];
let guides = null; // подписи групп на фоне
let selectedId = '';
let hoverId = '';
let filterPred = null;
// Острова: чей человек, сколько знакомств между островами, выбранный остров и тот, над
// которым сейчас держат перетаскиваемого (туда его можно перенести).
let groupOfNode = new Map();
let crossCounts = new Map(); // 'a|b' (a < b) → число знакомств
let selectedGroup = '';
let focusSet = null; // кто остаётся ярким при выборе группы или интереса (null – никто не выделен)
let groupDim = 0;
let dropGroup = '';
let selectedGroupIsFocus = false; // подсвечены ровно люди выбранного острова (без колец)
let captionHits = []; // где на экране подписи островов: { id, x, y, w, h }
let islandGeo = new Map(); // id острова → { hull, cx, cy, r, top } по текущим точкам
let colors = null;
let fontFamily = 'sans-serif';
let labelsDrawn = 0;
const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)');
const camera = { x: 0, y: 0, zoom: 1 };
let cameraTween = null;
let inertia = null;
let moveTween = null; // общая анимация перестройки: { t0, dur }
let rafId = 0;
let lastBackAt = 0;
let selectDim = 0; // 0..1: насколько приглушены остальные при выбранной точке
let pendingFit = false;
let dirty = true; // верхний слой надо перерисовать
let backDirty = true; // нижний слой надо перерисовать
let lastFrameBusy = false;
let labelsShownAt = 0; // когда точки встали: подписи проявляются после этого
// Карта вписана целиком и человек её ещё не трогал: догрузки (знакомства, подписи, панели)
// вписывают её заново. Первое касание, масштаб или выбор это выключают.
let autoFit = false;
// ---- цвета -------------------------------------------------------------------------------
function readColor(token, fallback) {
probe.style.color = fallback;
probe.style.color = `var(${token}, ${fallback})`;
return parseRgb(getComputedStyle(probe).color);
}
// Цвета читаются только у встроенного в страницу элемента: до этого computed style пуст.
function refreshColors() {
if (!probe.isConnected) {
colors = null;
requestDraw();
return;
}
const background = readColor('--background', '#121419');
const dark = luminance(background) < 0.5;
const surface = readColor('--surface', '#1c1f27');
const edge = {
family: dark ? [255, 138, 101] : [194, 80, 42],
close_friend: readColor('--rel-family', '#f0b82e'),
friend: readColor('--info', '#a8c9f3'),
contact: readColor('--text-secondary', '#a8abb8'),
};
colors = {
dark,
background,
surface,
text: readColor('--text-primary', '#f1f1f5'),
textSecondary: readColor('--text-secondary', '#a8abb8'),
accent: readColor('--accent', '#b8aef5'),
shining: readColor('--rel-shining', '#68d8ff'),
edge,
// Заливка мелкой точки – фон с оттенком группы (как подложка инициалов на картинке).
dotFill: Object.fromEntries(Object.entries(edge).map(([key, rgb]) => [key, mix(surface, rgb, dark ? 0.16 : 0.12)])),
marks: {
green: dark ? [92, 214, 140] : [36, 140, 82],
yellow: dark ? [245, 205, 80] : [190, 140, 10],
red: dark ? [255, 104, 104] : [200, 48, 60],
blue: dark ? [96, 170, 255] : [40, 100, 210],
violet: dark ? [190, 140, 255] : [120, 70, 210],
},
};
colors.dotFill.shining = mix(surface, colors.shining, dark ? 0.16 : 0.12);
const islandFallback = dark ? ISLAND_RGB.dark : ISLAND_RGB.light;
colors.islands = islandFallback.map((rgb, i) => readColor(`--net-island-${i}`, `rgb(${rgb.join(', ')})`));
fontFamily = getComputedStyle(stage).fontFamily || 'sans-serif';
auraSprite = null;
nodes.forEach((node) => { node.sprite = null; node.labelWidth = 0; });
requestDraw();
}
// Мягкий ореол один раз рисуется в отдельный холст и дальше только копируется.
let auraSprite = null;
function getAuraSprite() {
if (auraSprite) return auraSprite;
const size = 128;
const sprite = document.createElement('canvas');
sprite.width = size;
sprite.height = size;
const g = sprite.getContext('2d');
const gradient = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
const c = colors.shining;
gradient.addColorStop(0, rgba(c, colors.dark ? 0.55 : 0.42));
gradient.addColorStop(0.45, rgba(c, colors.dark ? 0.24 : 0.18));
gradient.addColorStop(1, rgba(c, 0));
g.fillStyle = gradient;
g.fillRect(0, 0, size, size);
auraSprite = sprite;
return sprite;
}
function ringColorOf(node) {
if (node.data.shining) return colors.shining;
if (node.isFocus) return colors.accent;
return colors.edge[groupOf(node.data)] || colors.textSecondary;
}
// Разрешение картинки точки подбирается под масштаб (степени двойки): на обзоре картинки
// не нужны вовсе, вблизи – только у видимых точек.
function spriteScaleFor(zoom) {
const need = clamp(dpr * zoom * 1.15, 1, 8);
return 2 ** Math.ceil(Math.log2(need));
}
// Готовая картинка точки: фон, фото или инициалы, цветной ободок.
function buildSprite(node, scale) {
const r = node.r;
const ring = node.isFocus ? 3 : 2;
const size = Math.ceil((r + ring) * 2 * scale);
const sprite = document.createElement('canvas');
sprite.width = size;
sprite.height = size;
const g = sprite.getContext('2d');
const c = size / 2;
const inner = r * scale;
g.save();
g.beginPath();
g.arc(c, c, inner, 0, Math.PI * 2);
g.closePath();
g.fillStyle = rgba(colors.surface, 1);
g.fill();
g.clip();
const image = node.image?.ready ? node.image.img : null;
if (image && image.naturalWidth) {
const side = Math.min(image.naturalWidth, image.naturalHeight);
const sx = (image.naturalWidth - side) / 2;
const sy = (image.naturalHeight - side) / 2;
g.drawImage(image, sx, sy, side, side, c - inner, c - inner, inner * 2, inner * 2);
} else {
const tint = node.data.shining ? colors.shining : (colors.edge[groupOf(node.data)] || colors.accent);
g.fillStyle = rgba(tint, colors.dark ? 0.16 : 0.12);
g.fillRect(0, 0, size, size);
g.fillStyle = rgba(colors.text, 0.92);
g.font = `600 ${Math.round(inner * (node.initials.length > 1 ? 0.68 : 0.78))}px ${fontFamily}`;
g.textAlign = 'center';
g.textBaseline = 'middle';
g.fillText(node.initials, c, c + inner * 0.04);
}
g.restore();
g.beginPath();
g.arc(c, c, inner + (ring * scale) / 2, 0, Math.PI * 2);
g.lineWidth = ring * scale;
g.strokeStyle = rgba(ringColorOf(node), node.data.shining || node.isFocus ? 0.95 : 0.75);
g.stroke();
node.sprite = sprite;
node.spriteScale = scale;
node.spriteSize = size / scale;
}
function attachAvatar(node) {
const url = avatarUrlSync(node.data);
const take = (src) => {
const entry = loadImage(src);
if (!entry) return;
node.image = entry;
if (!entry.ready && !entry.failed) entry.waiters.add(() => { node.sprite = null; requestDraw(); });
};
if (url) take(url);
else if (node.data?.avatar && typeof node.data.avatar === 'object') {
void avatarUrlFromServer(node.data).then((src) => {
if (destroyed || !src || nodes.get(node.id) !== node) return;
take(src);
node.sprite = null;
requestDraw();
});
}
}
// ---- геометрия ---------------------------------------------------------------------------
function toScreen(x, y) {
return { x: (x - camera.x) * camera.zoom + width / 2, y: (y - camera.y) * camera.zoom + height / 2 };
}
function toWorld(sx, sy) {
return { x: (sx - width / 2) / camera.zoom + camera.x, y: (sy - height / 2) / camera.zoom + camera.y };
}
function insets() {
const value = getInsets?.() || {};
return { top: Number(value.top) || 0, bottom: Number(value.bottom) || 0 };
}
function resize() {
const rect = stage.getBoundingClientRect();
const nextW = Math.max(1, Math.round(rect.width));
const nextH = Math.max(1, Math.round(rect.height));
const nextDpr = Math.min(3, window.devicePixelRatio || 1);
if (nextW === width && nextH === height && nextDpr === dpr) return;
const dprChanged = nextDpr !== dpr;
width = nextW;
height = nextH;
dpr = nextDpr;
for (const c of [canvas, backCanvas]) {
c.width = Math.round(width * dpr);
c.height = Math.round(height * dpr);
c.style.width = `${width}px`;
c.style.height = `${height}px`;
}
if (dprChanged) nodes.forEach((node) => { node.sprite = null; });
if ((pendingFit || autoFit) && width > 1 && height > 1) fitCamera({ animate: false });
requestDraw();
}
// Растяжение колец под форму свободной части экрана: на телефоне – вверх, на широком – вбок.
function layoutStretch() {
// Данные могут прийти раньше, чем ResizeObserver сообщит размер, – меряем сами.
const rect = width > 1 && height > 1 ? { width, height } : stage.getBoundingClientRect();
if (rect.width <= 1 || rect.height <= 1) return { x: 1, y: 1 };
const pad = insets();
const ratio = Math.max(80, rect.height - pad.top - pad.bottom) / Math.max(80, rect.width);
const k = Math.round(clamp(ratio >= 1 ? ratio : 1 / ratio, 1, 1.45) * 10) / 10;
return ratio >= 1 ? { x: 1, y: k } : { x: k, y: 1 };
}
// ---- кадры -------------------------------------------------------------------------------
// Кадр по действию (палец, масштаб, новые данные) перерисовывает оба слоя; кадры одного
// только «дыхания» ауры – лишь нижний.
function requestDraw() {
dirty = true;
backDirty = true;
if (destroyed || rafId) return;
rafId = requestAnimationFrame(frame);
}
function hasVisibleShining() {
for (const node of nodes.values()) if (node.data.shining && node.alpha > 0.01) return true;
return false;
}
function frame(now) {
rafId = 0;
if (destroyed) return;
if (!colors) {
if (!probe.isConnected) return; // кадр запросит resize, когда экран встроят
refreshColors();
}
let busy = false;
if (moveTween) {
const t = clamp((now - moveTween.t0) / moveTween.dur, 0, 1);
const k = easeOutCubic(t);
nodes.forEach((node) => {
if (node.dragging) return;
node.x = node.fromX + (node.tx - node.fromX) * k;
node.y = node.fromY + (node.ty - node.fromY) * k;
});
if (t >= 1) {
if (moveTween.real) labelsShownAt = now;
moveTween = null;
} else busy = true;
}
// Подписи проявляются после того, как точки встали.
if (!moveTween && now - labelsShownAt < LABEL_FADE_MS) busy = true;
nodes.forEach((node) => {
if (node.alpha === node.alphaTarget) return;
const step = (now - (node.alphaAt || now)) / FADE_MS;
node.alphaAt = now;
node.alpha = node.alpha < node.alphaTarget ? Math.min(node.alphaTarget, node.alpha + step) : Math.max(node.alphaTarget, node.alpha - step);
if (node.alpha !== node.alphaTarget) busy = true;
});
if (leaving.length) {
leaving = leaving.filter((node) => {
const step = (now - (node.alphaAt || now)) / FADE_MS;
node.alphaAt = now;
node.alpha = Math.max(0, node.alpha - step);
return node.alpha > 0;
});
if (leaving.length) busy = true;
}
const dimTarget = selectedId ? 1 : 0;
if (selectDim !== dimTarget) {
selectDim = dimTarget > selectDim ? Math.min(1, selectDim + 0.12) : Math.max(0, selectDim - 0.12);
busy = true;
}
const groupTarget = focusSet ? 1 : 0;
if (groupDim !== groupTarget) {
groupDim = groupTarget > groupDim ? Math.min(1, groupDim + 0.12) : Math.max(0, groupDim - 0.12);
busy = true;
}
if (cameraTween) {
const t = clamp((now - cameraTween.t0) / CAMERA_MS, 0, 1);
const k = easeOutCubic(t);
camera.x = cameraTween.from.x + (cameraTween.to.x - cameraTween.from.x) * k;
camera.y = cameraTween.from.y + (cameraTween.to.y - cameraTween.from.y) * k;
camera.zoom = cameraTween.from.zoom * Math.pow(cameraTween.to.zoom / cameraTween.from.zoom, k);
if (t >= 1) cameraTween = null; else busy = true;
}
if (inertia) {
camera.x -= inertia.vx / camera.zoom;
camera.y -= inertia.vy / camera.zoom;
inertia.vx *= 0.88;
inertia.vy *= 0.88;
if (Math.abs(inertia.vx) + Math.abs(inertia.vy) < 0.3) inertia = null; else busy = true;
}
let spritesPending = false;
const breathingNow = !reducedMotion?.matches && hasVisibleShining();
if (dirty || busy || backDirty) updateIslandGeometry();
if (dirty || busy) {
dirty = false;
spritesPending = drawFront();
}
const breathing = breathingNow;
if (backDirty || busy || (breathing && now - lastBackAt >= AURA_FRAME_MS)) {
backDirty = false;
drawBack(now, breathing);
lastBackAt = now;
}
if (spritesPending) dirty = true;
lastFrameBusy = busy || spritesPending;
if (busy || breathing || spritesPending) rafId = requestAnimationFrame(frame);
}
const markDirty = requestDraw;
function nodeAlpha(node) {
let alpha = node.alpha;
if (selectDim > 0 && selectedId) {
const near = node.id === selectedId || node.adjacent?.has(selectedId);
if (!near) alpha *= 1 - selectDim * 0.7;
}
if (groupDim > 0 && focusSet && !node.isFocus && !focusSet.has(node.id)) {
alpha *= 1 - groupDim * 0.74;
}
return alpha;
}
// ---- острова -----------------------------------------------------------------------------
const islandsShown = () => guides?.kind === 'islands' && guides.items.length > 0;
// Оболочки островов по текущим положениям точек (во время перестройки они «перетекают»
// вместе с людьми). Перетаскиваемый человек в оболочку своего острова не входит.
function updateIslandGeometry() {
islandGeo = new Map();
if (!islandsShown()) return;
for (const item of guides.items) {
const points = [];
for (const id of item.members) {
const node = nodes.get(id);
if (!node || node.dragging || !Number.isFinite(node.x)) continue;
points.push({ x: node.x, y: node.y });
}
if (!points.length) continue;
let cx = 0;
let cy = 0;
points.forEach((p) => { cx += p.x; cy += p.y; });
cx /= points.length;
cy /= points.length;
let r = 0;
let top = Infinity;
let bottom = -Infinity;
points.forEach((p) => {
r = Math.max(r, Math.hypot(p.x - cx, p.y - cy));
top = Math.min(top, p.y);
bottom = Math.max(bottom, p.y);
});
islandGeo.set(item.key, { item, hull: convexHull(points), cx, cy, r: r + HULL_PAD, top: top - HULL_PAD, bottom: bottom + HULL_PAD });
}
}
function islandColor(item) {
if (item.kind === 'rest' || item.color < 0) return colors.textSecondary;
return colors.islands[item.color % ISLAND_COLORS] || colors.accent;
}
// Подложки островов – на нижнем слое, под нитями и точками.
function drawIslands() {
if (!islandGeo.size) return;
const fade = settledFade();
const zoom = camera.zoom;
bctx.save();
worldTransform(bctx);
bctx.lineJoin = 'round';
islandGeo.forEach((geo, id) => {
const rgb = islandColor(geo.item);
const rest = geo.item.kind === 'rest';
const selected = id === selectedGroup;
const target = id === dropGroup;
const dimmed = groupDim > 0 && focusSet && !selected;
let fill = rest ? (colors.dark ? 0.035 : 0.04) : (colors.dark ? 0.075 : 0.07);
let stroke = rest ? 0.22 : (colors.dark ? 0.34 : 0.42);
if (selected) { fill *= 1 + groupDim * 0.8; stroke = Math.min(0.85, stroke + 0.4 * groupDim); }
if (dimmed) { fill *= 1 - groupDim * 0.6; stroke *= 1 - groupDim * 0.6; }
if (target) { fill = Math.max(fill, 0.16); stroke = 0.9; }
// Пока точки разлетаются, подложки едва видны – иначе мигают оболочки клубка.
const appear = 0.35 + 0.65 * fade;
bctx.beginPath();
traceHull(bctx, geo.hull, HULL_PAD);
bctx.fillStyle = rgba(rgb, fill * appear);
bctx.fill();
bctx.lineWidth = (target || selected ? 2 : 1.2) / zoom;
bctx.setLineDash(rest || target ? [5 / zoom, 5 / zoom] : []);
bctx.strokeStyle = rgba(rgb, stroke * appear);
bctx.stroke();
});
bctx.setLineDash([]);
bctx.restore();
}
// Мостики между островами: одна нить на пару, толще – чем больше знакомств между ними.
// Видны только заметные: у каждого острова – два самых крепких (иначе при случайных
// знакомствах «каждый с каждым» получается паутина); у выбранного острова – все.
// Отдельные нити между людьми разных островов видны только у выбранного человека.
let strongBridges = new Set();
function pickStrongBridges() {
const byIsland = new Map();
crossCounts.forEach((count, key) => {
if (count < 2) return;
key.split('|').forEach((id) => {
if (!byIsland.has(id)) byIsland.set(id, []);
byIsland.get(id).push({ key, count });
});
});
strongBridges = new Set();
byIsland.forEach((list) => {
list.sort((x, y) => y.count - x.count || (x.key < y.key ? -1 : 1)).slice(0, 2).forEach((row) => strongBridges.add(row.key));
});
}
function drawBridges(widthScale) {
if (!islandGeo.size || !crossCounts.size) return [];
let max = 1;
crossCounts.forEach((count) => { max = Math.max(max, count); });
const zoom = camera.zoom;
const bubbles = [];
ctx.save();
ctx.lineCap = 'round';
crossCounts.forEach((count, key) => {
const [a, b] = key.split('|');
const touches = Boolean(selectedGroup) && (a === selectedGroup || b === selectedGroup);
if (!touches && !strongBridges.has(key)) return;
const ga = islandGeo.get(a);
const gb = islandGeo.get(b);
if (!ga || !gb) return;
const dx = gb.cx - ga.cx;
const dy = gb.cy - ga.cy;
const len = Math.hypot(dx, dy) || 1;
if (len <= ga.r + gb.r + 4) return;
const ux = dx / len;
const uy = dy / len;
const x1 = ga.cx + ux * ga.r;
const y1 = ga.cy + uy * ga.r;
const x2 = gb.cx - ux * gb.r;
const y2 = gb.cy - uy * gb.r;
// Мостик сквозь третий остров читается как его собственные связи – такой не рисуем
// (у выбранного острова видны все: там важнее полнота).
if (!touches && bridgeBlocked(x1, y1, x2, y2, a, b)) return;
const sag = Math.min(40, len * 0.08) * (hash01(key) < 0.5 ? -1 : 1);
const cx = (x1 + x2) / 2 - uy * sag;
const cy = (y1 + y2) / 2 + ux * sag;
const share = count / max;
let alpha = 0.16 + 0.34 * share;
if (selectedGroup) alpha = touches ? Math.max(alpha, 0.55) : alpha * (1 - groupDim * 0.75);
else if (focusSet) alpha *= 1 - groupDim * 0.75;
if (selectedId) alpha *= 1 - selectDim * 0.6;
alpha *= settledFade();
if (alpha <= 0.01) return;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cx, cy, x2, y2);
ctx.lineWidth = (1.4 + 3.2 * Math.sqrt(share)) * widthScale;
ctx.strokeStyle = rgba(colors.textSecondary, alpha);
ctx.stroke();
// Число знакомств – посередине мостика, если он на экране не совсем короткий.
const mid = { x: 0.25 * x1 + 0.5 * cx + 0.25 * x2, y: 0.25 * y1 + 0.5 * cy + 0.25 * y2 };
if ((len - ga.r - gb.r) * zoom > 44) bubbles.push({ ...mid, count, alpha: Math.min(1, alpha * 2), touches });
});
ctx.restore();
return bubbles;
}
function bridgeBlocked(x1, y1, x2, y2, a, b) {
const dx = x2 - x1;
const dy = y2 - y1;
const len2 = dx * dx + dy * dy || 1;
for (const [id, geo] of islandGeo) {
if (id === a || id === b) continue;
const t = clamp(((geo.cx - x1) * dx + (geo.cy - y1) * dy) / len2, 0, 1);
const d = Math.hypot(x1 + dx * t - geo.cx, y1 + dy * t - geo.cy);
if (d < geo.r * 0.92) return true;
}
return false;
}
function drawBridgeCounts(bubbles, fits) {
if (!bubbles.length) return;
ctx.save();
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.font = `600 10.5px ${fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const bubble of bubbles) {
const p = toScreen(bubble.x, bubble.y);
if (p.x < -20 || p.x > width + 20 || p.y < -20 || p.y > height + 20) continue;
const text = String(bubble.count);
const w = Math.max(20, ctx.measureText(text).width + 10);
// Число не налезает на подписи островов (они уже заняли свои места).
if (!fits(p.x - w / 2, p.y - 9, w, 18)) continue;
ctx.globalAlpha = bubble.alpha;
ctx.fillStyle = rgba(colors.background, 0.94);
ctx.strokeStyle = rgba(colors.textSecondary, 0.45);
ctx.lineWidth = 1;
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(p.x - w / 2, p.y - 9, w, 18, 9);
else ctx.rect(p.x - w / 2, p.y - 9, w, 18);
ctx.fill();
ctx.stroke();
ctx.fillStyle = rgba(colors.textSecondary, 1);
ctx.fillText(text, p.x, p.y + 0.5);
}
ctx.restore();
ctx.globalAlpha = 1;
}
// Подписи островов: цветная точка, название и число людей.
// Крупный на экране остров – подпись над ним (а если там занято – под ним); верх острова
// ушёл под панель фильтров, а сам он ещё виден – подпись прилипает к краю.
// Мелкий остров (обзор всей карты) – подпись прямо на нём, как название района на карте:
// коротко («Людмила К.» вместо «Людмила К. и др. · 30»), длинное – в две строки. Так
// подпись не уезжает на соседний остров и сразу ясно, к какому она относится.
function fitText(text, maxWidth) {
if (ctx.measureText(text).width <= maxWidth) return text;
let shown = text;
while (shown.length > 2 && ctx.measureText(`${shown}…`).width > maxWidth) shown = shown.slice(0, -1);
return `${shown.trimEnd()}…`;
}
// Одна или две строки не шире maxWidth: разрыв – по пробелу ближе к середине.
function wrapText(text, maxWidth) {
if (ctx.measureText(text).width <= maxWidth) return [text];
const words = text.split(' ');
if (words.length < 2) return [fitText(text, maxWidth)];
let best = null;
for (let i = 1; i < words.length; i += 1) {
const a = words.slice(0, i).join(' ');
const b = words.slice(i).join(' ');
const w = Math.max(ctx.measureText(a).width, ctx.measureText(b).width);
if (!best || w < best.w) best = { a, b, w };
}
return [fitText(best.a, maxWidth), fitText(best.b, maxWidth)];
}
function drawCaptionPill(item, lines, x, y, w, h, { selected, dimmed }) {
const rgb = islandColor(item);
const strong = selected || item.key === dropGroup;
ctx.globalAlpha = settledFade() * (dimmed ? 1 - groupDim * 0.55 : 1);
ctx.fillStyle = rgba(colors.background, 0.94);
ctx.strokeStyle = rgba(rgb, strong ? 0.95 : 0.55);
ctx.lineWidth = strong ? 1.6 : 1;
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(x, y, w, h, Math.min(h / 2, 13));
else ctx.rect(x, y, w, h);
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.arc(x + 13, y + (lines.length > 1 ? 13 : h / 2), 4, 0, Math.PI * 2);
ctx.fillStyle = rgba(rgb, item.kind === 'rest' ? 0.7 : 1);
ctx.fill();
ctx.fillStyle = rgba(colors.text, 0.95);
lines.forEach((line, i) => ctx.fillText(line, x + 23, y + 13 + i * 15 + 0.5));
}
function drawIslandCaptions(fits, reserveRect) {
captionHits = [];
if (!islandGeo.size) return;
const fade = settledFade();
if (fade <= 0) return;
const topInset = insets().top + 4;
const bottomInset = height - insets().bottom;
const order = [...islandGeo.values()].sort((a, b) => (b.item.key === selectedGroup) - (a.item.key === selectedGroup)
|| (a.item.kind === 'rest') - (b.item.kind === 'rest') || b.item.count - a.item.count);
ctx.save();
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.textBaseline = 'middle';
ctx.textAlign = 'left';
for (const geo of order) {
const item = geo.item;
if (!item.caption) continue;
const top = toScreen(geo.cx, geo.top);
const bottom = toScreen(geo.cx, geo.bottom);
const center = toScreen(geo.cx, geo.cy);
if (bottom.y < topInset + 20 || top.y > bottomInset || center.x < -150 || center.x > width + 150) continue;
const selected = item.key === selectedGroup;
const dimmed = groupDim > 0 && focusSet && !selected;
const islandW = Math.max(0, (geo.r - HULL_PAD) * 2 * camera.zoom);
let placed = null;
// Над островом / под ним – полной подписью, при нехватке места короче.
const besideIsland = () => {
ctx.font = `600 12px ${fontFamily}`;
const texts = [fitText(item.caption, 220), fitText(item.short || item.caption, 150)];
for (const text of texts) {
const w = ctx.measureText(text).width + 32;
const x = clamp(center.x - w / 2, 6, width - w - 6);
for (const y of [Math.max(topInset, top.y - 30), bottom.y + 4]) {
if (y < topInset || y + 26 > bottomInset) continue;
if (fits(x - 2, y - 1, w + 4, 28)) return { lines: [text], x, y, w, h: 26 };
}
}
return null;
};
// На самом острове (как название района): коротко, длинное – в две строки; если тесно –
// сдвинувшись в пределах острова, над ним или под ним.
const onIsland = () => {
ctx.font = `600 11.5px ${fontFamily}`;
const maxW = Math.max(72, Math.min(150, islandW + 28));
const name = item.short || item.caption;
const withCount = `${name} · ${item.count}`;
const lines = ctx.measureText(withCount).width <= maxW ? [withCount] : wrapText(name, maxW);
const w = Math.max(...lines.map((line) => ctx.measureText(line).width)) + 30;
const h = lines.length > 1 ? 41 : 26;
const variants = [{ lines, w, h }];
if (lines.length > 1) {
const one = fitText(name, Math.max(56, islandW + 8));
variants.push({ lines: [one], w: ctx.measureText(one).width + 30, h: 26 });
}
for (const v of variants) {
const shiftY = Math.max(0, (bottom.y - top.y) / 2 - v.h / 2 - 4);
const shiftX = Math.max(0, Math.min(islandW / 2, v.w / 2));
const spots = [[0, 0], [0, -shiftY], [0, shiftY], [-shiftX, 0], [shiftX, 0], [-shiftX, -shiftY], [shiftX, -shiftY], [-shiftX, shiftY], [shiftX, shiftY]]
.map(([dx, dy]) => [center.x - v.w / 2 + dx, center.y - v.h / 2 + dy]);
spots.push([center.x - v.w / 2, top.y - v.h - 2], [center.x - v.w / 2, bottom.y + 2]);
for (const [sx, sy] of spots) {
const vx = clamp(sx, 4, width - v.w - 4);
if (sy < topInset || sy + v.h > bottomInset) continue;
if (fits(vx - 2, sy - 1, v.w + 4, v.h + 2)) return { lines: v.lines, x: vx, y: sy, w: v.w, h: v.h };
}
}
return null;
};
// На обзоре (людей не различить) подпись – на острове; когда люди видны, она их не
// закрывает и встаёт рядом, а на остров – только если рядом места нет.
const overview = NODE_R[1] * camera.zoom < 8 && islandW < 150;
placed = selected || !overview ? (besideIsland() || onIsland()) : (onIsland() || besideIsland());
if (!placed && selected) {
ctx.font = `600 12px ${fontFamily}`;
const text = fitText(item.short || item.caption, 150);
const w = ctx.measureText(text).width + 32;
placed = { lines: [text], x: clamp(center.x - w / 2, 6, width - w - 6), y: clamp(top.y - 30, topInset, bottomInset - 26), w, h: 26 };
}
if (!placed) continue;
captionHits.push({ id: item.key, x: placed.x, y: placed.y, w: placed.w, h: placed.h });
drawCaptionPill(item, placed.lines, placed.x, placed.y, placed.w, placed.h, { selected, dimmed });
// Выбранный остров рисуется первым: его место подписи соседей обходят.
if (selected) {
const left = toScreen(geo.cx - geo.r, geo.cy - geo.r);
const right = toScreen(geo.cx + geo.r, geo.cy + geo.r);
reserveRect(left.x, left.y, right.x - left.x, right.y - left.y);
}
}
ctx.restore();
ctx.globalAlpha = 1;
}
// Подпись центра рисуется всегда – подписи островов её обходят.
function reserveFocusLabel(reserve) {
if (!islandGeo.size) return;
const node = nodes.get(focusId);
if (!node) return;
const p = toScreen(node.x, node.y);
const r = node.r * camera.zoom;
const w = Math.max(90, (node.labelWidth || 70) + 20);
reserve(p.x - w / 2, p.y - r - 4, w, r * 2 + 30);
}
// Остров под точкой экрана (для переноса человека). Свой остров не считается.
function islandAt(sx, sy, exceptId) {
const world = toWorld(sx, sy);
let best = '';
let bestScore = Infinity;
islandGeo.forEach((geo, id) => {
if (id === exceptId) return;
const d = Math.hypot(world.x - geo.cx, world.y - geo.cy);
const score = d / Math.max(geo.r, 1);
if (score <= 1 && score < bestScore) { best = id; bestScore = score; }
});
return best;
}
function overviewIslands() {
return islandsShown() && NODE_R[1] * camera.zoom < 8;
}
function captionAt(sx, sy) {
for (let i = captionHits.length - 1; i >= 0; i -= 1) {
const hit = captionHits[i];
if (sx >= hit.x - 4 && sx <= hit.x + hit.w + 4 && sy >= hit.y - 6 && sy <= hit.y + hit.h + 6) return hit.id;
}
return '';
}
function viewBox(pad = 80) {
const zoom = camera.zoom;
return {
left: camera.x - width / 2 / zoom - pad,
right: camera.x + width / 2 / zoom + pad,
top: camera.y - height / 2 / zoom - pad,
bottom: camera.y + height / 2 / zoom + pad,
};
}
function worldTransform(c) {
const zoom = camera.zoom;
c.setTransform(dpr * zoom, 0, 0, dpr * zoom, dpr * (width / 2 - camera.x * zoom), dpr * (height / 2 - camera.y * zoom));
}
// ---- нижний слой: сетка, группы, аура ---------------------------------------------------
function drawGrid() {
let step = 48;
while (step * camera.zoom < 22) step *= 2;
const s = step * camera.zoom;
const origin = toScreen(0, 0);
const offX = ((origin.x % s) + s) % s;
const offY = ((origin.y % s) + s) % s;
const dot = clamp(1.1 * Math.sqrt(camera.zoom), 0.7, 1.6);
bctx.fillStyle = rgba(colors.textSecondary, colors.dark ? 0.16 : 0.22);
bctx.beginPath();
for (let x = offX; x < width; x += s) {
for (let y = offY; y < height; y += s) bctx.rect(x - dot / 2, y - dot / 2, dot, dot);
}
bctx.fill();
}
// Насколько проявлены подписи и кольца групп: 0 – пока точки разлетаются, 1 – встали.
function settledFade() {
if (moveTween?.real) return 0;
return clamp((performance.now() - labelsShownAt) / LABEL_FADE_MS, 0, 1);
}
// Границы колец «Близкие / Друзья / Контакты» – тонкий пунктир на фоне.
function drawGuideRings() {
if (guides?.kind !== 'rings' || !guides.items.length || nodes.size < 6) return;
const anchor = nodes.get(focusId);
if (!anchor) return;
const { stretch } = guides;
const zoom = camera.zoom;
bctx.save();
worldTransform(bctx);
bctx.lineWidth = 1 / zoom;
bctx.setLineDash([3 / zoom, 5 / zoom]);
bctx.strokeStyle = rgba(colors.textSecondary, (colors.dark ? 0.22 : 0.28) * settledFade());
for (const band of guides.items) {
const r = band.to + 32;
bctx.beginPath();
bctx.ellipse(anchor.x, anchor.y, r * stretch.x, r * stretch.y, 0, 0, Math.PI * 2);
bctx.stroke();
}
bctx.restore();
}
// Подписи групп («Друзья · 58») – поверх нитей и точек, на постоянном экранном размере.
// Занятые ими места подписи людей обходят.
function drawGuideCaptions(reserve) {
if (guides?.kind !== 'rings' || !guides.items.length || nodes.size < 6) return;
const anchor = nodes.get(focusId);
if (!anchor) return;
const { stretch } = guides;
const fade = settledFade();
if (fade <= 0) return;
const topInset = insets().top - 8;
ctx.save();
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.globalAlpha = fade;
ctx.font = `600 11px ${fontFamily}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const item of guides.items) {
const p = toScreen(anchor.x, anchor.y - (item.to + 32) * stretch.y);
if (p.y < -20 || p.y > height + 20 || p.x < -200 || p.x > width + 200) continue;
// Под панелью чипов подпись не видна – не рисуем её там вовсе.
if (p.y - 10 < topInset) continue;
const text = `${item.caption} · ${item.count}`;
const w = ctx.measureText(text).width + 16;
// Подпись не уходит за край экрана.
p.x = clamp(p.x, w / 2 + 6, width - w / 2 - 6);
reserve(p.x - w / 2, p.y - 10, w, 20);
ctx.fillStyle = rgba(colors.background, 0.92);
ctx.strokeStyle = rgba(colors.textSecondary, colors.dark ? 0.28 : 0.32);
ctx.lineWidth = 1;
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(p.x - w / 2, p.y - 10, w, 20, 10);
else ctx.rect(p.x - w / 2, p.y - 10, w, 20);
ctx.fill();
ctx.stroke();
ctx.fillStyle = rgba(colors.textSecondary, 1);
ctx.fillText(text, p.x, p.y + 0.5);
}
ctx.restore();
}
function drawBack(now, breathing) {
bctx.setTransform(dpr, 0, 0, dpr, 0, 0);
bctx.clearRect(0, 0, width, height);
drawGrid();
drawGuideRings();
drawIslands();
worldTransform(bctx);
const view = viewBox();
const breath = breathing ? 0.5 + 0.5 * Math.sin((now / AURA_PERIOD_MS) * Math.PI * 2) : 0.6;
const aura = getAuraSprite();
for (const node of [...leaving, ...nodes.values()]) {
if (!node.data.shining || node.alpha <= 0.01) continue;
if (node.x < view.left || node.x > view.right || node.y < view.top || node.y > view.bottom) continue;
const size = node.r * (2.9 + breath * 0.35);
bctx.globalAlpha = nodeAlpha(node) * (0.75 + breath * 0.25);
bctx.drawImage(aura, node.x - size / 2, node.y - size / 2, size, size);
}
bctx.globalAlpha = 1;
}
// ---- верхний слой: нити, точки, подписи -------------------------------------------------
function edgeGeometry(a, b, key) {
const dx = b.x - a.x;
const dy = b.y - a.y;
const len = Math.hypot(dx, dy) || 1;
// Нить чуть провисает: направление изгиба постоянное для каждой пары.
const sag = Math.min(26, len * 0.07) * (hash01(key) < 0.5 ? -1 : 1);
const cx = (a.x + b.x) / 2 - (dy / len) * sag;
const cy = (a.y + b.y) / 2 + (dx / len) * sag;
const ua = Math.hypot(cx - a.x, cy - a.y) || 1;
const ub = Math.hypot(cx - b.x, cy - b.y) || 1;
return {
x1: a.x + ((cx - a.x) / ua) * (a.r + 1.5),
y1: a.y + ((cy - a.y) / ua) * (a.r + 1.5),
cx,
cy,
x2: b.x + ((cx - b.x) / ub) * (b.r + 1.5),
y2: b.y + ((cy - b.y) / ub) * (b.r + 1.5),
tooShort: len < a.r + b.r + 4,
};
}
// Какие нити видны без выбора. В островах: внутри острова – да; «спицы» к центру и нити
// между островами – нет (их заменяют мостики). В остальных раскладках не видны знакомства
// (tie): на кольцах они превращаются в клубок, а у выбранного человека проявляются.
function edgeShownByDefault(edge, islands) {
if (islands) {
if (edge.a === focusId || edge.b === focusId) return false;
const ga = groupOfNode.get(edge.a);
const gb = groupOfNode.get(edge.b);
return !(ga && gb && ga !== gb);
}
return !edge.tie;
}
// Нити рисуются пачками одного вида: сотни отдельных штрихов со сменой пунктира – это
// и была главная цена кадра на «друзьях друзей».
function drawEdges(inView, widthScale) {
const zoom = camera.zoom;
const islands = islandsShown();
let shownCount = 0;
let cross = 0;
for (const edge of edges) {
if (!edgeShownByDefault(edge, islands)) continue;
shownCount += 1;
if (edge.a !== focusId && edge.b !== focusId) cross += 1;
}
const crowd = shownCount > 120;
// Когда известно, кто с кем знаком, «спицы» к центру почти прячем: кольца и так
// показывают связь с центром, а рисунок знакомств за спицами не виден.
const quietSpokes = cross > 40;
const batches = new Map();
for (const edge of edges) {
const incident = Boolean(selectedId) && (edge.a === selectedId || edge.b === selectedId);
const hovered = Boolean(hoverId) && (edge.a === hoverId || edge.b === hoverId);
if (!incident && !hovered && !edgeShownByDefault(edge, islands)) continue;
const a = nodes.get(edge.a);
const b = nodes.get(edge.b);
if (!a || !b) continue;
let alpha = Math.min(a.alpha, b.alpha);
if (alpha <= 0.01 || (!inView(a) && !inView(b))) continue;
if (selectDim > 0 && selectedId && !incident) alpha *= 1 - selectDim * 0.85;
if (groupDim > 0 && focusSet && !incident && !(focusSet.has(edge.a) && focusSet.has(edge.b))) {
alpha *= 1 - groupDim * 0.85;
}
const type = EDGE_WIDTH[edge.type] ? edge.type : 'contact';
let base = type === 'contact' ? 0.5 : 0.85;
// Когда нитей много, второстепенные (не к центру) и контакты тише – видно рисунок, а не клубок.
if (crowd && !incident) {
const spoke = edge.a === focusId || edge.b === focusId;
if (spoke && quietSpokes) base *= 0.22;
else if (!spoke) base *= quietSpokes ? 0.7 : 0.45;
if (type === 'contact') base *= zoom < 0.5 ? 0.4 : 0.6;
}
const a1 = Math.round(base * alpha * 20) / 20;
if (a1 <= 0) continue;
const g = edgeGeometry(a, b, edge.key);
if (g.tooShort) continue;
const key = `${type}|${edge.mutual ? 1 : 0}|${incident ? 1 : 0}|${a1}`;
let batch = batches.get(key);
if (!batch) {
batch = { type, mutual: edge.mutual, incident, alpha: a1, list: [] };
batches.set(key, batch);
}
batch.list.push(g);
}
ctx.lineCap = 'round';
const ordered = [...batches.values()].sort((x, y) => (x.incident - y.incident) || (x.alpha - y.alpha));
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);
}
ctx.stroke();
}
ctx.setLineDash([]);
}
// Мелкая точка: кружок с заливкой и ободком, пачками одного цвета.
function drawDots(list) {
const zoom = camera.zoom;
const batches = new Map();
for (const node of list) {
const alpha = Math.round(nodeAlpha(node) * 20) / 20;
if (alpha <= 0) continue;
const fillKey = node.data.shining ? 'shining' : groupOf(node.data);
const key = `${fillKey}|${alpha}|${node.isFocus ? 1 : 0}`;
let batch = batches.get(key);
if (!batch) {
batch = { fill: colors.dotFill[fillKey] || colors.surface, ring: ringColorOf(node), alpha, list: [] };
batches.set(key, batch);
}
batch.list.push(node);
}
for (const batch of batches.values()) {
ctx.beginPath();
for (const node of batch.list) {
ctx.moveTo(node.x + node.r, node.y);
ctx.arc(node.x, node.y, node.r, 0, Math.PI * 2);
}
ctx.globalAlpha = batch.alpha;
ctx.fillStyle = rgba(batch.fill, 1);
ctx.fill();
ctx.lineWidth = Math.max(1.4 / zoom, 2);
ctx.strokeStyle = rgba(batch.ring, 0.8);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
// Возвращает true, если не все картинки точек успели собраться (дорисуются в следующих кадрах).
function drawFront() {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
if (!nodes.size && !leaving.length) return false;
const zoom = camera.zoom;
worldTransform(ctx);
const view = viewBox();
const inView = (node) => node.x > view.left && node.x < view.right && node.y > view.top && node.y < view.bottom;
const widthScale = clamp(zoom, 0.6, 1.5) / zoom;
const bubbles = drawBridges(widthScale);
drawEdges(inView, widthScale);
// Точки: глубже – раньше, центр и выбранная – поверх всех.
const order = [...leaving, ...nodes.values()].filter((node) => node.alpha > 0.01 && inView(node));
order.sort((a, b) => (a.drawRank - b.drawRank) || (a.id === selectedId) - (b.id === selectedId));
const scale = spriteScaleFor(zoom);
let builds = 0;
let pending = false;
const small = [];
const big = [];
for (const node of order) {
if (node.r * zoom < LOD_SCREEN_R && node.id !== selectedId && !node.isFocus) small.push(node);
else big.push(node);
}
drawDots(small);
// Крупные картинки точек за краем экрана выгружаются: при прогулке по карте вблизи
// их иначе набиралось бы на сотни мегабайт.
const drawn = new Set(big);
nodes.forEach((node) => { if (node.sprite && node.spriteScale >= 4 && !drawn.has(node)) node.sprite = null; });
for (const node of big) {
if (!node.avatarRequested && node.data.avatar) {
node.avatarRequested = true;
attachAvatar(node);
}
if (!node.sprite || node.spriteScale < scale) {
// За кадр собирается ограниченное число картинок, остальные пока рисуются кружком.
if (builds < SPRITE_BUILDS_PER_FRAME) { buildSprite(node, scale); builds += 1; }
else pending = true;
}
const alpha = nodeAlpha(node);
ctx.globalAlpha = alpha;
if (node.sprite) {
const s = node.spriteSize;
ctx.drawImage(node.sprite, node.x - s / 2, node.y - s / 2, s, s);
} else {
drawDots([node]);
ctx.globalAlpha = alpha;
}
if (node.id === selectedId || node.id === hoverId || node.lifted) {
ctx.beginPath();
ctx.arc(node.x, node.y, node.r + (node.lifted ? 7 : 5), 0, Math.PI * 2);
ctx.lineWidth = (node.lifted ? 3 : 2) / zoom;
ctx.strokeStyle = rgba(colors.accent, node.id === selectedId || node.lifted ? 0.95 : 0.55);
ctx.stroke();
}
}
ctx.globalAlpha = 1;
// Интерес: подсвеченные люди разбросаны по всей карте – вокруг каждого кольцо, чтобы их
// было видно и на обзоре, где точки мелкие.
if (focusSet && !selectedGroupIsFocus && groupDim > 0) {
ctx.globalAlpha = groupDim;
ctx.beginPath();
for (const node of order) {
if (!focusSet.has(node.id) || node.isFocus) continue;
const ring = node.r + Math.max(3, 4 / zoom);
ctx.moveTo(node.x + ring, node.y);
ctx.arc(node.x, node.y, ring, 0, Math.PI * 2);
}
ctx.lineWidth = Math.max(2 / zoom, 2);
ctx.strokeStyle = rgba(colors.accent, 0.95);
ctx.stroke();
ctx.globalAlpha = 1;
}
// Значки поверх точек: от 4 px на экране – иначе это просто шум.
for (const node of order) {
if (node.r * zoom < 4.5) continue;
ctx.globalAlpha = nodeAlpha(node);
if (node.data.official) drawOfficialBadge(node);
if (node.data.mark || node.data.hasNote) drawNoteMark(node);
}
ctx.globalAlpha = 1;
const placed = createLabelGrid();
// Кнопки поверх карты (масштаб, «Списком») подписи обходят.
(getObstacles?.() || []).forEach((rect) => placed.reserve(rect.x, rect.y, rect.w, rect.h));
drawGuideCaptions(placed.reserve);
reserveFocusLabel(placed.reserve);
drawIslandCaptions(placed.fits, placed.reserve);
drawBridgeCounts(bubbles, placed.fits);
drawLabels(order, placed.fits);
return pending;
}
// Сетка занятых мест на экране: подпись встаёт, только если её прямоугольник свободен.
function createLabelGrid() {
const grid = new Map();
const cells = (x, y, w, h, fn) => {
for (let gx = Math.floor(x / LABEL_GRID); gx <= Math.floor((x + w) / LABEL_GRID); gx += 1) {
for (let gy = Math.floor(y / LABEL_GRID); gy <= Math.floor((y + h) / LABEL_GRID); gy += 1) {
if (fn(`${gx}|${gy}`) === false) return false;
}
}
return true;
};
const reserve = (x, y, w, h) => {
const rect = { x, y, w, h };
cells(x, y, w, h, (key) => {
if (!grid.has(key)) grid.set(key, []);
grid.get(key).push(rect);
});
};
const fits = (x, y, w, h) => {
const free = cells(x, y, w, h, (key) => {
const list = grid.get(key);
if (!list) return true;
for (const r of list) if (x < r.x + r.w && x + w > r.x && y < r.y + r.h && y + h > r.y) return false;
return true;
});
if (free) reserve(x, y, w, h);
return free;
};
return { reserve, fits };
}
function drawOfficialBadge(node) {
const br = Math.max(5, node.r * 0.3);
const bx = node.x + node.r * 0.72;
const by = node.y + node.r * 0.72;
ctx.beginPath();
ctx.arc(bx, by, br + 1.5, 0, Math.PI * 2);
ctx.fillStyle = rgba(colors.background, 1);
ctx.fill();
ctx.beginPath();
ctx.arc(bx, by, br, 0, Math.PI * 2);
ctx.fillStyle = 'rgb(47, 140, 255)';
ctx.fill();
ctx.beginPath();
ctx.moveTo(bx - br * 0.45, by + br * 0.02);
ctx.lineTo(bx - br * 0.1, by + br * 0.38);
ctx.lineTo(bx + br * 0.5, by - br * 0.32);
ctx.lineWidth = Math.max(1.2, br * 0.28);
ctx.lineJoin = 'round';
ctx.strokeStyle = '#ffffff';
ctx.stroke();
}
function drawNoteMark(node) {
const mr = Math.max(4, node.r * 0.24);
const mx = node.x + node.r * 0.72;
const my = node.y - node.r * 0.72;
ctx.beginPath();
ctx.arc(mx, my, mr + 1.5, 0, Math.PI * 2);
ctx.fillStyle = rgba(colors.background, 1);
ctx.fill();
ctx.beginPath();
ctx.arc(mx, my, mr, 0, Math.PI * 2);
const mark = colors.marks[node.data.mark];
if (mark) {
ctx.fillStyle = rgba(mark, 1);
ctx.fill();
} else {
// Заметка без метки – полый кружок.
ctx.lineWidth = Math.max(1.2, mr * 0.4);
ctx.strokeStyle = rgba(colors.textSecondary, 0.95);
ctx.stroke();
}
}
// Подписи: по важности (выбранный, центр, наведённый, близкие, друзья, контакты, дальше
// по кругам), каждая – только если её место на экране ещё свободно.
function labelPriority(node) {
if (node.id === selectedId) return 0;
if (node.isFocus) return 1;
if (node.id === hoverId) return 2;
const tier = clamp(Number(node.data.tier) || 1, 1, 3);
const group = GROUP_ORDER.indexOf(groupOf(node.data));
return 3 + (tier - 1) * 5 + group;
}
// Подписи рисуются в экранных пикселях: растут с масштабом, но остаются читаемыми
// (10–15 px). Появляются, когда точка на экране достаточно крупная, чтобы было понятно,
// к кому подпись относится.
const LABEL_PX = { focus: [12.5, 16], 1: [11, 15], 2: [10, 13], 3: [10, 12.5] };
const LABEL_MIN_SCREEN_R = { 1: 7.5, 2: 6.5, 3: 6 };
function drawLabels(order, fits) {
const zoom = camera.zoom;
// Пока точки разлетаются, подписи (кроме центра и выбранного) не рисуем – иначе на
// первых кадрах вспыхивает клубок имён; после остановки они мягко проявляются.
const fade = settledFade();
const candidates = order.filter((node) => {
if (node.isFocus || node.id === selectedId || node.id === hoverId) return true;
if (fade <= 0) return false;
const tier = clamp(Number(node.data.tier) || 1, 1, 3);
return node.r * zoom >= LABEL_MIN_SCREEN_R[tier];
});
candidates.sort((a, b) => labelPriority(a) - labelPriority(b) || b.r - a.r || (a.id < b.id ? -1 : 1));
labelsDrawn = 0;
ctx.save();
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const node of candidates) {
const full = node.isFocus || node.id === selectedId || node.id === hoverId;
const text = full ? node.fullLabel : node.label;
const tier = clamp(Number(node.data.tier) || 1, 1, 3);
const [minPx, maxPx] = node.isFocus ? LABEL_PX.focus : LABEL_PX[tier];
const fontPx = Math.round(clamp((node.isFocus ? LABEL_FONT.focus : LABEL_FONT[tier]) * zoom, minPx, maxPx) * 2) / 2;
const weight = node.isFocus ? 700 : 500;
ctx.font = `${weight} ${fontPx}px ${fontFamily}`;
const cacheKey = `${fontPx}|${full ? 1 : 0}`;
if (node.labelKey !== cacheKey || !node.labelWidth) {
node.labelWidth = ctx.measureText(text).width;
node.labelKey = cacheKey;
}
const padX = fontPx * 0.5;
const h = Math.round(fontPx * 1.5);
const w = node.labelWidth + padX * 2;
const p = toScreen(node.x, node.y);
const x = p.x - w / 2;
const gap = node.isFocus ? 5 : 3;
// Под точкой, а если там занято – над ней.
let y = p.y + node.r * zoom + gap;
if (!fits(x - 2, y - 1, w + 4, h + 2)) {
const above = p.y - node.r * zoom - gap - h;
if (fits(x - 2, above - 1, w + 4, h + 2)) y = above;
else if (!(node.isFocus || node.id === selectedId)) continue;
}
labelsDrawn += 1;
const forced = node.isFocus || node.id === selectedId || node.id === hoverId;
ctx.globalAlpha = Math.max(nodeAlpha(node), node.id === selectedId ? 1 : 0) * (forced ? 1 : fade);
ctx.fillStyle = rgba(colors.background, colors.dark ? 0.82 : 0.88);
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(x, y, w, h, h / 2);
else ctx.rect(x, y, w, h);
ctx.fill();
ctx.fillStyle = rgba(colors.text, node.isFocus ? 1 : 0.92);
ctx.fillText(text, p.x, y + h / 2 + 0.5);
}
ctx.restore();
ctx.globalAlpha = 1;
}
// ---- модель ------------------------------------------------------------------------------
function makeLabel(data, full) {
const text = String(data.name || data.login || data.id);
if (!full) {
// На карте коротко: «Имя Ф.», полностью – у центра, выбранного и под курсором.
const first = String(data.firstName || '').trim();
const last = String(data.lastName || '').trim();
if (first && last) return `${first} ${last[0]}.`;
}
return text.length > MAX_LABEL_CHARS ? `${text.slice(0, MAX_LABEL_CHARS - 1)}…` : text;
}
function targetsBounds(onlyVisible = true, only = null) {
let minX = Infinity; let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity;
nodes.forEach((node) => {
if (only && !only.has(node.id)) return;
if (onlyVisible && node.alphaTarget <= 0) return;
const r = node.r + 8;
minX = Math.min(minX, node.tx - r - 30);
maxX = Math.max(maxX, node.tx + r + 30);
minY = Math.min(minY, node.ty - r);
maxY = Math.max(maxY, node.ty + r + 22);
});
if (!Number.isFinite(minX)) return { minX: -100, minY: -100, maxX: 100, maxY: 100 };
// Подложки островов и подписи над ними тоже должны попасть в кадр.
if (islandsShown()) {
minX -= HULL_PAD - 30;
maxX += HULL_PAD - 30;
minY -= HULL_PAD + 34;
maxY += HULL_PAD - 22;
return { minX, minY, maxX, maxY };
}
// Внешнее кольцо групп с подписью сверху тоже должно попасть в кадр.
const anchor = nodes.get(focusId);
if (!only && guides?.kind === 'rings' && guides.items.length && anchor) {
const r = guides.items[guides.items.length - 1].to + 32;
minY = Math.min(minY, anchor.ty - r * guides.stretch.y - 16);
maxY = Math.max(maxY, anchor.ty + r * guides.stretch.y);
}
return { minX, minY, maxX, maxY };
}
function fitCamera({ animate = true, only = null } = {}) {
autoFit = !only;
// Экран ещё не встроен в страницу и не знает своих размеров – впишем, когда узнает.
if (width <= 1 || height <= 1) {
pendingFit = true;
return;
}
pendingFit = false;
const box = targetsBounds(!only, only);
const pad = insets();
const availW = Math.max(80, width - 32);
const availH = Math.max(80, height - pad.top - pad.bottom - 24);
const zoom = clamp(Math.min(availW / (box.maxX - box.minX), availH / (box.maxY - box.minY), FIT_ZOOM_MAX), ZOOM_MIN, ZOOM_MAX);
// Центр рамки сдвигаем так, чтобы карта легла между верхней и нижней панелями.
const to = {
x: (box.minX + box.maxX) / 2,
y: (box.minY + box.maxY) / 2 - (pad.top - pad.bottom) / 2 / zoom,
zoom,
};
setCamera(to, animate);
}
function setCamera(to, animate) {
inertia = null;
if (!animate || reducedMotion?.matches) {
cameraTween = null;
Object.assign(camera, to);
requestDraw();
return;
}
cameraTween = { from: { ...camera }, to, t0: performance.now() };
requestDraw();
}
/**
* Новый состав карты. Уже стоящие точки остаются на местах (если не relayout),
* новые вылетают из того, через кого появились.
*/
function setGraph(graph, { manual = new Map(), mode = 'rings', relayout = false, fit = false, groups = null } = {}) {
const wantIslands = ISLAND_MODES.has(mode) && Array.isArray(groups) && groups.length > 0;
// Смена вида раскладки (кольца ↔ острова) – всегда полная перестройка.
if (wantIslands !== (guides?.kind === 'islands')) relayout = true;
const nextFocus = String(graph?.focusId || '');
const list = Array.isArray(graph?.nodes) ? graph.nodes : [];
const focusChanged = nextFocus !== focusId;
// Смена центра: сдвигаем старые координаты так, чтобы новый центр оказался в (0, 0),
// и камеру на столько же – картинка не прыгает, а перестраивается от нового центра.
if (focusChanged && nodes.has(nextFocus)) {
const anchor = nodes.get(nextFocus);
const dx = anchor.x;
const dy = anchor.y;
nodes.forEach((node) => { node.x -= dx; node.y -= dy; node.tx -= dx; node.ty -= dy; });
leaving.forEach((node) => { node.x -= dx; node.y -= dy; });
camera.x -= dx;
camera.y -= dy;
if (cameraTween) { cameraTween.to.x -= dx; cameraTween.to.y -= dy; cameraTween.from.x -= dx; cameraTween.from.y -= dy; }
}
focusId = nextFocus;
const nextNodes = new Map();
for (const data of list) {
const id = String(data?.id || '');
if (!id || nextNodes.has(id)) continue;
const prev = nodes.get(id);
const isFocus = id === focusId;
const r = nodeRadius(data, focusId);
const node = prev || { id, x: NaN, y: NaN, tx: 0, ty: 0, alpha: 0, alphaTarget: 1 };
const visualChanged = !prev || prev.r !== r || prev.isFocus !== isFocus
|| prev.data.shining !== data.shining || prev.data.relationType !== data.relationType
|| prev.data.name !== data.name || JSON.stringify(prev.data.avatar || null) !== JSON.stringify(data.avatar || null);
const avatarChanged = !prev || JSON.stringify(prev.data?.avatar || null) !== JSON.stringify(data.avatar || null);
node.data = data;
node.isFocus = isFocus;
node.r = r;
node.drawRank = isFocus ? 100 : -(Number(data.tier) || 1);
if (visualChanged) {
node.sprite = null;
node.label = makeLabel(data, false);
node.fullLabel = makeLabel(data, true);
node.labelWidth = 0;
node.initials = buildAvatarInitials({ login: data.login || String(data.id), firstName: data.firstName || '', lastName: data.lastName || '' }).slice(0, 2)
|| buildAvatarInitials({ login: data.login || String(data.id), firstName: data.name || '' }).slice(0, 2);
// Фото грузится, только когда точка видна достаточно крупно (см. drawFront): на обзоре
// сотен людей картинки не нужны, а сотня одновременных загрузок тормозила бы открытие.
if (avatarChanged) { node.image = null; node.avatarRequested = false; }
}
nextNodes.set(id, node);
}
nodes.forEach((node, id) => {
if (nextNodes.has(id)) return;
node.alphaAt = performance.now();
leaving.push(node);
});
nodes = nextNodes;
if (selectedId && !nodes.has(selectedId)) selectedId = '';
if (hoverId && !nodes.has(hoverId)) hoverId = '';
const edgeKeys = new Set();
edges = [];
for (const edge of Array.isArray(graph?.edges) ? graph.edges : []) {
const a = String(edge?.a || '');
const b = String(edge?.b || '');
if (!a || !b || a === b || !nodes.has(a) || !nodes.has(b)) continue;
const key = a < b ? `${a}|${b}` : `${b}|${a}`;
if (edgeKeys.has(key)) continue;
edgeKeys.add(key);
edges.push({ a, b, key, type: String(edge.type || 'contact'), mutual: edge.mutual !== false, tie: Boolean(edge.tie) });
}
nodes.forEach((node) => { node.adjacent = new Set(); });
for (const edge of edges) {
nodes.get(edge.a).adjacent.add(edge.b);
nodes.get(edge.b).adjacent.add(edge.a);
}
// Что не двигаем: ручные позиции всегда, уже стоящие точки – если это не полная перестройка.
const fixed = new Map();
if (!relayout && !focusChanged) {
nodes.forEach((node) => { if (Number.isFinite(node.x)) fixed.set(node.id, { x: node.tx, y: node.ty }); });
}
manual.forEach((point, id) => { if (nodes.has(id) && id !== focusId) fixed.set(id, point); });
const stretch = relayout || focusChanged || !guides ? layoutStretch() : guides.stretch;
const layout = computeLayout({
focusId, nodes: [...nodes.values()].map((node) => node.data), edges, fixed, mode, stretch, groups: wantIslands ? groups : null,
});
// Подписи групп – от полной раскладки; при добавлении новых людей прежние остаются.
// Острова – всегда по свежим группам: состав и названия задаёт страница.
if (layout.guides && (relayout || focusChanged || !guides || layout.guides.kind === 'islands')) guides = layout.guides;
else if (!layout.guides && (relayout || focusChanged)) guides = null;
groupOfNode = new Map();
crossCounts = new Map();
if (guides?.kind === 'islands') {
guides.items.forEach((item) => {
item.members.forEach((id) => groupOfNode.set(id, item.key));
item.count = item.members.filter((id) => nodes.has(id)).length;
});
for (const edge of edges) {
const ga = groupOfNode.get(edge.a);
const gb = groupOfNode.get(edge.b);
if (!ga || !gb || ga === gb) continue;
const key = ga < gb ? `${ga}|${gb}` : `${gb}|${ga}`;
crossCounts.set(key, (crossCounts.get(key) || 0) + 1);
}
pickStrongBridges();
if (selectedGroup && !guides.items.some((item) => item.key === selectedGroup)) selectedGroup = '';
} else {
selectedGroup = '';
}
if (focusSet) {
focusSet = new Set([...focusSet].filter((id) => nodes.has(id)));
if (!focusSet.size) focusSet = null;
}
if (guides?.kind === 'rings') {
// Подписи групп считают всех, кто сейчас в группе, а не только новых.
const counts = new Map();
nodes.forEach((node) => {
if (node.isFocus || (Number(node.data.tier) || 1) > 1) return;
const key = RING_BAND[groupOf(node.data)];
counts.set(key, (counts.get(key) || 0) + 1);
});
guides.items.forEach((item) => { item.count = counts.get(item.key) || item.count; });
}
const now = performance.now();
nodes.forEach((node) => {
const target = layout.get(node.id) || { x: 0, y: 0 };
if (!Number.isFinite(node.x)) {
// Новая точка вылетает из родителя (или из центра).
const from = nodes.get(node.data.parentId) || nodes.get(focusId);
node.x = from && Number.isFinite(from.x) ? from.x : target.x;
node.y = from && Number.isFinite(from.y) ? from.y : target.y;
node.alpha = 0;
}
node.fromX = node.x;
node.fromY = node.y;
node.tx = target.x;
node.ty = target.y;
node.manual = manual.has(node.id);
node.alphaAt = now;
node.alphaTarget = filterPred && !node.isFocus && !filterPred(node.data) ? 0 : 1;
});
// «Настоящее» движение – если хоть одна точка заметно едет; иначе подписи не прячем.
const realMove = [...nodes.values()].some((node) => Math.hypot(node.tx - node.fromX, node.ty - node.fromY) > 2);
moveTween = reducedMotion?.matches ? null : { t0: now, dur: MOVE_MS, real: realMove };
if (!moveTween) nodes.forEach((node) => { node.x = node.tx; node.y = node.ty; });
if (fit || focusChanged) fitCamera({ animate: !focusChanged || nodes.size > 1 });
else if (autoFit) fitCamera({ animate: true });
markDirty();
}
// Куда встали точки (без человека в центре): из этого собирается «своя раскладка».
function getPositions() {
const out = new Map();
nodes.forEach((node) => {
if (!node.isFocus && Number.isFinite(node.tx)) out.set(node.id, { x: node.tx, y: node.ty });
});
return out;
}
function setFilter(pred) {
filterPred = typeof pred === 'function' ? pred : null;
const now = performance.now();
nodes.forEach((node) => {
node.alphaAt = now;
node.alphaTarget = filterPred && !node.isFocus && !filterPred(node.data) ? 0 : 1;
});
if (selectedId && nodes.get(selectedId)?.alphaTarget === 0) select('');
markDirty();
}
// Видна ли точка в свободной части экрана (между верхней панелью и нижними).
function isComfortablyVisible(node, margin = 30) {
const p = toScreen(node.tx, node.ty);
const pad = insets();
return p.x >= margin && p.x <= width - margin && p.y >= pad.top + margin && p.y <= height - pad.bottom - margin;
}
function select(id, { reveal = false } = {}) {
const next = id && nodes.has(id) ? id : '';
selectedId = next;
if (reveal && next) revealNode(next);
markDirty();
}
// Подвинуть камеру так, чтобы точка оказалась в свободной части экрана (не под карточкой).
function revealNode(id, { minZoom = 0.8 } = {}) {
const node = nodes.get(id);
if (!node || width <= 1) return;
autoFit = false;
if (isComfortablyVisible(node) && camera.zoom >= minZoom * 0.999) return;
const pad = insets();
const zoom = Math.max(camera.zoom, minZoom);
const sy = pad.top + (height - pad.top - pad.bottom) / 2;
setCamera({ x: node.tx, y: node.ty - (sy - height / 2) / zoom, zoom }, true);
}
// ---- жесты -------------------------------------------------------------------------------
const pointers = new Map();
let gesture = null; // { kind: 'pending' | 'pan' | 'drag' | 'pinch', ... }
let lastTap = { at: 0, x: 0, y: 0 };
let longPressTimer = 0;
function localPoint(event) {
const rect = canvas.getBoundingClientRect();
return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}
function hitTest(sx, sy) {
const world = toWorld(sx, sy);
let best = null;
let bestD = Infinity;
for (const node of nodes.values()) {
if (node.alphaTarget <= 0 || node.alpha <= 0.3) continue;
const tolerance = Math.max(node.r + 3, 20 / camera.zoom);
const d = Math.hypot(node.x - world.x, node.y - world.y);
if (d > tolerance) continue;
// Центр и выбранный – «сверху», при равенстве выигрывает ближайший.
const bonus = (node.isFocus ? 6 : 0) + (node.id === selectedId ? 4 : 0);
if (d - node.r - bonus < bestD) {
best = node;
bestD = d - node.r - bonus;
}
}
return best;
}
// Потомки точки, которые ещё никто не двигал руками: при перетаскивании едут вместе с ней.
function dependentsOf(rootId) {
const out = [];
const queue = [rootId];
const seen = new Set(queue);
while (queue.length) {
const id = queue.shift();
nodes.forEach((node) => {
if (seen.has(node.id) || node.manual || node.isFocus || node.data.parentId !== id) return;
seen.add(node.id);
out.push(node);
queue.push(node.id);
});
}
return out;
}
function clearLongPress() {
if (longPressTimer) window.clearTimeout(longPressTimer);
longPressTimer = 0;
}
function startDrag(current) {
clearLongPress();
current.kind = 'drag';
current.node.dragging = true;
current.node.lifted = true;
current.followers = dependentsOf(current.node.id);
current.followers.forEach((node) => { node.dragging = true; });
const w = toWorld(current.last.x, current.last.y);
current.grab = { x: current.node.x - w.x, y: current.node.y - w.y };
canvas.classList.add('is-dragging');
requestDraw();
}
function onPointerDown(event) {
if (event.button !== undefined && event.button > 0) return;
autoFit = false;
// Захват может не сработать (указатель уже отпущен) – жест тогда просто идёт без него.
try { canvas.setPointerCapture?.(event.pointerId); } catch { /* без захвата */ }
const p = localPoint(event);
pointers.set(event.pointerId, p);
cameraTween = null;
inertia = null;
clearLongPress();
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
if (gesture?.kind === 'drag') finishDrag(gesture);
gesture = {
kind: 'pinch',
d0: Math.hypot(a.x - b.x, a.y - b.y) || 1,
zoom0: camera.zoom,
world: toWorld((a.x + b.x) / 2, (a.y + b.y) / 2),
};
return;
}
if (pointers.size > 2) return;
// Подпись острова лежит поверх точек – нажатие по ней открывает группу, а не человека.
// На обзоре (точки мелкие, людей не различить) нажатие по острову – выбор этого острова,
// даже если поверх него легла подпись соседа.
const caption = (overviewIslands() && islandAt(p.x, p.y, '')) || captionAt(p.x, p.y);
const node = caption ? null : hitTest(p.x, p.y);
const touch = event.pointerType === 'touch' || event.pointerType === 'pen';
gesture = { kind: 'pending', touch, start: p, last: p, lastAt: performance.now(), node, caption, vx: 0, vy: 0 };
// Пальцем: просто провести – двигается карта; задержать палец на человеке – можно
// переносить его. Иначе на плотной карте любая попытка сдвинуть её хватала бы точку.
if (touch && node && !node.isFocus) {
const current = gesture;
longPressTimer = window.setTimeout(() => {
longPressTimer = 0;
if (gesture !== current || current.kind !== 'pending') return;
try { navigator.vibrate?.(12); } catch { /* без вибрации */ }
startDrag(current);
}, LONG_PRESS_MS);
}
}
function onPointerMove(event) {
if (!pointers.has(event.pointerId)) {
if (event.pointerType === 'mouse' && !event.buttons) updateHover(event);
return;
}
const p = localPoint(event);
pointers.set(event.pointerId, p);
if (!gesture) return;
if (gesture.kind === 'pinch') {
const [a, b] = [...pointers.values()];
if (!a || !b) return;
const d = Math.hypot(a.x - b.x, a.y - b.y) || 1;
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
camera.zoom = clamp(gesture.zoom0 * (d / gesture.d0), ZOOM_MIN, ZOOM_MAX);
camera.x = gesture.world.x - (mid.x - width / 2) / camera.zoom;
camera.y = gesture.world.y - (mid.y - height / 2) / camera.zoom;
requestDraw();
return;
}
if (gesture.kind === 'pending') {
if (Math.hypot(p.x - gesture.start.x, p.y - gesture.start.y) < TAP_SLOP) return;
clearLongPress();
if (gesture.node && !gesture.node.isFocus && !gesture.touch) {
gesture.last = gesture.start;
startDrag(gesture);
} else {
gesture.kind = 'pan';
canvas.classList.add('is-panning');
if (hoverId) { hoverId = ''; requestDraw(); }
}
}
if (gesture.kind === 'drag') {
const node = gesture.node;
const w = toWorld(p.x, p.y);
const nx = w.x + gesture.grab.x;
const ny = w.y + gesture.grab.y;
const dx = nx - node.x;
const dy = ny - node.y;
if (dx || dy) gesture.moved = true;
node.x = node.tx = nx;
node.y = node.ty = ny;
gesture.followers.forEach((f) => { f.x += dx; f.y += dy; f.tx += dx; f.ty += dy; });
// Над другим островом – его можно сделать группой этого человека: остров подсвечивается.
const target = islandsShown() && node.data.tier <= 1 ? islandAt(p.x, p.y, groupOfNode.get(node.id)) : '';
if (target !== dropGroup) dropGroup = target;
requestDraw();
} else if (gesture.kind === 'pan') {
const now = performance.now();
const dx = p.x - gesture.last.x;
const dy = p.y - gesture.last.y;
camera.x -= dx / camera.zoom;
camera.y -= dy / camera.zoom;
const dt = Math.max(1, now - gesture.lastAt);
gesture.vx = clamp((dx / dt) * 16, -30, 30);
gesture.vy = clamp((dy / dt) * 16, -30, 30);
gesture.lastAt = now;
requestDraw();
}
gesture.last = p;
}
let hoverFrame = 0;
let hoverPoint = null;
function updateHover(event) {
hoverPoint = localPoint(event);
if (hoverFrame) return;
hoverFrame = requestAnimationFrame(() => {
hoverFrame = 0;
if (destroyed || !hoverPoint) return;
const caption = (overviewIslands() && islandAt(hoverPoint.x, hoverPoint.y, '')) || captionAt(hoverPoint.x, hoverPoint.y);
const node = caption ? null : hitTest(hoverPoint.x, hoverPoint.y);
const next = node ? node.id : '';
canvas.classList.toggle('is-over-node', Boolean(node || caption));
if (next !== hoverId) {
hoverId = next;
requestDraw();
}
});
}
function onPointerLeave(event) {
if (event.pointerType !== 'mouse' || pointers.size) return;
hoverPoint = null;
canvas.classList.remove('is-over-node');
if (hoverId) { hoverId = ''; requestDraw(); }
}
function onPointerUp(event) {
if (!pointers.has(event.pointerId)) return;
pointers.delete(event.pointerId);
try { canvas.releasePointerCapture?.(event.pointerId); } catch { /* уже отпущен */ }
clearLongPress();
const current = gesture;
if (current?.kind === 'pinch') {
// Второй палец ещё на экране – продолжаем как панораму без рывка.
if (pointers.size === 1) {
const [p] = [...pointers.values()];
gesture = { kind: 'pan', start: p, last: p, lastAt: performance.now(), node: null, vx: 0, vy: 0 };
} else gesture = null;
return;
}
if (pointers.size) return;
gesture = null;
canvas.classList.remove('is-dragging', 'is-panning');
if (!current || event.type === 'pointercancel') {
if (current?.kind === 'drag') finishDrag(current);
return;
}
if (current.kind === 'pending') {
const now = performance.now();
if (current.caption) {
onGroupSelect?.(current.caption);
} else if (current.node) {
onSelect?.(current.node.data);
} else {
const p = current.start;
if (now - lastTap.at < DOUBLE_TAP_MS && Math.hypot(p.x - lastTap.x, p.y - lastTap.y) < 30) {
lastTap = { at: 0, x: 0, y: 0 };
fitCamera();
} else {
lastTap = { at: now, x: p.x, y: p.y };
onSelect?.(null);
}
}
} else if (current.kind === 'drag') {
// Подержал палец и отпустил на месте – это выбор человека, а не перенос.
if (!current.moved) onSelect?.(current.node.data);
finishDrag(current);
} else if (current.kind === 'pan' && performance.now() - current.lastAt < 80) {
if (Math.abs(current.vx) + Math.abs(current.vy) > 1) {
inertia = { vx: current.vx, vy: current.vy };
requestDraw();
}
}
}
function finishDrag(current) {
const node = current.node;
node.dragging = false;
node.lifted = false;
current.followers?.forEach((f) => { f.dragging = false; });
const group = dropGroup;
dropGroup = '';
if (current.moved) {
node.manual = true;
onNodeMoved?.(node.data, { x: Math.round(node.tx), y: Math.round(node.ty) }, { group });
}
requestDraw();
}
function zoomAt(factor, sx, sy) {
const before = toWorld(sx, sy);
camera.zoom = clamp(camera.zoom * factor, ZOOM_MIN, ZOOM_MAX);
camera.x = before.x - (sx - width / 2) / camera.zoom;
camera.y = before.y - (sy - height / 2) / camera.zoom;
requestDraw();
}
function onWheel(event) {
event.preventDefault();
autoFit = false;
cameraTween = null;
inertia = null;
const p = localPoint(event);
// Щипок на тачпаде приходит как wheel с ctrlKey и мелким шагом.
const k = event.ctrlKey ? 0.01 : 0.0016;
zoomAt(Math.exp(-event.deltaY * k), p.x, p.y);
}
function zoomBy(factor) {
autoFit = false;
const pad = insets();
const sx = width / 2;
const sy = pad.top + (height - pad.top - pad.bottom) / 2;
const before = toWorld(sx, sy);
const zoom = clamp(camera.zoom * factor, ZOOM_MIN, ZOOM_MAX);
setCamera({ x: before.x - (sx - width / 2) / zoom, y: before.y - (sy - height / 2) / zoom, zoom }, true);
}
// ---- подписки ----------------------------------------------------------------------------
const resizeObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(() => resize()) : null;
resizeObserver?.observe(stage);
window.addEventListener('resize', resize);
const themeObserver = new MutationObserver(() => refreshColors());
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'style', 'class'] });
const colorScheme = window.matchMedia?.('(prefers-color-scheme: dark)');
colorScheme?.addEventListener?.('change', refreshColors);
const onContextMenu = (event) => event.preventDefault();
// После касания браузер досылает «клик» туда, где был палец. Карточка человека или группы
// появляется как раз внизу, под пальцем, – и клик нажимал её кнопку («Написать», чип
// соседней группы). Карте клик не нужен (всё на pointer-событиях), поэтому гасим его.
const onTouchEnd = (event) => { if (event.cancelable) event.preventDefault(); };
canvas.addEventListener('pointerdown', onPointerDown);
canvas.addEventListener('pointermove', onPointerMove);
canvas.addEventListener('pointerup', onPointerUp);
canvas.addEventListener('pointercancel', onPointerUp);
canvas.addEventListener('pointerleave', onPointerLeave);
canvas.addEventListener('wheel', onWheel, { passive: false });
canvas.addEventListener('contextmenu', onContextMenu);
canvas.addEventListener('touchend', onTouchEnd, { passive: false });
resize();
refreshColors();
const api = {
setGraph,
setFilter,
getPositions,
select,
// Выбрать остров и/или подсветить людей (остальные приглушаются): members – кого
// подсветить (по умолчанию – люди острова; интерес подсвечивает читателей по всей карте);
// reveal – показать подсвеченных целиком.
selectGroup: (id, { reveal = false, members = null } = {}) => {
const item = guides?.kind === 'islands' ? guides.items.find((row) => row.key === id) : null;
selectedGroup = item ? item.key : '';
const set = members ? new Set([...members].filter((one) => nodes.has(one))) : (item ? new Set(item.members) : null);
focusSet = set && set.size ? set : null;
selectedGroupIsFocus = Boolean(item && !members);
if (focusSet && reveal) fitCamera({ only: focusSet });
markDirty();
},
// Найти человека на карте: выбрать и подвести камеру поближе.
reveal: (id) => { if (nodes.has(id)) { select(id); revealNode(id, { minZoom: 1 }); } },
// Сдвинуть карту, только если точка ушла под панели (карточку, нижнее меню).
ensureVisible: (id) => revealNode(id, { minZoom: 0 }),
fit: (animate = true) => fitCamera({ animate }),
// Положение камеры – чтобы при возврате на экран («назад» из профиля) карта стояла как была.
// auto – карта была вписана целиком и её не трогали: тогда при возврате её надо вписать
// заново (данные могли догрузиться), а не ставить старое положение.
getView: () => ({ x: camera.x, y: camera.y, zoom: camera.zoom, auto: autoFit }),
setView: (view) => {
if (!view || !Number.isFinite(view.x) || !Number.isFinite(view.y) || !Number.isFinite(view.zoom)) return;
pendingFit = false;
autoFit = false;
setCamera({ x: view.x, y: view.y, zoom: clamp(view.zoom, ZOOM_MIN, ZOOM_MAX) }, false);
},
zoomBy,
// Панели поверх карты поменяли размер: если карта ещё вписана целиком – вписать заново.
refitIfAuto: () => { if (autoFit && !cameraTween) fitCamera({ animate: false }); },
// Сколько точек сейчас видно после фильтра (без центра).
visibleCount: () => [...nodes.values()].filter((node) => !node.isFocus && node.alphaTarget > 0).length,
// Текущее положение точки относительно центра (для сохранения раскладки целиком).
getPositions: () => new Map([...nodes.values()].map((node) => [node.id, { x: Math.round(node.tx), y: Math.round(node.ty) }])),
// Для автопроверок: что под точкой экрана – подпись/остров или человек.
debugPick: (sx, sy) => ({
overview: overviewIslands(),
island: islandsShown() ? islandAt(sx, sy, '') : '',
caption: captionAt(sx, sy),
node: hitTest(sx, sy)?.id || '',
}),
debugState: () => ({
focusId,
selectedId,
zoom: Number(camera.zoom.toFixed(3)),
camera: { x: Math.round(camera.x), y: Math.round(camera.y) },
animating: Boolean(rafId),
moving: Boolean(moveTween || cameraTween || inertia || lastFrameBusy),
labels: labelsDrawn,
guides: guides ? guides.items.map((item) => `${item.caption}:${item.count}`) : [],
layoutKind: guides?.kind || '',
autoFit,
fitInfo: { box: targetsBounds(), insets: insets(), width, height },
selectedGroup,
highlighted: focusSet ? focusSet.size : 0,
islands: [...islandGeo.values()].map((geo) => {
const top = toScreen(geo.cx, geo.top);
const c = toScreen(geo.cx, geo.cy);
return {
id: geo.item.key, caption: geo.item.caption, count: geo.item.count, color: geo.item.color, sx: Math.round(top.x), sy: Math.round(top.y),
cx: Math.round(c.x), cy: Math.round(c.y), r: Math.round(geo.r * camera.zoom),
};
}),
captions: captionHits.map((hit) => ({ ...hit })),
bridges: [...crossCounts.entries()].map(([key, count]) => `${key}:${count}`),
nodes: [...nodes.values()].map((node) => {
const s = toScreen(node.x, node.y);
return {
id: node.id, x: Math.round(node.x), y: Math.round(node.y), sx: Math.round(s.x), sy: Math.round(s.y), r: node.r,
alpha: Number(node.alpha.toFixed(2)), manual: Boolean(node.manual), group: groupOfNode.get(node.id) || '',
};
}),
edges: edges.length,
links: edges.map((edge) => [edge.a, edge.b]),
tiers: Object.fromEntries([...nodes.values()].map((node) => [node.id, Number(node.data.tier) || 1])),
}),
destroy() {
if (destroyed) return;
destroyed = true;
clearLongPress();
if (rafId) cancelAnimationFrame(rafId);
if (hoverFrame) cancelAnimationFrame(hoverFrame);
rafId = 0;
resizeObserver?.disconnect();
themeObserver.disconnect();
window.removeEventListener('resize', resize);
colorScheme?.removeEventListener?.('change', refreshColors);
canvas.remove();
backCanvas.remove();
probe.remove();
},
};
// Для автопроверок: состояние карты можно прочитать из DOM, не вмешиваясь в работу.
canvas.netDebugState = api.debugState;
canvas.netDebugPick = api.debugPick;
return api;
}