SHA256
583 lines
26 KiB
JavaScript
583 lines
26 KiB
JavaScript
// SHiNE Explorer V4: та же модель V3, но две статические Canvas 2D-плоскости.
|
|
// В простое нет requestAnimationFrame, физики, SVG-фильтров и CSS-анимаций.
|
|
import { buildAvatarInitials } from '../../components/avatar-image.js';
|
|
import { state } from '../../state.js';
|
|
import { buildArweaveDataUrl } from '../../services/arweave-file-service.js';
|
|
import { resolvePublicFileUrl } from '../../services/public-file-service.js';
|
|
import { PALETTES, ORB_DIAMETER, clamp, rgba, color, keyOf, edgeGradient, edgeCoreGradient, geometryFor } from './graph-style.js';
|
|
|
|
export const ZOOM_MIN = 0.55;
|
|
export const ZOOM_MAX = 2.2;
|
|
export const DIVE_ZOOM = 1.7;
|
|
|
|
// V4: стеклянная внешняя кромка V3 под непрозрачной фотографией; неон V3 на Canvas.
|
|
const LONG_PRESS_MS = 480;
|
|
const DRAG_SLOP = 8;
|
|
const MAX_SPRITES_PER_FRAME = 16;
|
|
const SPRITE_MEMORY_BUDGET = 96 * 1024 * 1024;
|
|
const GLASS_URL = '/assets/glass_overlay_faithful.png';
|
|
const GLASS_SCALE = 1.19; // V3 .fg-pngorb: размер накладки 119% от узла
|
|
const PHOTO_RATIO = 0.78; // фотография 78% от стеклянного бокса, но рисуется ПОВЕРХ
|
|
const BADGE_URL = '/assets/shine-official-badge.svg?v=2';
|
|
|
|
function makeSpriteCanvas(size) {
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = size; canvas.height = size;
|
|
return canvas;
|
|
}
|
|
|
|
function loadImage(src, notify) {
|
|
const img = new Image();
|
|
img.decoding = 'async';
|
|
img.referrerPolicy = 'no-referrer';
|
|
// Не устанавливаем crossOrigin: не все внешние Arweave/R2 шлюзы возвращают CORS.
|
|
// Canvas используется только для отображения, а не для экспорта/readback.
|
|
img.onload = () => notify(true, img);
|
|
img.onerror = () => notify(false, img);
|
|
img.src = src;
|
|
return img;
|
|
}
|
|
|
|
function avatarSource(node) {
|
|
const direct = String(node.photo || '').trim();
|
|
if (direct) return direct;
|
|
if (typeof node.avatar === 'string') return node.avatar.trim();
|
|
const txId = String(node.avatar?.ar || '').trim();
|
|
if (!txId) return '';
|
|
try {
|
|
return buildArweaveDataUrl({ gateway: state?.entrySettings?.arweaveServer, txId }) || '';
|
|
} catch { return ''; }
|
|
}
|
|
|
|
export function createExplorerCanvasGraph({ stage, model, onCenterTap, onNodeTap, onNodeLongPress, onNodeMoveEnd } = {}) {
|
|
if (!stage) throw new Error('createExplorerCanvasGraph: stage обязателен');
|
|
const edgesCanvas = document.createElement('canvas');
|
|
edgesCanvas.className = 'fg-canvas-v4 fg-canvas-v4--edges';
|
|
edgesCanvas.setAttribute('aria-hidden', 'true');
|
|
const canvas = document.createElement('canvas');
|
|
canvas.className = 'fg-canvas-v4 fg-canvas-v4--nodes';
|
|
canvas.setAttribute('role', 'img');
|
|
const ectx = edgesCanvas.getContext('2d');
|
|
const ctx = canvas.getContext('2d');
|
|
if (!ectx || !ctx) throw new Error('Canvas 2D недоступен');
|
|
stage.append(edgesCanvas, canvas);
|
|
const a11y = document.createElement('div');
|
|
a11y.className = 'fg-a11y';
|
|
a11y.setAttribute('role', 'region');
|
|
stage.append(a11y);
|
|
|
|
let destroyed = false;
|
|
let nodes = [];
|
|
let nodeById = new Map();
|
|
let focusId = '';
|
|
let width = 1, height = 1, dpr = 1;
|
|
let zoom = 1, camX = 0, camY = 0;
|
|
let frame = 0;
|
|
let edgesDirty = true;
|
|
let palette = PALETTES.dark;
|
|
let spriteScale = 1;
|
|
let auraSprite = null;
|
|
const spriteCache = new Map(); // id -> { key, scale, canvas }, меняется только при смене фотографии/LOD
|
|
const photos = new Map(); // id -> { key, image, ready }
|
|
let badge = null, glass = null;
|
|
let badgeReady = false, glassReady = false;
|
|
|
|
const requestDraw = (redrawEdges = true) => {
|
|
if (redrawEdges) edgesDirty = true;
|
|
if (destroyed || frame) return;
|
|
frame = requestAnimationFrame(() => { frame = 0; if (!destroyed) draw(); });
|
|
};
|
|
badge = loadImage(BADGE_URL, (ok) => { badgeReady = ok; requestDraw(false); });
|
|
glass = loadImage(GLASS_URL, (ok) => { glassReady = ok; spriteCache.clear(); requestDraw(false); });
|
|
|
|
function setupPhoto(node) {
|
|
const id = keyOf(node.id);
|
|
const key = JSON.stringify([node.avatar || null, node.photo || '', node.login || '']);
|
|
if (photos.get(id)?.key === key) return;
|
|
const entry = { key, image: null, ready: false };
|
|
photos.set(id, entry);
|
|
spriteCache.delete(id);
|
|
let url = avatarSource(node);
|
|
if (!url && node.avatar?.pr && !node.avatar?.ar) {
|
|
void resolvePublicFileUrl({ pr: String(node.avatar.pr), authorLogin: String(node.login || '') })
|
|
.then((resolved) => { if (!destroyed && photos.get(id) === entry && resolved) start(resolved); })
|
|
.catch(() => {});
|
|
} else if (url) start(url);
|
|
function start(src) {
|
|
entry.image = loadImage(src, (ok, image) => {
|
|
if (destroyed || photos.get(id) !== entry) return;
|
|
entry.ready = ok && image.naturalWidth > 0;
|
|
spriteCache.delete(id);
|
|
requestDraw(false);
|
|
});
|
|
}
|
|
}
|
|
|
|
function makeAura() {
|
|
const c = makeSpriteCanvas(160);
|
|
const a = c.getContext('2d');
|
|
const g = a.createRadialGradient(80, 80, 15, 80, 80, 80);
|
|
g.addColorStop(0, rgba(palette.shine, .50));
|
|
g.addColorStop(.45, rgba(palette.shine, .23));
|
|
g.addColorStop(1, rgba(palette.shine, 0));
|
|
a.fillStyle = g; a.fillRect(0, 0, 160, 160);
|
|
return c;
|
|
}
|
|
|
|
function desiredSpriteScale() {
|
|
const need = Math.max(1, dpr * zoom * 1.15);
|
|
// Подготавливаем всех пользователей, поэтому масштаб также ограничен общим бюджетом памяти.
|
|
const bytesPerScale = Math.max(1, nodes.length) * (ORB_DIAMETER * GLASS_SCALE) ** 2 * 4;
|
|
const budgetScale = Math.max(1, Math.sqrt(SPRITE_MEMORY_BUDGET / bytesPerScale));
|
|
const maxScale = Math.min(8, budgetScale);
|
|
let candidate = 1;
|
|
while (candidate * 2 <= maxScale && candidate < need) candidate *= 2;
|
|
return candidate;
|
|
}
|
|
|
|
function spriteKey(node, photo) {
|
|
return JSON.stringify([node.id, node.name, node.login, photo?.key, photo?.ready, glassReady, palette === PALETTES.light]);
|
|
}
|
|
|
|
function buildSprite(node) {
|
|
const photo = photos.get(keyOf(node.id));
|
|
const key = spriteKey(node, photo);
|
|
// Единый спрайт: стеклянная кромка снизу, полностью непрозрачный аватар сверху.
|
|
// Отдельного красного/синего кольца категории НЕ рисуем.
|
|
const side = Math.max(2, Math.ceil(ORB_DIAMETER * GLASS_SCALE * spriteScale));
|
|
const sprite = makeSpriteCanvas(side);
|
|
const g = sprite.getContext('2d');
|
|
const center = side / 2;
|
|
const photoRadius = center * PHOTO_RATIO;
|
|
const diameter = photoRadius * 2;
|
|
|
|
// Непрозрачный фон между фотографией и стеклянным краем:
|
|
// неон нижнего canvas не просвечивает через стеклянную сферу.
|
|
g.fillStyle = palette.bg;
|
|
g.beginPath(); g.arc(center, center, center - .5 * spriteScale, 0, Math.PI * 2); g.fill();
|
|
if (glassReady && glass?.naturalWidth) {
|
|
g.drawImage(glass, 0, 0, side, side);
|
|
} else {
|
|
// Минимальный резервный стеклянный край, если файл пока не загрузился.
|
|
g.strokeStyle = rgba(palette.shine, .33);
|
|
g.lineWidth = Math.max(1, spriteScale * 1.2);
|
|
g.beginPath(); g.arc(center, center, center - g.lineWidth * 1.4, 0, 2 * Math.PI); g.stroke();
|
|
}
|
|
|
|
// Фото В ПОСЛЕДНЮЮ ОЧЕРЕДЬ поверх самого стекла, без затенения бликами.
|
|
g.save();
|
|
g.beginPath(); g.arc(center, center, photoRadius, 0, Math.PI * 2); g.clip();
|
|
g.fillStyle = palette.bg;
|
|
g.fillRect(center - photoRadius, center - photoRadius, diameter, diameter);
|
|
if (photo?.ready && photo.image?.naturalWidth) {
|
|
const img = photo.image;
|
|
const crop = Math.min(img.naturalWidth, img.naturalHeight);
|
|
g.drawImage(img, (img.naturalWidth - crop) / 2, (img.naturalHeight - crop) / 2,
|
|
crop, crop, center - photoRadius, center - photoRadius, diameter, diameter);
|
|
} else {
|
|
const initials = buildAvatarInitials({ login: node.login || node.id, firstName: node.name || '' });
|
|
g.fillStyle = palette.text;
|
|
g.textAlign = 'center'; g.textBaseline = 'middle';
|
|
g.font = `600 ${Math.round(side * .24)}px system-ui, sans-serif`;
|
|
g.fillText(initials, center, center, side * .58);
|
|
}
|
|
g.restore();
|
|
|
|
const result = { key, scale: spriteScale, canvas: sprite };
|
|
spriteCache.set(keyOf(node.id), result);
|
|
return result;
|
|
}
|
|
|
|
function screenPoint(node) {
|
|
return { x: width / 2 + camX + node.x * zoom, y: height / 2 + camY + node.y * zoom };
|
|
}
|
|
function nodeScreenPoint(node) {
|
|
const p = screenPoint(node);
|
|
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
|
|
const box = canvas.getBoundingClientRect();
|
|
const rect = { left: box.left + p.x - size / 2, top: box.top + p.y - size / 2,
|
|
width: size, height: size, right: box.left + p.x + size / 2, bottom: box.top + p.y + size / 2 };
|
|
return { x: box.left + p.x, y: rect.top, rect };
|
|
}
|
|
|
|
// Неоновый композит из V3: мягкое размытое поле (16px / blur6),
|
|
// размытая трубка (6px / blur2), сверху чёткое светлое ядро (2px).
|
|
// Каждое размытие выполняется ОДИН раз для всех сияющих связей, а не для каждого ребра.
|
|
const flareCanvas = makeSpriteCanvas(1);
|
|
const tubeCanvas = makeSpriteCanvas(1);
|
|
const flareCtx = flareCanvas.getContext('2d');
|
|
const tubeCtx = tubeCanvas.getContext('2d');
|
|
|
|
function drawStroke(g, path, widthPx, strokeStyle, alpha, dash = null) {
|
|
g.save();
|
|
g.globalAlpha = alpha;
|
|
g.lineWidth = widthPx;
|
|
g.strokeStyle = strokeStyle;
|
|
g.lineCap = 'round';
|
|
g.lineJoin = 'round';
|
|
if (dash) g.setLineDash(dash.map((v) => v * zoom));
|
|
g.stroke(path);
|
|
g.restore();
|
|
}
|
|
|
|
function drawNormalEdge(g, path, geo, ref) {
|
|
// V3: две аккуратные нити вместо двух тяжёлых цветных полос.
|
|
const gradient = edgeGradient(g, geo, ref, palette);
|
|
const strength = clamp(Number(ref.strength) || .5, 0, 1);
|
|
drawStroke(g, path, (2.6 + strength * 1.4) * zoom, gradient, .22);
|
|
drawStroke(g, path, 1.2 * zoom, gradient, .70);
|
|
}
|
|
|
|
function edgePath(geo, shining, directed) {
|
|
const path = new Path2D();
|
|
path.moveTo(geo.x1, geo.y1);
|
|
if (shining && !directed) {
|
|
const dx = geo.x2 - geo.x1, dy = geo.y2 - geo.y1;
|
|
const perpX = -geo.uy, perpY = geo.ux;
|
|
const amp = Math.min(13, 5 + Math.hypot(dx, dy) * .05);
|
|
const bowX = geo.cpx - geo.mx, bowY = geo.cpy - geo.my;
|
|
path.bezierCurveTo(geo.x1 + dx / 3 + bowX + perpX * amp,
|
|
geo.y1 + dy / 3 + bowY + perpY * amp,
|
|
geo.x1 + dx * 2 / 3 + bowX - perpX * amp,
|
|
geo.y1 + dy * 2 / 3 + bowY - perpY * amp,
|
|
geo.x2, geo.y2);
|
|
} else path.quadraticCurveTo(geo.cpx, geo.cpy, geo.x2, geo.y2);
|
|
return path;
|
|
}
|
|
|
|
function paintEdges() {
|
|
// Вспомогательные холсты создаются один раз и переиспользуются; анимации нет.
|
|
for (const g of [flareCtx, tubeCtx]) {
|
|
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
g.clearRect(0, 0, width, height);
|
|
}
|
|
const origin = { x: width / 2 + camX, y: height / 2 + camY };
|
|
const shiningEdges = [];
|
|
for (const node of nodes) {
|
|
for (const ref of node.edgeParents || []) {
|
|
const parent = nodeById.get(keyOf(ref?.id));
|
|
if (!parent || parent === node) continue;
|
|
const geo = geometryFor(parent, node, zoom, origin, origin);
|
|
const shining = Boolean(node.shining && parent.shining);
|
|
const directed = ref.mutual === false;
|
|
const path = edgePath(geo, shining, directed);
|
|
if (!shining) {
|
|
drawNormalEdge(ectx, path, geo, ref);
|
|
continue;
|
|
}
|
|
shiningEdges.push({ path, geo, ref, directed });
|
|
const dash = directed ? [20, 4] : null; // V3: только направленная сияющая связь пунктирная.
|
|
drawStroke(flareCtx, path, 16 * zoom, edgeGradient(flareCtx, geo, ref, palette), .42, dash);
|
|
drawStroke(tubeCtx, path, 6 * zoom, edgeGradient(tubeCtx, geo, ref, palette), .85, dash);
|
|
}
|
|
}
|
|
if (!shiningEdges.length) return;
|
|
// screen-подсветка и двухслойное размытие соответствуют CSS .fg-plasma-* в V3.
|
|
// Нет резкой непрозрачной 14px-полосы — только светлая узкая сердцевина.
|
|
ectx.save();
|
|
ectx.globalCompositeOperation = 'screen';
|
|
ectx.filter = `blur(${(6 * zoom).toFixed(2)}px)`;
|
|
ectx.drawImage(flareCanvas, 0, 0, width, height);
|
|
ectx.filter = `blur(${(2 * zoom).toFixed(2)}px)`;
|
|
ectx.drawImage(tubeCanvas, 0, 0, width, height);
|
|
ectx.filter = 'none';
|
|
for (const { path, geo, ref, directed } of shiningEdges) {
|
|
drawStroke(ectx, path, 2 * zoom, edgeCoreGradient(ectx, geo, ref, palette), 1,
|
|
directed ? [20, 4] : null);
|
|
}
|
|
ectx.restore();
|
|
}
|
|
|
|
function paintNodes() {
|
|
if (!auraSprite) auraSprite = makeAura();
|
|
let built = 0, needsBuild = false;
|
|
// Весь свет под всеми аватарками, а не поверх соседних фотографий.
|
|
for (const node of nodes) {
|
|
if (!node.shining) continue;
|
|
const { x, y } = screenPoint(node);
|
|
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom * 1.95;
|
|
ctx.drawImage(auraSprite, x - size / 2, y - size / 2, size, size);
|
|
}
|
|
// Все пользователи рисуются, в том числе за пределами экрана — по решению для V4.
|
|
for (const node of nodes) {
|
|
const { x, y } = screenPoint(node);
|
|
const size = ORB_DIAMETER * (node.visualSmall ? .5 : 1) * zoom;
|
|
const id = keyOf(node.id);
|
|
const cached = spriteCache.get(id);
|
|
const photo = photos.get(id);
|
|
const currentKey = spriteKey(node, photo);
|
|
let sprite = cached;
|
|
if (!cached || cached.key !== currentKey || cached.scale !== spriteScale) {
|
|
if (built < MAX_SPRITES_PER_FRAME) { sprite = buildSprite(node); built += 1; }
|
|
else needsBuild = true;
|
|
}
|
|
if (sprite) {
|
|
const imageSize = size * GLASS_SCALE;
|
|
ctx.drawImage(sprite.canvas, x - imageSize / 2, y - imageSize / 2, imageSize, imageSize);
|
|
} else {
|
|
ctx.fillStyle = rgba(color(palette, node.relationType), .8);
|
|
ctx.beginPath(); ctx.arc(x, y, size / 2, 0, 2 * Math.PI); ctx.fill();
|
|
}
|
|
if (badgeReady && node.official) {
|
|
const badgeSize = Math.max(12, size * .32);
|
|
ctx.drawImage(badge, x - size / 2, y + size / 2 - badgeSize, badgeSize, badgeSize);
|
|
}
|
|
}
|
|
// Подписи V2: компактные округлённые плашки без толстого контура текста.
|
|
// Приоритет центра и близких, защита от пересечений и резервная позиция сверху.
|
|
ctx.save();
|
|
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
|
const fontFamily = getComputedStyle(stage).fontFamily || 'sans-serif';
|
|
const occupied = nodes.map((node) => {
|
|
const { x, y } = screenPoint(node);
|
|
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
|
|
return { left: x - r - 2, right: x + r + 2, top: y - r - 2, bottom: y + r + 2 };
|
|
});
|
|
const collides = (r) => occupied.some((other) =>
|
|
r.left < other.right && r.right > other.left && r.top < other.bottom && r.bottom > other.top);
|
|
const priority = (node) => node.id === focusId ? 0 :
|
|
(node.relationType === 'close_friend' ? 1 : node.relationType === 'friend' ? 2 : 3) +
|
|
Math.max(0, Number(node.distance) || 0) * 5;
|
|
const ordered = [...nodes].sort((a, b) => priority(a) - priority(b) || a.id.localeCompare(b.id));
|
|
const MAX_LABEL_CHARS = 18;
|
|
for (const node of ordered) {
|
|
const { x, y } = screenPoint(node);
|
|
const isFocus = node.id === focusId;
|
|
const r = ORB_DIAMETER * (node.visualSmall ? .25 : .5) * zoom;
|
|
if (!isFocus && r < 6.5) continue;
|
|
const original = String(node.name || node.login || node.id).trim();
|
|
const words = original.split(/\s+/).filter(Boolean);
|
|
// Вторая версия показывает «Имя Ф.» для обычных участников и полное имя центра.
|
|
const short = !isFocus && words.length >= 2 ? `${words[0]} ${words[1][0]}.` : original;
|
|
const label = short.length > MAX_LABEL_CHARS ? `${short.slice(0, MAX_LABEL_CHARS - 1)}…` : short;
|
|
const fontSize = Math.round(clamp((isFocus ? 13 : node.visualSmall ? 10.5 : 12) * zoom,
|
|
isFocus ? 12.5 : node.visualSmall ? 10 : 11, isFocus ? 16 : node.visualSmall ? 13 : 15) * 2) / 2;
|
|
ctx.font = `${isFocus ? 700 : 500} ${fontSize}px ${fontFamily}`;
|
|
const labelW = ctx.measureText(label).width;
|
|
const padX = fontSize * .5;
|
|
const w = labelW + padX * 2;
|
|
const h = Math.round(fontSize * 1.5);
|
|
const gap = isFocus ? 5 : 3;
|
|
let y0 = y + r + gap;
|
|
let bounds = { left: x - w / 2 - 2, right: x + w / 2 + 2, top: y0 - 1, bottom: y0 + h + 1 };
|
|
if (collides(bounds)) {
|
|
const above = y - r - gap - h;
|
|
const alternate = { ...bounds, top: above - 1, bottom: above + h + 1 };
|
|
if (!collides(alternate)) { y0 = above; bounds = alternate; }
|
|
else if (!isFocus) continue;
|
|
}
|
|
occupied.push(bounds);
|
|
const x0 = x - w / 2;
|
|
ctx.fillStyle = palette === PALETTES.light ? 'rgba(230,237,243,.88)' : 'rgba(23,36,49,.82)';
|
|
ctx.beginPath();
|
|
if (ctx.roundRect) ctx.roundRect(x0, y0, w, h, h / 2);
|
|
else ctx.rect(x0, y0, w, h);
|
|
ctx.fill();
|
|
ctx.fillStyle = palette.text;
|
|
ctx.fillText(label, x, y0 + h / 2 + .5);
|
|
}
|
|
ctx.restore();
|
|
return needsBuild;
|
|
}
|
|
|
|
function draw() {
|
|
if (width <= 0 || height <= 0) return;
|
|
if (edgesDirty) {
|
|
ectx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
ectx.clearRect(0, 0, width, height);
|
|
paintEdges();
|
|
edgesDirty = false;
|
|
}
|
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
ctx.clearRect(0, 0, width, height);
|
|
if (paintNodes()) requestDraw(false);
|
|
}
|
|
|
|
function updateSize() {
|
|
const rect = stage.getBoundingClientRect();
|
|
const w = Math.max(1, Math.round(rect.width || stage.clientWidth || 1));
|
|
const h = Math.max(1, Math.round(rect.height || stage.clientHeight || 1));
|
|
const ratio = clamp(window.devicePixelRatio || 1, 1, 2.5);
|
|
if (w === width && h === height && ratio === dpr) return;
|
|
width = w; height = h; dpr = ratio;
|
|
for (const element of [canvas, edgesCanvas, flareCanvas, tubeCanvas]) {
|
|
element.width = Math.ceil(w * dpr); element.height = Math.ceil(h * dpr);
|
|
if (element === canvas || element === edgesCanvas) {
|
|
element.style.width = `${w}px`; element.style.height = `${h}px`;
|
|
}
|
|
}
|
|
const nextScale = desiredSpriteScale();
|
|
if (nextScale !== spriteScale) spriteScale = nextScale;
|
|
requestDraw();
|
|
}
|
|
|
|
function setModel(next) {
|
|
const oldFocus = focusId;
|
|
focusId = keyOf(next?.focusId);
|
|
const seen = new Set();
|
|
nodes = (Array.isArray(next?.nodes) ? next.nodes : []).map((raw) => {
|
|
const id = keyOf(raw.id);
|
|
seen.add(id);
|
|
const node = { ...raw, id, x: Number(raw.layoutX) || 0, y: Number(raw.layoutY) || 0 };
|
|
setupPhoto(node);
|
|
return node;
|
|
});
|
|
nodeById = new Map(nodes.map((n) => [n.id, n]));
|
|
for (const id of photos.keys()) if (!seen.has(id)) { photos.delete(id); spriteCache.delete(id); }
|
|
for (const id of spriteCache.keys()) if (!seen.has(id)) spriteCache.delete(id);
|
|
if (oldFocus && focusId !== oldFocus) { camX = 0; camY = 0; }
|
|
spriteScale = desiredSpriteScale();
|
|
a11y.textContent = `Граф связей: ${nodes.length} пользователей. Центр: ${nodes.find((n) => n.id === focusId)?.name || focusId}.`;
|
|
requestDraw();
|
|
}
|
|
|
|
function updateZoom(next, sx = width / 2, sy = height / 2) {
|
|
const value = clamp(next, ZOOM_MIN, ZOOM_MAX);
|
|
if (Math.abs(value - zoom) < .00001) return;
|
|
const factor = value / zoom;
|
|
camX = sx - width / 2 - (sx - width / 2 - camX) * factor;
|
|
camY = sy - height / 2 - (sy - height / 2 - camY) * factor;
|
|
zoom = value;
|
|
spriteScale = desiredSpriteScale();
|
|
requestDraw();
|
|
}
|
|
|
|
function hitNode(clientX, clientY) {
|
|
const rect = canvas.getBoundingClientRect();
|
|
const sx = clientX - rect.left, sy = clientY - rect.top;
|
|
for (let i = nodes.length - 1; i >= 0; i -= 1) {
|
|
const node = nodes[i];
|
|
const p = screenPoint(node);
|
|
const r = Math.max(8, ORB_DIAMETER / 2 * (node.visualSmall ? .5 : 1) * zoom);
|
|
if (Math.hypot(sx - p.x, sy - p.y) <= r) return node;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const pointers = new Map();
|
|
let gesture = null, pinchDistance = 0, longTimer = 0;
|
|
const clearLong = () => { if (longTimer) window.clearTimeout(longTimer); longTimer = 0; };
|
|
function pointerDown(e) {
|
|
if (e.button !== undefined && e.button !== 0) return;
|
|
e.preventDefault();
|
|
try { canvas.setPointerCapture(e.pointerId); } catch {}
|
|
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
clearLong();
|
|
if (pointers.size >= 2) {
|
|
const pts = [...pointers.values()];
|
|
pinchDistance = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
|
|
gesture = { pinching: true };
|
|
return;
|
|
}
|
|
const node = hitNode(e.clientX, e.clientY);
|
|
gesture = { id: e.pointerId, x: e.clientX, y: e.clientY, camX, camY,
|
|
node, nodeX: node?.x || 0, nodeY: node?.y || 0, moved: false, longFired: false };
|
|
if (node && typeof onNodeLongPress === 'function') {
|
|
longTimer = window.setTimeout(() => {
|
|
if (!gesture || gesture.moved || gesture.pinching || destroyed) return;
|
|
gesture.longFired = true;
|
|
onNodeLongPress(node, nodeScreenPoint(node));
|
|
}, LONG_PRESS_MS);
|
|
}
|
|
}
|
|
function pointerMove(e) {
|
|
if (pointers.has(e.pointerId)) pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
if (pointers.size >= 2 && gesture?.pinching) {
|
|
const pts = [...pointers.values()];
|
|
const dist = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1;
|
|
const rect = canvas.getBoundingClientRect();
|
|
updateZoom(zoom * dist / (pinchDistance || dist), (pts[0].x + pts[1].x) / 2 - rect.left,
|
|
(pts[0].y + pts[1].y) / 2 - rect.top);
|
|
pinchDistance = dist;
|
|
return;
|
|
}
|
|
if (!gesture || gesture.id !== e.pointerId || gesture.longFired) {
|
|
canvas.classList.toggle('is-over-node', Boolean(hitNode(e.clientX, e.clientY)));
|
|
return;
|
|
}
|
|
const dx = e.clientX - gesture.x, dy = e.clientY - gesture.y;
|
|
if (Math.hypot(dx, dy) > DRAG_SLOP) { gesture.moved = true; clearLong(); }
|
|
if (!gesture.moved) return;
|
|
if (gesture.node) {
|
|
gesture.node.x = gesture.nodeX + dx / zoom;
|
|
gesture.node.y = gesture.nodeY + dy / zoom;
|
|
} else { camX = gesture.camX + dx; camY = gesture.camY + dy; }
|
|
requestDraw();
|
|
}
|
|
function pointerUp(e) {
|
|
pointers.delete(e.pointerId);
|
|
clearLong();
|
|
try { canvas.releasePointerCapture(e.pointerId); } catch {}
|
|
if (gesture?.pinching) { if (pointers.size < 2) gesture = null; return; }
|
|
if (!gesture || gesture.id !== e.pointerId) return;
|
|
const completed = gesture;
|
|
gesture = null;
|
|
if (completed.longFired) return;
|
|
if (completed.moved) {
|
|
if (completed.node) onNodeMoveEnd?.(completed.node, { x: completed.node.x, y: completed.node.y });
|
|
return;
|
|
}
|
|
if (!completed.node) return;
|
|
if (completed.node.id === focusId) onCenterTap?.(completed.node, nodeScreenPoint(completed.node));
|
|
else onNodeTap?.(completed.node);
|
|
}
|
|
function onCancel(e) { pointers.delete(e.pointerId); clearLong(); gesture = null; }
|
|
function onWheel(e) {
|
|
e.preventDefault();
|
|
const rect = canvas.getBoundingClientRect();
|
|
updateZoom(zoom * Math.exp(-e.deltaY * .0016), e.clientX - rect.left, e.clientY - rect.top);
|
|
}
|
|
function onContextMenu(e) {
|
|
e.preventDefault();
|
|
const node = hitNode(e.clientX, e.clientY);
|
|
if (node) onNodeLongPress?.(node, nodeScreenPoint(node));
|
|
}
|
|
function onTheme() {
|
|
const next = document.documentElement.dataset.theme === 'light' ? PALETTES.light : PALETTES.dark;
|
|
if (palette === next) return;
|
|
palette = next; spriteCache.clear(); auraSprite = null; requestDraw();
|
|
}
|
|
|
|
canvas.addEventListener('pointerdown', pointerDown);
|
|
canvas.addEventListener('pointermove', pointerMove);
|
|
canvas.addEventListener('pointerup', pointerUp);
|
|
canvas.addEventListener('pointercancel', onCancel);
|
|
canvas.addEventListener('lostpointercapture', onCancel);
|
|
canvas.addEventListener('wheel', onWheel, { passive: false });
|
|
canvas.addEventListener('contextmenu', onContextMenu);
|
|
const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(updateSize) : null;
|
|
observer?.observe(stage);
|
|
window.addEventListener('resize', updateSize);
|
|
const themeObserver = typeof MutationObserver === 'function' ?
|
|
new MutationObserver(onTheme) : null;
|
|
themeObserver?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
|
onTheme();
|
|
updateSize();
|
|
setModel(model);
|
|
|
|
return {
|
|
setModel, nodeScreenPoint,
|
|
getFocusNode: () => nodeById.get(focusId) || null,
|
|
recenter: () => { camX = 0; camY = 0; updateZoom(DIVE_ZOOM); requestDraw(); },
|
|
destroy: () => {
|
|
if (destroyed) return;
|
|
destroyed = true;
|
|
clearLong(); pointers.clear();
|
|
if (frame) cancelAnimationFrame(frame);
|
|
observer?.disconnect(); themeObserver?.disconnect();
|
|
window.removeEventListener('resize', updateSize);
|
|
canvas.removeEventListener('pointerdown', pointerDown);
|
|
canvas.removeEventListener('pointermove', pointerMove);
|
|
canvas.removeEventListener('pointerup', pointerUp);
|
|
canvas.removeEventListener('pointercancel', onCancel);
|
|
canvas.removeEventListener('lostpointercapture', onCancel);
|
|
canvas.removeEventListener('wheel', onWheel);
|
|
canvas.removeEventListener('contextmenu', onContextMenu);
|
|
photos.clear(); spriteCache.clear();
|
|
edgesCanvas.remove(); canvas.remove(); a11y.remove();
|
|
},
|
|
// Диагностика без зависимости от структуры canvas.
|
|
debugState: () => ({ nodeCount: nodes.length, zoom, spriteScale, cachedSprites: spriteCache.size, frameQueued: !!frame }),
|
|
};
|
|
}
|