or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

behavior-system.mdcontrollers.mdgraph-management.mdindex.mditem-management.mdshape-system.mdutilities.md
tile.json

utilities.mddocs/

Utilities

Comprehensive utility functions for mathematical operations, graphics calculations, path manipulations, and graph analysis. The utility system provides essential tools for geometry calculations, transformations, and data processing.

Capabilities

Math Utilities

Mathematical operations for geometry, transformations, and graph algorithms.

/**
 * Calculate distance between two points
 * @param p1 - First point
 * @param p2 - Second point
 * @returns Distance between points
 */
function distance(p1: Point, p2: Point): number;

/**
 * Find intersection point of two lines
 * @param p0 - First line start point
 * @param p1 - First line end point
 * @param p2 - Second line start point
 * @param p3 - Second line end point
 * @returns Intersection point or null if no intersection
 */
function getLineIntersect(p0: Point, p1: Point, p2: Point, p3: Point): Point | null;

/**
 * Find intersection point between rectangle and external point
 * @param rect - Rectangle bounds
 * @param point - External point
 * @returns Intersection point on rectangle edge
 */
function getRectIntersectByPoint(rect: IRect, point: Point): Point | null;

/**
 * Find intersection point between circle and external point
 * @param circle - Circle definition
 * @param point - External point
 * @returns Intersection point on circle edge
 */
function getCircleIntersectByPoint(circle: ICircle, point: Point): Point | null;

/**
 * Find intersection point between ellipse and external point
 * @param ellipse - Ellipse definition
 * @param point - External point
 * @returns Intersection point on ellipse edge
 */
function getEllipseIntersectByPoint(ellipse: IEllipse, point: Point): Point;

/**
 * Apply transformation matrix to point
 * @param point - Point to transform
 * @param matrix - Transformation matrix
 * @param tag - Transform tag (0 for point, 1 for vector)
 * @returns Transformed point
 */
function applyMatrix(point: Point, matrix: Matrix, tag?: 0 | 1): Point;

/**
 * Apply inverse transformation matrix to point
 * @param point - Point to transform
 * @param matrix - Transformation matrix
 * @param tag - Transform tag (0 for point, 1 for vector)
 * @returns Inverse transformed point
 */
function invertMatrix(point: Point, matrix: Matrix, tag?: 0 | 1): Point;

/**
 * Calculate circle center from three points
 * @param p1 - First point on circle
 * @param p2 - Second point on circle
 * @param p3 - Third point on circle
 * @returns Circle center point
 */
function getCircleCenterByPoints(p1: Point, p2: Point, p3: Point): Point;

/**
 * Scale transformation matrix by ratio
 * @param matrix - Matrix to scale
 * @param ratio - Scale ratio
 */
function scaleMatrix(matrix: Matrix[], ratio: number): void;

Usage Examples:

import { Util } from "@antv/g6-core";

// Calculate distances
const dist = Util.distance({ x: 0, y: 0 }, { x: 3, y: 4 }); // 5

// Find line intersections
const intersection = Util.getLineIntersect(
  { x: 0, y: 0 }, { x: 10, y: 10 },
  { x: 0, y: 10 }, { x: 10, y: 0 }
); // { x: 5, y: 5 }

// Apply transformations
const transformed = Util.applyMatrix(
  { x: 100, y: 100 },
  [1, 0, 0, 1, 50, 50] // Translate by (50, 50)
); // { x: 150, y: 150 }

Graph Algorithm Utilities

Advanced algorithms for graph analysis and processing.

/**
 * Floyd-Warshall algorithm for shortest paths
 * @param adjMatrix - Adjacency matrix
 * @returns All-pairs shortest path matrix
 */
function floydWarshall(adjMatrix: Matrix[]): Matrix[];

/**
 * Generate adjacency matrix from graph data
 * @param data - Graph data with nodes and edges
 * @param directed - Whether graph is directed
 * @returns Adjacency matrix
 */
function getAdjMatrix(data: GraphData, directed: boolean): Matrix[];

/**
 * Calculate node degrees from edges
 * @param n - Number of nodes
 * @param nodeIdxMap - Node ID to index mapping
 * @param edges - Array of edge configurations
 * @returns Array of node degrees
 */
function getDegree(n: number, nodeIdxMap: NodeIdxMap, edges: EdgeConfig[]): number[];

Geometry Utilities

Geometric calculations for shapes, bounds, and spatial relationships.

/**
 * Check if point is inside polygon
 * @param points - Polygon vertices as [x, y] pairs
 * @param x - Point X coordinate
 * @param y - Point Y coordinate
 * @returns True if point is inside polygon
 */
function isPointInPolygon(points: number[][], x: number, y: number): boolean;

/**
 * Check if two bounding boxes intersect
 * @param box1 - First bounding box
 * @param box2 - Second bounding box
 * @returns True if boxes intersect
 */
function intersectBBox(box1: Partial<IBBox>, box2: Partial<IBBox>): boolean;

/**
 * Check if two polygons intersect
 * @param points1 - First polygon vertices
 * @param points2 - Second polygon vertices
 * @returns True if polygons intersect
 */
function isPolygonsIntersect(points1: number[][], points2: number[][]): boolean;

/**
 * Get bounding box edge line in specified direction
 * @param bbox - Bounding box
 * @param direction - Direction ('top', 'right', 'bottom', 'left')
 * @returns Line definition for bbox edge
 */
function getBBoxBoundLine(bbox: IBBox, direction: string): any[];

/**
 * Find intersection points between item and line
 * @param item - Graph item (node, edge, combo)
 * @param line - Line definition
 * @returns Array of intersection points and count
 */
function itemIntersectByLine(item: Item, line: any): [IPoint[], number];

/**
 * Calculate center point of multiple points
 * @param points - Array of points
 * @returns Center point
 */
function getPointsCenter(points: IPoint[]): IPoint;

/**
 * Calculate squared distance between two points
 * @param a - First point
 * @param b - Second point
 * @returns Squared distance
 */
function squareDist(a: IPoint, b: IPoint): number;

/**
 * Calculate squared distance from point to line
 * @param point - Point
 * @param line - Line definition
 * @returns Squared distance
 */
function pointLineSquareDist(point: IPoint, line: any): number;

/**
 * Check if two points overlap within tolerance
 * @param p1 - First point
 * @param p2 - Second point
 * @param e - Tolerance (default: 1e-6)
 * @returns True if points overlap
 */
function isPointsOverlap(p1: any, p2: any, e?: number): boolean;

/**
 * Calculate squared distance from point to rectangle
 * @param point - Point coordinates
 * @param rect - Rectangle definition
 * @returns Squared distance
 */
function pointRectSquareDist(point: Point, rect: IRect): number;

Graphics Utilities

Graphics-related calculations for rendering, layout, and visual elements.

/**
 * Get bounding box of graphics element
 * @param element - Graphics shape element
 * @param group - Graphics group container
 * @returns Element bounding box
 */
function getBBox(element: IShapeBase, group: IGroup): IBBox;

/**
 * Get loop edge configuration
 * @param cfg - Edge configuration
 * @returns Updated edge configuration for loops
 */
function getLoopCfgs(cfg: EdgeData): EdgeData;

/**
 * Calculate label position along path
 * @param pathShape - Path shape element
 * @param percent - Position along path (0-1)
 * @param refX - X reference offset
 * @param refY - Y reference offset
 * @param autoRotate - Whether to auto-rotate label
 * @returns Label style with position and rotation
 */
function getLabelPosition(pathShape: IShapeBase, percent: number, refX?: number, refY?: number, autoRotate?: boolean): LabelStyle;

/**
 * Calculate letter width for font size
 * @param letter - Character or string
 * @param fontSize - Font size in pixels
 * @returns Letter width in pixels
 */
function getLetterWidth(letter: any, fontSize: number): number;

/**
 * Calculate text dimensions
 * @param text - Text string
 * @param fontSize - Font size in pixels
 * @returns [width, height] dimensions
 */
function getTextSize(text: string, fontSize: number): [number, number];

/**
 * Get combo bounding box from its children
 * @param children - Child combo tree items
 * @param graph - Graph instance
 * @returns Combo bounding box
 */
function getComboBBox(children: ComboTree[], graph: IAbstractGraph): BBox;

/**
 * Get chart region bounds
 * @param params - Parameters with graph and optional combo
 * @returns Region bounds with min/max coordinates
 */
function getChartRegion(params: { graph: IAbstractGraph; combo?: string | ICombo }): { minX: number; minY: number; maxX: number; maxY: number };

Tree and Hierarchy Utilities

Functions for working with hierarchical data structures and tree layouts.

/**
 * Traverse tree structure downward
 * @param data - Tree data with children
 * @param fn - Function to call for each node (return false to stop)
 */
function traverseTree<T extends { children?: T[] }>(data: T, fn: (param: T) => boolean): void;

/**
 * Traverse tree structure upward
 * @param data - Tree data with children
 * @param fn - Function to call for each node (return false to stop)
 * @param parent - Parent node reference
 */
function traverseTreeUp<T extends { children?: T[] }>(data: T, fn: (param: T) => boolean, parent?: T): void;

/**
 * Apply radial layout to tree data
 * @param data - Tree data with positions
 * @param layout - Layout configuration
 * @returns Tree data with radial positions
 */
function radialLayout(data: TreeGraphDataWithPosition, layout?: any): TreeGraphDataWithPosition;

/**
 * Convert flat combo array to tree structure
 * @param array - Array of combo configurations
 * @param nodes - Array of node configurations
 * @returns Hierarchical combo tree structure
 */
function plainCombosToTrees(array: ComboConfig[], nodes?: NodeConfig[]): ComboTree[];

/**
 * Reconstruct tree from combo tree data
 * @param data - Combo tree array
 * @param fn - Filter function for reconstruction
 * @param parent - Parent combo reference
 * @returns Reconstructed combo tree or null
 */
function reconstructTree(data: ComboTree[], fn?: (param: ComboTree) => boolean, parent?: ComboTree): ComboTree | null;

Path Utilities

Functions for working with paths, splines, and geometric shapes.

/**
 * Generate spline path from points
 * @param points - Array of control points
 * @returns Spline path definition
 */
function getSpline(points: IPoint[]): any[];

/**
 * Calculate control point for curved paths
 * @param startPoint - Path start point
 * @param endPoint - Path end point
 * @param percent - Position along path (0-1)
 * @param offset - Curve offset amount
 * @returns Control point coordinates
 */
function getControlPoint(startPoint: IPoint, endPoint: IPoint, percent: number, offset: number): IPoint;

/**
 * Convert points array to polygon path string
 * @param points - Array of polygon vertices
 * @param z - Whether to close path with Z command
 * @returns SVG path string
 */
function pointsToPolygon(points: IPoint[], z?: boolean): string;

/**
 * Extract points from path definition
 * @param path - Path command array
 * @returns Array of points from path
 */
function pathToPoints(path: any[]): IPoint[];

/**
 * Generate closed spline path
 * @param points - Array of control points
 * @returns Closed spline path definition
 */
function getClosedSpline(points: IPoint[]): any[];

Transformation Utilities

Functions for applying transformations to graphics groups and elements.

/**
 * Translate graphics group by vector
 * @param group - Graphics group to transform
 * @param vec - Translation vector
 */
function translate(group: IGroup, vec: Point): void;

/**
 * Move graphics group to absolute position
 * @param group - Graphics group to move
 * @param point - Target position
 */
function move(group: IGroup, point: Point): void;

/**
 * Scale graphics group by ratio
 * @param group - Graphics group to scale
 * @param ratio - Scale ratio (number or [x, y] array)
 */
function scale(group: IGroup, ratio: number | number[]): void;

/**
 * Rotate graphics group by angle
 * @param group - Graphics group to rotate
 * @param angle - Rotation angle in radians
 */
function rotate(group: IGroup, angle: number): void;

Base Utilities

Essential utility functions for common operations.

/**
 * Format padding value to array format
 * @param padding - Padding as number, string, or array
 * @returns Normalized padding array [top, right, bottom, left]
 */
function formatPadding(padding: Padding): number[];

/**
 * Clone graph event object
 * @param e - Original graph event
 * @returns Cloned event object
 */
function cloneEvent(e: IG6GraphEvent): IG6GraphEvent;

/**
 * Check if viewport transformation has changed
 * @param matrix - Current transformation matrix
 * @returns True if viewport changed from identity
 */
function isViewportChanged(matrix: Matrix): boolean;

/**
 * Enhanced NaN check function
 * @param input - Value to check
 * @returns True if value is NaN
 */
function isNaN(input: any): boolean;

/**
 * Calculate bounding box that contains all items
 * @param items - Array of graph items
 * @returns Combined bounding box
 */
function calculationItemsBBox(items: Item[]): IBBox;

/**
 * Process parallel edges to avoid overlapping
 * @param edges - Array of edges to process
 * @param offsetDiff - Offset difference between parallel edges
 * @param multiEdgeType - Type for multiple edges
 * @param singleEdgeType - Type for single edges
 * @param loopEdgeType - Type for loop edges
 * @returns Processed edges with offset configurations
 */
function processParallelEdges(edges: IEdge[], offsetDiff?: number, multiEdgeType?: string, singleEdgeType?: string, loopEdgeType?: string): IEdge[];

Comparison Utilities

Helper functions for sorting and comparison operations.

/**
 * Create comparison function for sorting by attribute
 * @param attributeName - Name of attribute to compare
 * @returns Comparison function for Array.sort()
 */
function compare(attributeName: string): (m: any, n: any) => number;

Usage Example:

import { Util } from "@antv/g6-core";

// Sort nodes by x coordinate
const nodes = graph.getNodes();
nodes.sort(Util.compare('x'));

// Sort by nested attribute
const items = [
  { model: { priority: 3 } },
  { model: { priority: 1 } },
  { model: { priority: 2 } }
];
items.sort(Util.compare('model.priority'));

Advanced Usage Examples

// Calculate optimal edge control points
function calculateEdgeControlPoints(edge: IEdge) {
  const source = edge.getSource();
  const target = edge.getTarget();
  const sourcePoint = source.getModel();
  const targetPoint = target.getModel();
  
  // Calculate midpoint with offset for curved edge
  const controlPoint = Util.getControlPoint(
    sourcePoint,
    targetPoint,
    0.5,    // Middle of edge
    50      // Curve offset
  );
  
  return [controlPoint];
}

// Check if node overlaps with selection area
function isNodeInSelection(node: INode, selectionBounds: IBBox): boolean {
  const nodeBounds = node.getBBox();
  return Util.intersectBBox(nodeBounds, selectionBounds);
}

// Calculate text label dimensions for auto-sizing
function calculateLabelSize(text: string, fontSize: number): { width: number; height: number } {
  const [width, height] = Util.getTextSize(text, fontSize);
  return { width, height };
}

// Process hierarchical combo data
function processComboHierarchy(combos: ComboConfig[], nodes: NodeConfig[]) {
  // Convert flat combo array to tree structure
  const comboTrees = Util.plainCombosToTrees(combos, nodes);
  
  // Traverse tree to apply processing
  comboTrees.forEach(tree => {
    Util.traverseTree(tree, (combo) => {
      // Process each combo in hierarchy
      console.log(`Processing combo: ${combo.id}, depth: ${combo.depth}`);
      return true; // Continue traversal
    });
  });
  
  return comboTrees;
}

// Create smooth path through multiple points
function createSmoothPath(points: IPoint[]): string {
  const splinePoints = Util.getSpline(points);
  return Util.pointsToPolygon(splinePoints);
}

Types

interface Point {
  x: number;
  y: number;
}

interface IPoint extends Point {
  anchorIndex?: number;
}

interface IRect {
  x: number;
  y: number;
  width: number;
  height: number;
}

interface ICircle {
  x: number;
  y: number;
  r: number;
}

interface IEllipse {
  x: number;
  y: number;
  rx: number;
  ry: number;
}

interface IBBox extends IRect {
  centerX?: number;
  centerY?: number;
}

interface BBox {
  minX: number;
  minY: number;
  maxX: number;
  maxY: number;
  x: number;
  y: number;
  width: number;
  height: number;
}

type Matrix = number[];

type Padding = number | string | number[];

interface EdgeData {
  source: string;
  target: string;
  controlPoints?: IPoint[];
  [key: string]: any;
}

interface NodeIdxMap {
  [nodeId: string]: number;
}

interface ComboTree {
  id: string;
  children?: ComboTree[];
  depth?: number;
  [key: string]: any;
}

interface TreeGraphDataWithPosition {
  id: string;
  x?: number;
  y?: number;
  children?: TreeGraphDataWithPosition[];
  [key: string]: any;
}

interface LabelStyle {
  x?: number;
  y?: number;
  textAlign?: string;
  textBaseline?: string;
  rotate?: number;
  [key: string]: any;
}