or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-charts.mdbasic-charts.mdconfiguration.mdindex.mdspecialty-charts.mdstatistical-charts.mdtiny-charts.mdutilities.md
tile.json

utilities.mddocs/

Utilities and G2 Integration

Utility functions and G2 integration for advanced chart customization, text measurement, and access to the underlying G2 visualization library.

Capabilities

Text Measurement Utility

Utility function for measuring text width, useful for dynamic label sizing and layout calculations.

/**
 * Measures the width of text with specified font
 * @param text - Text to measure
 * @param font - Font specification (CSS font format)
 * @returns Width of the text in pixels
 */
function measureTextWidth(text: string, font?: string): number;

Usage Example:

import { measureTextWidth } from "@ant-design/plots";

// Measure text with default font
const width1 = measureTextWidth('Hello World');
console.log(`Width: ${width1}px`);

// Measure text with custom font
const width2 = measureTextWidth('Hello World', '14px Arial');
console.log(`Width with Arial: ${width2}px`);

// Use in chart configuration for dynamic label positioning
const data = [
  { label: 'Very Long Category Name', value: 100 },
  { label: 'Short', value: 80 },
];

const config = {
  data,
  xField: 'label',
  yField: 'value',
  label: {
    formatter: (datum) => {
      const width = measureTextWidth(datum.label, '12px sans-serif');
      return width > 60 ? datum.label.substring(0, 8) + '...' : datum.label;
    },
  },
};

G2 Library Access

Direct access to the complete G2 visualization library for advanced customization and low-level chart control.

/**
 * Complete G2 visualization library
 * Provides access to all G2 classes, functions, and utilities
 */
const G2: typeof import('@antv/g2');

Usage Example:

import { G2 } from "@ant-design/plots";

// Access G2 classes directly
const { Chart, View, Scale } = G2;

// Create a custom G2 chart
const customChart = new Chart({
  container: 'container',
  width: 400,
  height: 300,
});

customChart
  .data([
    { genre: 'Sports', sold: 275 },
    { genre: 'Strategy', sold: 115 },
    { genre: 'Action', sold: 120 },
  ])
  .encode('x', 'genre')
  .encode('y', 'sold')
  .coordinate({ transform: [{ type: 'transpose' }] });

customChart.render();

Chart Events

Access to G2 chart event system for advanced interaction handling.

/**
 * Chart event types and utilities from G2
 */
const ChartEvent: typeof import('@antv/g2').ChartEvent;

Usage Example:

import React, { useRef } from "react";
import { Line, ChartEvent } from "@ant-design/plots";

const InteractiveChart: React.FC = () => {
  const chartRef = useRef();

  const handleReady = (chart) => {
    chartRef.current = chart;
    
    // Listen to G2 chart events
    chart.on(ChartEvent.CLICK, (event) => {
      console.log('Chart clicked:', event);
    });
    
    chart.on(ChartEvent.HOVER, (event) => {
      console.log('Chart hovered:', event);
    });
    
    chart.on('element:click', (event) => {
      console.log('Element clicked:', event.data);
    });
  };

  const config = {
    data: [/* data */],
    xField: 'x',
    yField: 'y',
    onReady: handleReady,
  };

  return <Line {...config} ref={chartRef} />;
};

Registration System

Access to G2's registration system for custom components and extensions.

/**
 * G2 registration system for custom components
 */
const register: typeof import('@antv/g2').register;

Usage Example:

import { register, G2 } from "@ant-design/plots";

// Register a custom shape
register('shape', 'custom-rect', (style, context) => {
  const { document } = context;
  return document.createElement('rect', {
    style: {
      ...style,
      rx: 4, // rounded corners
    },
  });
});

// Register a custom interaction
register('interaction', 'custom-highlight', (context) => {
  return {
    start: () => {
      // Interaction start logic
    },
    end: () => {
      // Interaction end logic
    },
  };
});

// Use custom components in charts
const config = {
  data: [/* data */],
  xField: 'x',
  yField: 'y',
  style: {
    shape: 'custom-rect', // Use custom shape
  },
  interactions: [
    { type: 'custom-highlight' }, // Use custom interaction
  ],
};

Advanced Integration Patterns

Chart Instance Access

Access the underlying G2 chart instance for advanced manipulation.

interface Chart {
  /** Export chart as data URL */
  toDataURL?: (type?: string, encoderOptions?: number) => string;
  /** Download chart as image */
  downloadImage?: (name?: string, type?: string, encoderOptions?: number) => string;
  /** G2 chart instance methods */
  render(): void;
  clear(): void;
  destroy(): void;
  changeData(data: any[]): void;
  changeSize(width: number, height: number): void;
  on(event: string, callback: Function): void;
  off(event: string, callback?: Function): void;
  emit(event: string, ...args: any[]): void;
  /** Access to underlying G2 chart */
  chart?: import('@antv/g2').Chart;
}

Usage Example:

import React, { useRef } from "react";
import { Line } from "@ant-design/plots";

const AdvancedChart: React.FC = () => {
  const chartRef = useRef<Chart>();

  const handleExport = () => {
    if (chartRef.current) {
      // Export as image
      const dataURL = chartRef.current.toDataURL('image/png', 1.0);
      console.log('Chart exported:', dataURL);
      
      // Download image
      chartRef.current.downloadImage('chart', 'png');
    }
  };

  const handleUpdateData = (newData: any[]) => {
    if (chartRef.current) {
      // Update chart data without re-render
      chartRef.current.changeData(newData);
    }
  };

  const config = {
    data: [/* initial data */],
    xField: 'x',
    yField: 'y',
    onReady: (chart) => {
      chartRef.current = chart;
    },
  };

  return (
    <div>
      <Line {...config} />
      <button onClick={handleExport}>Export Chart</button>
      <button onClick={() => handleUpdateData([/* new data */])}>
        Update Data
      </button>
    </div>
  );
};

Custom Chart Factory

Create custom chart components using the internal chart factory.

/**
 * Chart component factory function
 * Creates React components for G2 chart types
 */
function makeChartComp<C>(
  chartType: string
): ForwardRefExoticComponent<PropsWithoutRef<C> & RefAttributes<Chart>>;

Usage Example:

import React from "react";
import { makeChartComp } from "@ant-design/plots";
import type { CommonConfig } from "@ant-design/plots";

// Define custom chart configuration
interface CustomChartConfig extends CommonConfig {
  customProp?: string;
  specialOption?: boolean;
}

// Create custom chart component
const CustomChart = makeChartComp<CustomChartConfig>('Custom');

// Use the custom chart
const MyCustomChart: React.FC = () => {
  const config = {
    data: [/* data */],
    xField: 'x',
    yField: 'y',
    customProp: 'custom value',
    specialOption: true,
  };

  return <CustomChart {...config} />;
};

G2 Integration Utilities

Scale Configuration

Access G2 scale system for advanced axis and data transformations.

// G2 scale types and utilities
interface ScaleConfig {
  type?: 'linear' | 'log' | 'pow' | 'sqrt' | 'symlog' | 'time' | 'ordinal' | 'point' | 'band';
  domain?: any[];
  range?: any[];
  nice?: boolean;
  clamp?: boolean;
  round?: boolean;
  tickCount?: number;
  tickInterval?: number;
  min?: number;
  max?: number;
  minLimit?: number;
  maxLimit?: number;
  base?: number;
  exponent?: number;
  constant?: number;
  formatter?: (value: any) => string;
}

Theme System Integration

Access G2 theme system for consistent styling.

// G2 theme configuration
interface G2Theme {
  /** Color palette */
  colors10?: string[];
  colors20?: string[];
  /** Background colors */
  backgroundColor?: string;
  subColor?: string;
  /** Semantic colors */
  semanticRed?: string;
  semanticGreen?: string;
  semanticYellow?: string;
  /** Typography */
  fontFamily?: string;
  /** Component styles */
  axis?: Record<string, any>;
  legend?: Record<string, any>;
  tooltip?: Record<string, any>;
  annotation?: Record<string, any>;
}

Animation System

Access G2 animation system for custom animations.

// G2 animation configuration
interface G2Animation {
  /** Animation type */
  type?: 'appear' | 'enter' | 'update' | 'leave';
  /** Animation name */
  animation?: string;
  /** Animation duration in milliseconds */
  duration?: number;
  /** Animation delay in milliseconds */
  delay?: number;
  /** Easing function */
  easing?: string | Function;
  /** Animation callback */
  callback?: Function;
}

Coordinate System

Access G2 coordinate transformations for custom projections.

// G2 coordinate transformations
interface CoordinateTransform {
  type: 'transpose' | 'reflect' | 'rotate' | 'scale' | 'translate' | 'polar' | 'helix' | 'parallel';
  cfg?: Record<string, any>;
}

// Coordinate system configuration
interface CoordinateConfig {
  transform?: CoordinateTransform[];
  start?: [number, number];
  end?: [number, number];
}

Performance Utilities

Optimization Helpers

Utilities for optimizing chart performance and rendering.

// Performance optimization utilities
interface PerformanceUtils {
  /** Debounce chart updates */
  debounceUpdate(fn: Function, delay: number): Function;
  /** Throttle chart interactions */
  throttleInteraction(fn: Function, limit: number): Function;
  /** Optimize large datasets */
  sampleData(data: any[], maxPoints: number): any[];
  /** Virtual scrolling for large datasets */
  virtualizeData(data: any[], viewport: { start: number; end: number }): any[];
}

Usage Example:

import React, { useMemo, useCallback } from "react";
import { Line } from "@ant-design/plots";

const PerformantChart: React.FC<{ data: any[] }> = ({ data }) => {
  // Optimize large datasets
  const optimizedData = useMemo(() => {
    if (data.length > 1000) {
      // Sample data for performance
      const step = Math.ceil(data.length / 1000);
      return data.filter((_, index) => index % step === 0);
    }
    return data;
  }, [data]);

  // Debounce updates
  const debouncedUpdate = useCallback(
    debounce((newData) => {
      // Update chart with new data
    }, 300),
    []
  );

  const config = {
    data: optimizedData,
    xField: 'x',
    yField: 'y',
    // Disable animations for large datasets
    animation: data.length > 500 ? false : true,
  };

  return <Line {...config} />;
};