Связи: подписи островов по месту, карта остаётся вписанной

- Подписи групп: на общем виде (людей не различить) – прямо на острове, как название
  района; когда люди видны – рядом с островом, чтобы их не закрывать.
- Пока карту не трогали, она остаётся вписанной целиком: догрузились знакомства, подписи
  или открылась чужая карта по ссылке – вписывается заново. Первое касание, масштаб или
  выбор человека это выключают. Раньше на чужой карте крайний остров уезжал за край экрана.
- Если групп нет совсем (связи не знакомы между собой, общих подписок нет, город никто не
  указал) – одна подсказка, почему доска пустая.
This commit is contained in:
q
2026-10-13 14:16:44 +03:00
parent 694aaf1f0e
commit 68eec2b28b
4 changed files with 65 additions and 24 deletions
+1 -1
View File
@@ -39,7 +39,7 @@
}());
</script>
<script>
window.__SHINE_BUILD_HASH__ = '20261013160500';
window.__SHINE_BUILD_HASH__ = '20261013170000';
window.__SHINE_CLIENT_VERSION__ = '1.2.10';
</script>
<script>
+25 -6
View File
@@ -528,6 +528,7 @@ export function render({ navigate, route, chrome } = {}) {
// Состав групп поменялся (освежились данные, перенесли человека) – острова перестраиваются;
// своя раскладка не трогается.
const regroup = Boolean(groupsModel && previousGroups && !sameGrouping(previousGroups, groupsModel)) && layout.id !== 'manual';
hintEmptyLens(groupsModel);
engine.setGraph(map, {
manual: layout.manual, mode: layout.mode, relayout: relayout || regroup, fit, groups: groupsModel?.groups || null,
});
@@ -658,12 +659,10 @@ export function render({ navigate, route, chrome } = {}) {
centerLogin = normalizeLogin(graph?.login || clean);
loadError = null;
syncLinksUrl(centerLogin, { push });
const restoring = Boolean(restoreView);
const restoring = Boolean(restoreView) && !restoreView.auto;
renderMap({ fit: !restoring });
if (restoreView) {
engine.setView(restoreView);
restoreView = null;
}
if (restoring) engine.setView(restoreView);
restoreView = null;
if (friendsOfFriends) void expandFriends({ fit: !restoring });
else if (expanded.size) void restoreExpanded();
} catch (error) {
@@ -1182,6 +1181,23 @@ export function render({ navigate, route, chrome } = {}) {
return { ...model, lens: mode, byId: new Map(model.groups.map((group) => [group.id, group])) };
}
// Групп нет совсем (все в «Без компании» / «Без общих подписок» / «Город не указан») – один
// раз на карту объясняем почему, иначе пустая доска выглядит как поломка.
const emptyLensHinted = new Set();
function hintEmptyLens(model) {
if (!model || viewMode !== 'map' || model.groups.some((group) => group.kind !== 'rest')) return;
const key = `${model.lens}|${normKey(centerLogin)}`;
if (emptyLensHinted.has(key)) return;
emptyLensHinted.add(key);
const self = isSelfCenter();
const text = {
companies: self ? 'Компаний пока нет: ваши связи не знакомы между собой' : 'Компаний пока нет: связи этого человека не знакомы между собой',
interests: 'Общих подписок пока нет: никакой канал не читают хотя бы двое',
cities: self ? 'Никто из ваших связей пока не указал город в профиле' : 'Никто из связей этого человека пока не указал город',
}[model.lens];
if (text) showToast(text, { kind: 'info', timeoutMs: 4500 });
}
// Тот же ли состав групп (без учёта их id: компания, получившая название, – та же компания).
function sameGrouping(a, b) {
if (!a || !b || a.lens !== b.lens || a.byPerson.size !== b.byPerson.size) return false;
@@ -2467,7 +2483,10 @@ export function render({ navigate, route, chrome } = {}) {
}
}
document.addEventListener('keydown', onKeydown);
const overlayObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(() => placeOverlays()) : null;
const overlayObserver = typeof ResizeObserver === 'function' ? new ResizeObserver(() => {
placeOverlays();
engine.refitIfAuto();
}) : null;
overlayObserver?.observe(stage);
overlayObserver?.observe(filterBar);
+38 -16
View File
@@ -773,6 +773,9 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
let backDirty = true; // нижний слой надо перерисовать
let lastFrameBusy = false;
let labelsShownAt = 0; // когда точки встали: подписи проявляются после этого
// Карта вписана целиком и человек её ещё не трогал: догрузки (знакомства, подписи, панели)
// вписывают её заново. Первое касание, масштаб или выбор это выключают.
let autoFit = false;
// ---- цвета -------------------------------------------------------------------------------
function readColor(token, fallback) {
@@ -953,7 +956,7 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
c.style.height = `${height}px`;
}
if (dprChanged) nodes.forEach((node) => { node.sprite = null; });
if (pendingFit && width > 1 && height > 1) fitCamera({ animate: false });
if ((pendingFit || autoFit) && width > 1 && height > 1) fitCamera({ animate: false });
requestDraw();
}
@@ -1343,7 +1346,8 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
const dimmed = groupDim > 0 && focusSet && !selected;
const islandW = Math.max(0, (geo.r - HULL_PAD) * 2 * camera.zoom);
let placed = null;
if (islandW >= 150 || selected) {
// Над островом / под ним – полной подписью, при нехватке места короче.
const besideIsland = () => {
ctx.font = `600 12px ${fontFamily}`;
const texts = [fitText(item.caption, 220), fitText(item.short || item.caption, 150)];
for (const text of texts) {
@@ -1351,15 +1355,14 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
const x = clamp(center.x - w / 2, 6, width - w - 6);
for (const y of [Math.max(topInset, top.y - 30), bottom.y + 4]) {
if (y < topInset || y + 26 > bottomInset) continue;
if (fits(x - 2, y - 1, w + 4, 28)) { placed = { lines: [text], x, y, w, h: 26 }; break; }
if (fits(x - 2, y - 1, w + 4, 28)) return { lines: [text], x, y, w, h: 26 };
}
if (placed) break;
}
if (!placed && selected) {
const w = ctx.measureText(texts[1]).width + 32;
placed = { lines: [texts[1]], x: clamp(center.x - w / 2, 6, width - w - 6), y: clamp(top.y - 30, topInset, bottomInset - 26), w, h: 26 };
}
} else {
return null;
};
// На самом острове (как название района): коротко, длинное – в две строки; если тесно –
// сдвинувшись в пределах острова, над ним или под ним.
const onIsland = () => {
ctx.font = `600 11.5px ${fontFamily}`;
const maxW = Math.max(72, Math.min(150, islandW + 28));
const name = item.short || item.caption;
@@ -1367,9 +1370,6 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
const lines = ctx.measureText(withCount).width <= maxW ? [withCount] : wrapText(name, maxW);
const w = Math.max(...lines.map((line) => ctx.measureText(line).width)) + 30;
const h = lines.length > 1 ? 41 : 26;
const x = clamp(center.x - w / 2, 6, width - w - 6);
// На самом острове: по центру или сдвинувшись в пределах острова – где свободно;
// не нашлось – в одну строку покороче.
const variants = [{ lines, w, h }];
if (lines.length > 1) {
const one = fitText(name, Math.max(56, islandW + 8));
@@ -1380,15 +1380,24 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
const shiftX = Math.max(0, Math.min(islandW / 2, v.w / 2));
const spots = [[0, 0], [0, -shiftY], [0, shiftY], [-shiftX, 0], [shiftX, 0], [-shiftX, -shiftY], [shiftX, -shiftY], [-shiftX, shiftY], [shiftX, shiftY]]
.map(([dx, dy]) => [center.x - v.w / 2 + dx, center.y - v.h / 2 + dy]);
// На самом острове тесно (соседняя подпись, край экрана) – над ним или под ним.
spots.push([center.x - v.w / 2, top.y - v.h - 2], [center.x - v.w / 2, bottom.y + 2]);
for (const [sx, sy] of spots) {
const vx = clamp(sx, 4, width - v.w - 4);
if (sy < topInset || sy + v.h > bottomInset) continue;
if (fits(vx - 2, sy - 1, v.w + 4, v.h + 2)) { placed = { lines: v.lines, x: vx, y: sy, w: v.w, h: v.h }; break; }
if (fits(vx - 2, sy - 1, v.w + 4, v.h + 2)) return { lines: v.lines, x: vx, y: sy, w: v.w, h: v.h };
}
if (placed) break;
}
return null;
};
// На обзоре (людей не различить) подпись – на острове; когда люди видны, она их не
// закрывает и встаёт рядом, а на остров – только если рядом места нет.
const overview = NODE_R[1] * camera.zoom < 8 && islandW < 150;
placed = selected || !overview ? (besideIsland() || onIsland()) : (onIsland() || besideIsland());
if (!placed && selected) {
ctx.font = `600 12px ${fontFamily}`;
const text = fitText(item.short || item.caption, 150);
const w = ctx.measureText(text).width + 32;
placed = { lines: [text], x: clamp(center.x - w / 2, 6, width - w - 6), y: clamp(top.y - 30, topInset, bottomInset - 26), w, h: 26 };
}
if (!placed) continue;
captionHits.push({ id: item.key, x: placed.x, y: placed.y, w: placed.w, h: placed.h });
@@ -1983,6 +1992,7 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
}
function fitCamera({ animate = true, only = null } = {}) {
autoFit = !only;
// Экран ещё не встроен в страницу и не знает своих размеров – впишем, когда узнает.
if (width <= 1 || height <= 1) {
pendingFit = true;
@@ -2168,6 +2178,7 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
moveTween = reducedMotion?.matches ? null : { t0: now, dur: MOVE_MS, real: realMove };
if (!moveTween) nodes.forEach((node) => { node.x = node.tx; node.y = node.ty; });
if (fit || focusChanged) fitCamera({ animate: !focusChanged || nodes.size > 1 });
else if (autoFit) fitCamera({ animate: true });
markDirty();
}
@@ -2209,6 +2220,7 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
function revealNode(id, { minZoom = 0.8 } = {}) {
const node = nodes.get(id);
if (!node || width <= 1) return;
autoFit = false;
if (isComfortablyVisible(node) && camera.zoom >= minZoom * 0.999) return;
const pad = insets();
const zoom = Math.max(camera.zoom, minZoom);
@@ -2283,6 +2295,7 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
function onPointerDown(event) {
if (event.button !== undefined && event.button > 0) return;
autoFit = false;
// Захват может не сработать (указатель уже отпущен) – жест тогда просто идёт без него.
try { canvas.setPointerCapture?.(event.pointerId); } catch { /* без захвата */ }
const p = localPoint(event);
@@ -2486,6 +2499,7 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
function onWheel(event) {
event.preventDefault();
autoFit = false;
cameraTween = null;
inertia = null;
const p = localPoint(event);
@@ -2495,6 +2509,7 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
}
function zoomBy(factor) {
autoFit = false;
const pad = insets();
const sx = width / 2;
const sy = pad.top + (height - pad.top - pad.bottom) / 2;
@@ -2551,13 +2566,18 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
ensureVisible: (id) => revealNode(id, { minZoom: 0 }),
fit: (animate = true) => fitCamera({ animate }),
// Положение камеры – чтобы при возврате на экран («назад» из профиля) карта стояла как была.
getView: () => ({ x: camera.x, y: camera.y, zoom: camera.zoom }),
// auto – карта была вписана целиком и её не трогали: тогда при возврате её надо вписать
// заново (данные могли догрузиться), а не ставить старое положение.
getView: () => ({ x: camera.x, y: camera.y, zoom: camera.zoom, auto: autoFit }),
setView: (view) => {
if (!view || !Number.isFinite(view.x) || !Number.isFinite(view.y) || !Number.isFinite(view.zoom)) return;
pendingFit = false;
autoFit = false;
setCamera({ x: view.x, y: view.y, zoom: clamp(view.zoom, ZOOM_MIN, ZOOM_MAX) }, false);
},
zoomBy,
// Панели поверх карты поменяли размер: если карта ещё вписана целиком – вписать заново.
refitIfAuto: () => { if (autoFit && !cameraTween) fitCamera({ animate: false }); },
// Сколько точек сейчас видно после фильтра (без центра).
visibleCount: () => [...nodes.values()].filter((node) => !node.isFocus && node.alphaTarget > 0).length,
// Текущее положение точки относительно центра (для сохранения раскладки целиком).
@@ -2579,6 +2599,8 @@ export function createGraphCanvas({ stage, onSelect, onNodeMoved, onGroupSelect,
labels: labelsDrawn,
guides: guides ? guides.items.map((item) => `${item.caption}:${item.count}`) : [],
layoutKind: guides?.kind || '',
autoFit,
fitInfo: { box: targetsBounds(), insets: insets(), width, height },
selectedGroup,
highlighted: focusSet ? focusSet.size : 0,
islands: [...islandGeo.values()].map((geo) => {