Files
SHiNE-server/shine-UI/js/pages/network/graph-canvas.js
T
q 3f05806563 Связи: открытие карты без вспышки подписей
Пока точки разлетаются от центра, подписи людей и колец групп не рисуются (раньше первые
~300 мс вспыхивал клубок налезающих имён), после остановки – мягко проявляются за 0,2 с.
Если перестройка ничего не сдвинула (например, изменилась заметка), подписи не мигают.
Подпись кольца под панелью чипов не рисуется.
2026-10-13 04:13:06 +03:00

2008 lines
87 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 раз в секунду), верхний – нити, точки и подписи (только когда что-то изменилось).
// Мелкие на экране точки рисуются простыми кружками без картинок; подписи не налезают друг
// на друга – каждая занимает место, только если оно свободно.
//
// Раскладка считается сразу до конца (без живой физики) и проигрывается одной плавной
// анимацией. Знакомые между собой люди ставятся рядом на кольцах, поэтому нити между ними
// короткие, а не клубок через всю карту. Уже стоящие точки при добавлении новых не сдвигаются,
// перетащенные вручную остаются там, куда их положили.
//
// Модель: { focusId, nodes: [{ id, login, name, firstName, lastName, avatar, relationType,
// shining, official, tier, parentId, mark, hasNote }], edges: [{ a, b, type, mutual }] }.
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';
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 SECTOR_CAPTION = { family: 'Семья', close_friend: 'Близкие', friend: 'Друзья', contact: 'Контакты' };
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 placeSectors(list, out, seed, stretch, preferred) {
const groups = GROUP_ORDER
.map((group) => {
const items = list.filter((node) => groupOf(node) === group);
if (preferred) items.sort((a, b) => (preferred.get(a.id) ?? 0) - (preferred.get(b.id) ?? 0) || compareByName(a, b));
else items.sort(compareByName);
return { group, items };
})
.filter((row) => row.items.length);
// Маленькой группе – хотя бы десятая часть круга, иначе она вытягивается в одну «спицу».
const totalCount = groups.reduce((sum, row) => sum + row.items.length, 0);
const weightOf = (row) => Math.max(2, row.items.length, totalCount * 0.1);
const weightSum = groups.reduce((sum, row) => sum + weightOf(row), 0);
const gap = groups.length > 1 ? 0.22 : 0;
let angle = -Math.PI / 2 - (hash01(`${seed}|sectors`) - 0.5) * 0.6;
const sectors = [];
for (const row of groups) {
const span = (Math.PI * 2 - gap * groups.length) * (weightOf(row) / weightSum);
let radius = 120;
let placed = 0;
while (placed < row.items.length) {
const capacity = Math.max(1, Math.floor((span * radius) / 70));
const count = Math.min(capacity, row.items.length - placed);
for (let i = 0; i < count; i += 1) {
const a = angle + span * ((i + 0.5) / count);
out.set(row.items[placed + i].id, { x: Math.cos(a) * radius * stretch.x, y: Math.sin(a) * radius * stretch.y });
}
placed += count;
radius += 72;
}
sectors.push({ key: row.group, caption: SECTOR_CAPTION[row.group], count: row.items.length, angle: angle + span / 2, outer: radius - 72 });
angle += span + gap;
}
return sectors;
}
// Друзья друзей – веером «наружу» от того, через кого они пришли.
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 – подписи групп для фона (кольца или сектора).
*/
export function computeLayout({ focusId, nodes, edges, fixed = new Map(), mode = 'rings', stretch = { x: 1, y: 1 } }) {
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 preferred = communityAngles(allFirst, nodes, edges, focusId, focusId);
const firstLevel = allFirst.filter((node) => !pos.has(node.id));
const ringSlots = new Map();
let guides = null;
if (firstLevel.length) {
guides = mode === 'groups'
? { kind: 'sectors', stretch, items: placeSectors(firstLevel, ringSlots, focusId, stretch, preferred) }
: { kind: 'rings', stretch, items: placeRings(firstLevel, ringSlots, focusId, stretch, preferred) };
}
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 }) экранные поля, занятые панелями поверх карты
*/
export function createGraphCanvas({ stage, onSelect, onNodeMoved, getInsets } = {}) {
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 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; // когда точки встали: подписи проявляются после этого
// ---- цвета -------------------------------------------------------------------------------
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);
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 && 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;
}
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;
if (dirty || busy) {
dirty = false;
spritesPending = drawFront();
}
const breathing = !reducedMotion?.matches && hasVisibleShining();
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;
}
return alpha;
}
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?.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) {
let p;
if (guides.kind === 'rings') p = toScreen(anchor.x, anchor.y - (item.to + 32) * stretch.y);
else {
const r = item.outer + 54;
p = toScreen(anchor.x + Math.cos(item.angle) * r * stretch.x, anchor.y + Math.sin(item.angle) * r * 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();
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,
};
}
// Нити рисуются пачками одного вида: сотни отдельных штрихов со сменой пунктира – это
// и была главная цена кадра на «друзьях друзей».
function drawEdges(inView, widthScale) {
const zoom = camera.zoom;
const crowd = edges.length > 120;
// Когда известно, кто с кем знаком, «спицы» к центру почти прячем: кольца и так
// показывают связь с центром, а рисунок знакомств за спицами не виден.
const cross = edges.reduce((sum, edge) => sum + (edge.a !== focusId && edge.b !== focusId ? 1 : 0), 0);
const quietSpokes = cross > 40;
const batches = new Map();
for (const edge of edges) {
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;
const incident = Boolean(selectedId) && (edge.a === selectedId || edge.b === selectedId);
if (selectDim > 0 && selectedId && !incident) alpha *= 1 - selectDim * 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;
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;
// Значки поверх точек: от 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();
drawGuideCaptions(placed.reserve);
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) {
let minX = Infinity; let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity;
nodes.forEach((node) => {
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 };
// Внешнее кольцо групп с подписью сверху тоже должно попасть в кадр.
const anchor = nodes.get(focusId);
if (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 } = {}) {
// Экран ещё не встроен в страницу и не знает своих размеров – впишем, когда узнает.
if (width <= 1 || height <= 1) {
pendingFit = true;
return;
}
pendingFit = false;
const box = targetsBounds();
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 } = {}) {
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 });
}
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 });
// Подписи групп – от полной раскладки; при добавлении новых людей прежние остаются.
if (layout.guides && (relayout || focusChanged || !guides)) guides = layout.guides;
else if (!layout.guides && (relayout || focusChanged)) guides = null;
if (guides) {
// Подписи групп считают всех, кто сейчас в группе, а не только новых.
const counts = new Map();
nodes.forEach((node) => {
if (node.isFocus || (Number(node.data.tier) || 1) > 1) return;
const key = guides.kind === 'rings' ? RING_BAND[groupOf(node.data)] : 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 });
markDirty();
}
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;
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;
// Захват может не сработать (указатель уже отпущен) – жест тогда просто идёт без него.
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 node = 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, 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; });
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 node = hitTest(hoverPoint.x, hoverPoint.y);
const next = node ? node.id : '';
canvas.classList.toggle('is-over-node', Boolean(node));
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.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; });
if (current.moved) {
node.manual = true;
onNodeMoved?.(node.data, { x: Math.round(node.tx), y: Math.round(node.ty) });
}
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();
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) {
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();
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);
resize();
refreshColors();
const api = {
setGraph,
setFilter,
select,
// Найти человека на карте: выбрать и подвести камеру поближе.
reveal: (id) => { if (nodes.has(id)) { select(id); revealNode(id, { minZoom: 1 }); } },
// Сдвинуть карту, только если точка ушла под панели (карточку, нижнее меню).
ensureVisible: (id) => revealNode(id, { minZoom: 0 }),
fit: (animate = true) => fitCamera({ animate }),
// Положение камеры – чтобы при возврате на экран («назад» из профиля) карта стояла как была.
getView: () => ({ x: camera.x, y: camera.y, zoom: camera.zoom }),
setView: (view) => {
if (!view || !Number.isFinite(view.x) || !Number.isFinite(view.y) || !Number.isFinite(view.zoom)) return;
pendingFit = false;
setCamera({ x: view.x, y: view.y, zoom: clamp(view.zoom, ZOOM_MIN, ZOOM_MAX) }, false);
},
zoomBy,
// Сколько точек сейчас видно после фильтра (без центра).
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) }])),
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}`) : [],
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) };
}),
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;
return api;
}