Files
tessera/web/src/lib/galaxyLabelLayout.ts

39 lines
1.3 KiB
TypeScript

export type Rect = { x: number; y: number; width: number; height: number };
type Label = { id: string; x: number; y: number; width: number };
export const LABEL_HEIGHT = 24;
const GAP = 4;
function overlaps(a: Rect, b: Rect) {
return a.x < b.x + b.width + GAP && a.x + a.width + GAP > b.x &&
a.y < b.y + b.height + GAP && a.y + a.height + GAP > b.y;
}
export function placeLabels(
candidates: Label[],
width: number,
height: number,
obstacles: Rect[],
): Label[] {
const occupied = [...obstacles];
const placed: Label[] = [];
for (const label of candidates) {
const { x, y, width: w } = label;
const offsets = [12, 28, 44].flatMap((gap) => [
[gap, -LABEL_HEIGHT / 2], [-w - gap, -LABEL_HEIGHT / 2],
[-w / 2, -LABEL_HEIGHT - gap], [-w / 2, gap],
[gap, -LABEL_HEIGHT - gap / 2], [-w - gap, gap / 2],
]);
for (const [dx, dy] of offsets) {
const rect = { x: x + dx, y: y + dy, width: w, height: LABEL_HEIGHT };
if (rect.x < GAP || rect.y < GAP || rect.x + w > width - GAP ||
rect.y + LABEL_HEIGHT > height - GAP || occupied.some((other) => overlaps(rect, other))) {
continue;
}
occupied.push(rect);
placed.push({ id: label.id, ...rect });
break;
}
}
return placed;
}