Files
SHiNE-server/shine-UI/js/pages/network/graph-canvas.js
T
q b9cbbb857b UI: личные чаты (поиск, медиа, «без звука», закреп) и новая карта связей
Личные сообщения:
- поиск по переписке с подсветкой, переход к дате по календарю;
- экран «Медиа и файлы» (/chat/<login>/media);
- «без звука» и закрепление чатов (на устройстве), push от заглушённых не показывается;
- новая нижняя панель ввода, круглый спиннер истории, медиа-карусель;
- история загружается в ~16 раз быстрее: ключ расшифровки достаётся один раз на страницу;
- исправлены прозрачные окна подтверждения в чате.

Связи:
- карта переписана на canvas (graph-canvas.js вместо force-graph.js): плавная анимация
  без дёрганья, панорама, масштаб щипком/колесом/кнопками, перетаскивание людей;
- ручная раскладка и режимы «По близости»/«По группам» запоминаются на устройстве;
- цвет нити – тип связи, пунктир – связь с одной стороны, аура только у сияющих;
- карточка человека: раскрыть связи на месте, в центр, профиль, написать, заметка;
- «Недавние» заменены раскрытием связей; фильтр «Заметки».

Личные заметки о людях (текст и цветная метка, только на устройстве) – на карте и в профиле.
2026-10-12 23:27:14 +03:00

1248 lines
51 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 готовых
// картинок и штрихи линий, а кадры рисуются только пока что-то движется.
//
// Раскладка считается сразу до конца (без живой физики) и проигрывается одной плавной
// анимацией: поэтому точки не «доезжают» и не дёргаются после остановки. Уже стоящие точки
// при добавлении новых не сдвигаются, а перетащенные вручную остаются там, куда их положили.
//
// Модель: { focusId, nodes: [{ id, login, name, 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.2;
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 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 MAX_LABEL_CHARS = 18;
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');
}
// --- Раскладка ------------------------------------------------------------------------------
// Первый круг «по близости»: семья и близкие ближе всех, дальше друзья, снаружи контакты.
// Каждая группа занимает своё кольцо (или несколько), соседние кольца повёрнуты друг к другу.
// Семья и близкие друзья – один «близкий круг» и делят кольцо.
const RING_BAND = { family: 0, close_friend: 0, friend: 1, contact: 2 };
function placeRings(list, out, seed) {
const bandOf = (node) => RING_BAND[groupOf(node)];
const ordered = [...list].sort((a, b) => bandOf(a) - bandOf(b) || GROUP_ORDER.indexOf(groupOf(a)) - GROUP_ORDER.indexOf(groupOf(b)) || compareByName(a, b));
let radius = 100;
let ring = 0;
let index = 0;
while (index < ordered.length) {
const band = bandOf(ordered[index]);
const sameGroup = [];
while (index < ordered.length && bandOf(ordered[index]) === band) sameGroup.push(ordered[index++]);
let start = 0;
while (start < sameGroup.length) {
const capacity = Math.max(3, Math.floor((Math.PI * 2 * radius) / 74));
const count = Math.min(capacity, sameGroup.length - start);
const phase = hash01(`${seed}|ring${ring}`) * Math.PI * 2;
for (let i = 0; i < count; i += 1) {
const angle = phase + (i / count) * Math.PI * 2;
out.set(sameGroup[start + i].id, { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius });
}
start += count;
radius += 64;
ring += 1;
}
}
}
// Первый круг «по группам»: каждой группе свой сектор, внутри сектора – дуги от центра наружу.
function placeSectors(list, out, seed) {
const groups = GROUP_ORDER
.map((group) => ({ group, items: list.filter((node) => groupOf(node) === group).sort(compareByName) }))
.filter((row) => row.items.length);
const weightSum = groups.reduce((sum, row) => sum + Math.max(2, row.items.length), 0);
const gap = groups.length > 1 ? 0.22 : 0;
let angle = -Math.PI / 2 - (hash01(`${seed}|sectors`) - 0.5) * 0.6;
for (const row of groups) {
const span = (Math.PI * 2 - gap * groups.length) * (Math.max(2, row.items.length) / 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, y: Math.sin(a) * radius });
}
placed += count;
radius += 72;
}
angle += span + gap;
}
}
// Друзья друзей – веером «наружу» от того, через кого они пришли.
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;
}
}
/**
* Считает итоговые координаты. focus всегда в (0, 0).
* fixed – точки, которые нельзя двигать (ручные и уже стоящие на карте).
*/
export function computeLayout({ focusId, nodes, edges, fixed = new Map(), mode = 'rings' }) {
const pos = new Map();
const locked = new Set();
pos.set(focusId, { x: 0, y: 0 });
locked.add(focusId);
for (const [id, point] of fixed) {
if (id === focusId || !nodes.some((node) => node.id === id)) continue;
pos.set(id, { x: point.x, y: point.y });
locked.add(id);
}
const byId = new Map(nodes.map((node) => [node.id, node]));
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 firstLevel = nodes.filter((node) => node.id !== focusId && (Number(node.tier) || 1) <= 1 && !pos.has(node.id));
const ringSlots = new Map();
if (mode === 'groups') placeSectors(firstLevel, ringSlots, focusId);
else placeRings(firstLevel, ringSlots, focusId);
ringSlots.forEach((point, id) => pos.set(id, point));
// Глубже – по уровням, чтобы родитель всегда был размещён раньше детей.
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 all = 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),
}));
for (let iter = 0; iter < 90; iter += 1) {
let moved = false;
for (let i = 0; i < all.length; i += 1) {
const a = all[i];
for (let j = i + 1; j < all.length; j += 1) {
const b = all[j];
if (!a.free && !b.free) 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 (a.free && 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 if (a.free) {
a.p.x -= dx * push; a.p.y -= dy * push;
} else {
b.p.x += dx * push; b.p.y += dy * push;
}
moved = true;
}
}
for (const row of all) {
if (!row.free) continue;
const anchor = anchors.get(row.id);
row.p.x += (anchor.x - row.p.x) * 0.04;
row.p.y += (anchor.y - row.p.y) * 0.04;
}
if (!moved && iter > 4) break;
}
}
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 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 canvas = document.createElement('canvas');
canvas.className = 'net-canvas';
canvas.setAttribute('aria-hidden', 'true');
const ctx = canvas.getContext('2d');
const probe = document.createElement('span');
probe.className = 'net-color-probe';
stage.append(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 selectedId = '';
let filterPred = null;
let colors = null;
let fontFamily = 'sans-serif';
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 lastDrawAt = 0;
let selectDim = 0; // 0..1: насколько приглушены остальные при выбранной точке
let pendingFit = 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;
colors = {
dark,
background,
surface: readColor('--surface', '#1c1f27'),
text: readColor('--text-primary', '#f1f1f5'),
textSecondary: readColor('--text-secondary', '#a8abb8'),
accent: readColor('--accent', '#b8aef5'),
shining: readColor('--rel-shining', '#68d8ff'),
edge: {
family: dark ? [255, 138, 101] : [194, 80, 42],
close_friend: readColor('--rel-family', '#f0b82e'),
friend: readColor('--info', '#a8c9f3'),
contact: readColor('--text-secondary', '#a8abb8'),
},
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],
},
};
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 buildSprite(node) {
const scale = Math.min(4, Math.max(2, dpr * 2));
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 * 0.78)}px ${fontFamily}`;
g.textAlign = 'center';
g.textBaseline = 'middle';
g.fillText(node.initials, c, c + inner * 0.04);
}
g.restore();
const ringColor = node.data.shining ? colors.shining : (node.isFocus ? colors.accent : (colors.edge[groupOf(node.data)] || colors.textSecondary));
g.beginPath();
g.arc(c, c, inner + (ring * scale) / 2, 0, Math.PI * 2);
g.lineWidth = ring * scale;
g.strokeStyle = rgba(ringColor, node.data.shining || node.isFocus ? 0.95 : 0.75);
g.stroke();
node.sprite = sprite;
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;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
if (dprChanged) nodes.forEach((node) => { node.sprite = null; });
if (pendingFit && width > 1 && height > 1) fitCamera({ animate: false });
requestDraw();
}
// ---- кадры -------------------------------------------------------------------------------
// dirty – кадр нужен из-за действия (палец, масштаб, новые данные), его нельзя пропускать
// ради экономии, как кадры одной только ауры.
let dirty = true;
function requestDraw() {
dirty = 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) moveTween = null; else 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;
}
const breathing = !reducedMotion?.matches && hasVisibleShining();
// Если двигается только аура – рисуем реже: глазу хватает, а ноутбук не греется.
if (dirty || busy || !breathing || now - lastDrawAt >= AURA_FRAME_MS) {
dirty = false;
draw(now, breathing);
lastDrawAt = now;
}
if (busy || breathing) rafId = requestAnimationFrame(frame);
}
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 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);
ctx.fillStyle = rgba(colors.textSecondary, colors.dark ? 0.16 : 0.22);
ctx.beginPath();
for (let x = offX; x < width; x += s) {
for (let y = offY; y < height; y += s) ctx.rect(x - dot / 2, y - dot / 2, dot, dot);
}
ctx.fill();
}
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 draw(now, breathing) {
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
drawGrid();
const zoom = camera.zoom;
ctx.setTransform(dpr * zoom, 0, 0, dpr * zoom, dpr * (width / 2 - camera.x * zoom), dpr * (height / 2 - camera.y * zoom));
const view = {
left: camera.x - width / 2 / zoom - 80,
right: camera.x + width / 2 / zoom + 80,
top: camera.y - height / 2 / zoom - 80,
bottom: camera.y + height / 2 / zoom + 80,
};
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;
// Нити.
ctx.lineCap = 'round';
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 = selectedId && (edge.a === selectedId || edge.b === selectedId);
if (selectDim > 0 && selectedId && !incident) alpha *= 1 - selectDim * 0.8;
const g = edgeGeometry(a, b, edge.key);
if (g.tooShort) continue;
const type = EDGE_WIDTH[edge.type] ? edge.type : 'contact';
const base = type === 'contact' ? 0.5 : 0.85;
ctx.strokeStyle = rgba(colors.edge[type], base * alpha);
ctx.lineWidth = EDGE_WIDTH[type] * widthScale * (incident ? 1.5 : 1);
ctx.setLineDash(edge.mutual ? [] : [5 * widthScale, 4 * widthScale]);
ctx.beginPath();
ctx.moveTo(g.x1, g.y1);
ctx.quadraticCurveTo(g.cx, g.cy, g.x2, g.y2);
ctx.stroke();
}
ctx.setLineDash([]);
// Точки: глубже – раньше, центр и выбранная – поверх всех.
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 breath = breathing ? 0.5 + 0.5 * Math.sin((now / AURA_PERIOD_MS) * Math.PI * 2) : 0.6;
for (const node of order) {
if (!node.data.shining) continue;
const alpha = nodeAlpha(node);
const size = node.r * (2.9 + breath * 0.35);
ctx.globalAlpha = alpha * (0.75 + breath * 0.25);
ctx.drawImage(getAuraSprite(), node.x - size / 2, node.y - size / 2, size, size);
}
ctx.globalAlpha = 1;
// Подписи друзей друзей прячутся раньше: на обзоре их слишком много и они мельче.
const labelScreenMin = { 1: 5.5, 2: 8.5, 3: 8.5 };
for (const node of order) {
const alpha = nodeAlpha(node);
if (!node.sprite) buildSprite(node);
ctx.globalAlpha = alpha;
const s = node.spriteSize;
ctx.drawImage(node.sprite, node.x - s / 2, node.y - s / 2, s, s);
if (node.id === selectedId) {
ctx.beginPath();
ctx.arc(node.x, node.y, node.r + 5, 0, Math.PI * 2);
ctx.lineWidth = 2 / zoom;
ctx.strokeStyle = rgba(colors.accent, 0.95);
ctx.stroke();
}
if (node.data.official) drawOfficialBadge(node);
if (node.data.mark || node.data.hasNote) drawNoteMark(node);
const tier = clamp(Number(node.data.tier) || 1, 1, 3);
const fontPx = node.isFocus ? LABEL_FONT.focus : LABEL_FONT[tier];
if (fontPx * zoom >= labelScreenMin[tier] || node.isFocus || node.id === selectedId) drawLabel(node, fontPx);
}
ctx.globalAlpha = 1;
}
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 drawLabel(node, fontPx) {
const weight = node.isFocus ? 700 : 500;
ctx.font = `${weight} ${fontPx}px ${fontFamily}`;
if (!node.labelWidth || node.labelFont !== fontPx) {
node.labelWidth = ctx.measureText(node.label).width;
node.labelFont = fontPx;
}
const padX = fontPx * 0.5;
const h = fontPx * 1.5;
const w = node.labelWidth + padX * 2;
const x = node.x - w / 2;
const y = node.y + node.r + (node.isFocus ? 6 : 4);
ctx.fillStyle = rgba(colors.background, colors.dark ? 0.78 : 0.85);
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.9);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(node.label, node.x, y + h / 2 + 0.5);
}
// ---- модель ------------------------------------------------------------------------------
function makeLabel(data) {
const text = String(data.name || data.login || data.id);
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 };
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);
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);
node.labelWidth = 0;
node.initials = buildAvatarInitials({ login: data.login || String(data.id), firstName: data.name || '' }).slice(0, 2);
if (!prev || JSON.stringify(prev.data?.avatar || null) !== JSON.stringify(data.avatar || null) || !node.image) attachAvatar(node);
}
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 = '';
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 layout = computeLayout({ focusId, nodes: [...nodes.values()].map((node) => node.data), edges, fixed, mode });
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;
});
moveTween = reducedMotion?.matches ? null : { t0: now, dur: MOVE_MS };
if (!moveTween) nodes.forEach((node) => { node.x = node.tx; node.y = node.ty; });
if (fit || focusChanged) fitCamera({ animate: !focusChanged || nodes.size > 1 });
requestDraw();
}
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('');
requestDraw();
}
function select(id, { reveal = false } = {}) {
const next = id && nodes.has(id) ? id : '';
selectedId = next;
if (reveal && next) {
const node = nodes.get(next);
const p = toScreen(node.tx, node.ty);
const pad = insets();
if (p.x < 30 || p.x > width - 30 || p.y < pad.top + 30 || p.y > height - pad.bottom - 30) {
setCamera({ x: node.tx, y: node.ty, zoom: Math.max(camera.zoom, 0.8) }, true);
}
}
requestDraw();
}
// ---- жесты -------------------------------------------------------------------------------
const pointers = new Map();
let gesture = null; // { kind: 'pending' | 'pan' | 'drag' | 'pinch', ... }
let lastTap = { at: 0, x: 0, y: 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);
const candidates = [...nodes.values()].filter((node) => node.alphaTarget > 0 && node.alpha > 0.3);
candidates.sort((a, b) => (b.drawRank - a.drawRank) || (b.id === selectedId) - (a.id === selectedId));
let best = null;
let bestD = Infinity;
for (const node of candidates) {
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 && d - node.r < bestD) {
best = node;
bestD = d - node.r;
}
}
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 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;
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
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);
gesture = { kind: 'pending', start: p, last: p, lastAt: performance.now(), node, vx: 0, vy: 0 };
}
function onPointerMove(event) {
if (!pointers.has(event.pointerId)) 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;
if (gesture.node && !gesture.node.isFocus) {
gesture.kind = 'drag';
gesture.node.dragging = true;
gesture.followers = dependentsOf(gesture.node.id);
gesture.followers.forEach((node) => { node.dragging = true; });
const w = toWorld(gesture.start.x, gesture.start.y);
gesture.grab = { x: gesture.node.x - w.x, y: gesture.node.y - w.y };
canvas.classList.add('is-dragging');
} else {
gesture.kind = 'pan';
canvas.classList.add('is-panning');
}
}
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;
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;
}
function onPointerUp(event) {
if (!pointers.has(event.pointerId)) return;
pointers.delete(event.pointerId);
try { canvas.releasePointerCapture?.(event.pointerId); } catch { /* уже отпущен */ }
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') {
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.manual = true;
current.followers?.forEach((f) => { f.dragging = false; });
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);
canvas.addEventListener('pointerdown', onPointerDown);
canvas.addEventListener('pointermove', onPointerMove);
canvas.addEventListener('pointerup', onPointerUp);
canvas.addEventListener('pointercancel', onPointerUp);
canvas.addEventListener('wheel', onWheel, { passive: false });
canvas.addEventListener('contextmenu', (event) => event.preventDefault());
resize();
refreshColors();
const api = {
setGraph,
setFilter,
select,
fit: (animate = true) => fitCamera({ animate }),
zoomBy,
// Текущее положение точки относительно центра (для сохранения раскладки целиком).
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),
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,
}),
destroy() {
if (destroyed) return;
destroyed = true;
if (rafId) cancelAnimationFrame(rafId);
rafId = 0;
resizeObserver?.disconnect();
themeObserver.disconnect();
window.removeEventListener('resize', resize);
colorScheme?.removeEventListener?.('change', refreshColors);
canvas.remove();
probe.remove();
},
};
// Для автопроверок: состояние карты можно прочитать из DOM, не вмешиваясь в работу.
canvas.netDebugState = api.debugState;
return api;
}