or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

annotations.mdchart-components.mdchart-container.mdg-components.mdg2-integration.mdgeometry-components.mdindex.mdmigration-guide.mdreact-hooks.mdstatistical-charts.mdtheme-system.mdutilities.md
tile.json

utilities.mddocs/

Utilities

BizCharts provides a comprehensive set of utility functions for data transformation, configuration helpers, and integration with the underlying visualization system. These utilities combine functions from @antv/util, BizCharts-specific helpers, and G2 utilities.

Capabilities

Util Object

The main utility object that combines all available utility functions from multiple sources.

/**
 * Combined utility object containing functions from:
 * - @antv/util: General utility functions
 * - BizCharts utilities: Chart-specific helpers  
 * - G2.Util: G2 visualization utilities
 */
declare const Util: {
  // Data transformation utilities
  fold: (data: any[], fields: string[], key: string, value: string) => any[];
  percentage: (data: any[], field: string) => any[];
  minifyNum: (num: number, precision?: number) => string;
  splitBySeparator: (data: any[], separator: string, field: string) => any[];
  
  // Configuration helpers
  visibleHelper: (visible?: boolean) => { visible: boolean };
  
  // Function utilities
  cloneDeep: <T>(obj: T) => T;
  shallowEqual: (objA: any, objB: any) => boolean;
  
  // @antv/util functions (extensive collection)
  isArray: (value: any) => boolean;
  isObject: (value: any) => boolean;
  isString: (value: any) => boolean;
  isNumber: (value: any) => boolean;
  isBoolean: (value: any) => boolean;
  isFunction: (value: any) => boolean;
  isEmpty: (value: any) => boolean;
  isNil: (value: any) => boolean;
  
  // Array utilities
  map: <T, U>(array: T[], callback: (item: T, index: number) => U) => U[];
  filter: <T>(array: T[], callback: (item: T, index: number) => boolean) => T[];
  reduce: <T, U>(array: T[], callback: (acc: U, item: T, index: number) => U, initial: U) => U;
  forEach: <T>(array: T[], callback: (item: T, index: number) => void) => void;
  find: <T>(array: T[], callback: (item: T, index: number) => boolean) => T | undefined;
  
  // Object utilities
  keys: (obj: object) => string[];
  values: (obj: object) => any[];
  entries: (obj: object) => [string, any][];
  assign: (target: object, ...sources: object[]) => object;
  pick: (obj: object, keys: string[]) => object;
  omit: (obj: object, keys: string[]) => object;
  
  // String utilities
  upperFirst: (str: string) => string;
  lowerFirst: (str: string) => string;
  camelCase: (str: string) => string;
  kebabCase: (str: string) => string;
  
  // Math utilities
  max: (array: number[]) => number;
  min: (array: number[]) => number;
  sum: (array: number[]) => number;
  mean: (array: number[]) => number;
  
  // G2 utilities
  [key: string]: any;
};

Data Transformation

Functions for transforming and preparing data for visualization.

/**
 * Fold/melt operation to convert wide data to long format
 * @param data - Array of data objects
 * @param fields - Fields to fold into key-value pairs
 * @param key - Name for the key column
 * @param value - Name for the value column
 * @returns Transformed data in long format
 */
function fold(
  data: any[], 
  fields: string[], 
  key: string, 
  value: string
): any[];

/**
 * Calculate percentage values for a numeric field
 * @param data - Array of data objects
 * @param field - Field name to calculate percentages for
 * @returns Data with percentage values added
 */
function percentage(data: any[], field: string): any[];

/**
 * Minify large numbers into readable format (e.g., 1K, 1M, 1B)
 * @param num - Number to minify
 * @param precision - Decimal precision for the result
 * @returns Minified number as string
 */
function minifyNum(num: number, precision?: number): string;

/**
 * Split data based on separator in a field value
 * @param data - Array of data objects
 * @param separator - String separator to split on
 * @param field - Field containing values to split
 * @returns Split data with duplicated rows
 */
function splitBySeparator(
  data: any[], 
  separator: string, 
  field: string
): any[];

Usage Examples:

import React from "react";
import { Chart, Line, Util } from "bizcharts";

// Data transformation example
function DataTransformChart() {
  const wideData = [
    { month: 'Jan', sales: 100, profit: 20, cost: 80 },
    { month: 'Feb', sales: 120, profit: 25, cost: 95 }
  ];

  // Transform wide data to long format for multi-series chart
  const longData = Util.fold(
    wideData, 
    ['sales', 'profit', 'cost'], 
    'metric', 
    'value'
  );
  
  return (
    <Chart height={400} data={longData} autoFit>
      <Line position="month*value" color="metric" />
    </Chart>
  );
}

// Percentage calculation
function PercentageChart() {
  const rawData = [
    { category: 'A', value: 100 },
    { category: 'B', value: 150 },
    { category: 'C', value: 75 }
  ];

  const percentData = Util.percentage(rawData, 'value');
  
  return (
    <Chart height={400} data={percentData} autoFit>
      <Line position="category*percent" />
    </Chart>
  );
}

// Number minification for labels
function MinifiedLabelsChart() {
  const largeNumberData = [
    { category: 'A', value: 1500000 },
    { category: 'B', value: 2300000 },
    { category: 'C', value: 890000 }
  ];

  const processedData = largeNumberData.map(d => ({
    ...d,
    displayValue: Util.minifyNum(d.value, 1)
  }));

  return (
    <Chart height={400} data={processedData} autoFit>
      <Line 
        position="category*value"
        label={{
          content: 'displayValue'
        }}
      />
    </Chart>
  );
}

// Array and object utilities
function UtilityExample() {
  const data = [
    { name: 'Alice', score: 85, subject: 'Math' },
    { name: 'Bob', score: 92, subject: 'Science' },
    { name: 'Carol', score: 78, subject: 'Math' }
  ];

  // Filter high scores
  const highScores = Util.filter(data, d => d.score > 80);
  
  // Group by subject
  const subjects = Util.uniq(Util.map(data, 'subject'));
  
  // Calculate average score
  const avgScore = Util.mean(Util.map(data, 'score'));
  
  // Clone data for modification
  const modifiedData = Util.cloneDeep(data);
  modifiedData.forEach(d => {
    d.grade = d.score >= 90 ? 'A' : d.score >= 80 ? 'B' : 'C';
  });

  return (
    <div>
      <p>High scores: {highScores.length}</p>
      <p>Subjects: {subjects.join(', ')}</p>
      <p>Average score: {avgScore.toFixed(1)}</p>
      <Chart height={400} data={modifiedData} autoFit>
        <Line position="name*score" color="grade" />
      </Chart>
    </div>
  );
}

Configuration Helpers

Helper functions for chart configuration and component setup.

/**
 * Helper for visibility configuration
 * @param visible - Visibility boolean
 * @returns Normalized visibility configuration object
 */
function visibleHelper(visible?: boolean): { visible: boolean };

Usage Examples:

// Configuration helper usage
function ConfiguredChart() {
  const showAxis = true;
  const showLegend = false;

  return (
    <Chart height={400} data={data} autoFit>
      <Line position="x*y" />
      <Axis name="x" {...Util.visibleHelper(showAxis)} />
      <Legend {...Util.visibleHelper(showLegend)} />
    </Chart>
  );
}

Function Utilities

Core utility functions for object manipulation and comparison.

/**
 * Deep clone an object or array
 * @param obj - Object to clone
 * @returns Deep copy of the object
 */
function cloneDeep<T>(obj: T): T;

/**
 * Shallow equality comparison between two objects
 * @param objA - First object to compare
 * @param objB - Second object to compare
 * @returns True if objects are shallow equal
 */
function shallowEqual(objA: any, objB: any): boolean;

Usage Examples:

// Deep cloning for data manipulation
function DataManipulationChart() {
  const originalData = [
    { name: 'A', values: [1, 2, 3] },
    { name: 'B', values: [4, 5, 6] }
  ];

  // Safe data modification
  const modifiedData = Util.cloneDeep(originalData);
  modifiedData[0].values.push(4);
  
  return (
    <Chart height={400} data={modifiedData} autoFit>
      <Line position="name*values" />
    </Chart>
  );
}

// Shallow comparison for optimization
function OptimizedComponent({ data, config }) {
  const [prevConfig, setPrevConfig] = useState(config);
  const [shouldUpdate, setShouldUpdate] = useState(true);

  useEffect(() => {
    const configChanged = !Util.shallowEqual(config, prevConfig);
    setShouldUpdate(configChanged);
    setPrevConfig(config);
  }, [config, prevConfig]);

  if (!shouldUpdate) {
    return null; // Skip re-render if config hasn't changed
  }

  return (
    <Chart height={400} data={data} autoFit {...config}>
      <Line position="x*y" />
    </Chart>
  );
}

Plot Creation System

Factory function for creating custom plot components.

/**
 * Factory function for creating plot components from G2Plot classes
 * @param PlotClass - G2Plot class constructor
 * @param name - Component display name
 * @param transCfg - Optional configuration transformation function
 * @returns React component for the plot
 */
function createPlot<IPlotConfig>(
  PlotClass: any,
  name: string,
  transCfg?: (cfg: IPlotConfig) => any
): React.ForwardRefExoticComponent<IPlotConfig>;

/**
 * Create tooltip connector utility for custom interactions
 * @returns Tooltip connector instance
 */
function createTooltipConnector(): any;

Usage Examples:

import { createPlot } from "bizcharts";
import { CustomPlot } from '@antv/g2plot';

// Create custom plot component
const CustomChart = createPlot(
  CustomPlot,
  'CustomChart',
  (config) => ({
    ...config,
    // Transform configuration if needed
    theme: config.theme || 'default'
  })
);

// Usage of custom plot
function CustomPlotExample() {
  return (
    <CustomChart
      data={data}
      xField="x"
      yField="y"
      height={400}
      autoFit
    />
  );
}

// Tooltip connector for advanced interactions
function AdvancedInteractionChart() {
  const tooltipConnector = Util.createTooltipConnector();
  
  return (
    <Chart height={400} data={data} autoFit>
      <Line position="x*y" />
      {/* Use tooltip connector for custom tooltip behavior */}
    </Chart>
  );
}

Integration with G2 Core

Access to core G2 functionality through utilities.

/**
 * G2 integration utilities and re-exports
 */
declare const G2: {
  /** G2 Chart class */
  Chart: any;
  /** G2 View class */
  View: any;
  /** G2 utilities */
  Util: any;
  /** G2 version information */
  VERSION: string;
  /** Error handling */
  setDefaultErrorFallback: (component: React.ComponentType) => void;
  
  // Scale registration from @antv/scale
  registerScale: (type: string, ScaleClass: any) => void;
  getScale: (type: string) => any;
  registerTickMethod: (method: string, tickMethod: Function) => void;
  
  // Global configuration from @antv/g2plot
  setGlobal: (config: object) => void;
  GLOBAL: object;
  
  [key: string]: any;
};

Core System Utilities

Core system utilities for scale registration, global configuration, and error handling.

/**
 * Register custom scale type with @antv/scale
 * @param type - Scale type name
 * @param ScaleClass - Scale class constructor
 */
function registerScale(type: string, ScaleClass: any): void;

/**
 * Get registered scale class by type
 * @param type - Scale type name
 * @returns Scale class constructor
 */
function getScale(type: string): any;

/**
 * Register tick calculation method for scales
 * @param method - Method name
 * @param tickMethod - Tick calculation function
 */
function registerTickMethod(method: string, tickMethod: Function): void;

/**
 * Set global configuration for G2Plot
 * @param config - Global configuration object
 */
function setGlobal(config: object): void;

/**
 * Global configuration object from G2Plot
 */
declare const GLOBAL: object;

/**
 * BizCharts version string
 */
declare const VERSION: string;

/**
 * Set default error fallback component for error boundaries
 * @param component - React component to use as error fallback
 */
function setDefaultErrorFallback(component: React.ComponentType): void;

Usage Examples:

import { 
  registerScale, 
  getScale, 
  setGlobal, 
  VERSION,
  setDefaultErrorFallback 
} from "bizcharts";

// Register custom scale
class CustomTimeScale {
  // Custom scale implementation
}
registerScale('customTime', CustomTimeScale);

// Use registered scale
const ScaleClass = getScale('customTime');

// Configure global settings
setGlobal({
  animate: false,
  defaultColor: '#1890ff'
});

// Set error fallback
function ChartErrorFallback({ error }) {
  return <div>Chart Error: {error.message}</div>;
}
setDefaultErrorFallback(ChartErrorFallback);

// Check version
console.log('BizCharts version:', VERSION);

Types

// Data transformation types
interface FoldOptions {
  fields: string[];
  key: string;
  value: string;
}

interface PercentageOptions {
  field: string;
  as?: string;
}

// Utility function types
type DeepCloneFunction = <T>(obj: T) => T;
type ShallowEqualFunction = (objA: any, objB: any) => boolean;
type VisibleHelperFunction = (visible?: boolean) => { visible: boolean };

// Plot creation types
interface PlotCreationOptions<T> {
  PlotClass: any;
  name: string;
  transCfg?: (cfg: T) => any;
}

// Array utility function types
type MapFunction = <T, U>(array: T[], callback: (item: T, index: number) => U) => U[];
type FilterFunction = <T>(array: T[], callback: (item: T, index: number) => boolean) => T[];
type ReduceFunction = <T, U>(array: T[], callback: (acc: U, item: T, index: number) => U, initial: U) => U;
type ForEachFunction = <T>(array: T[], callback: (item: T, index: number) => void) => void;
type FindFunction = <T>(array: T[], callback: (item: T, index: number) => boolean) => T | undefined;

// Object utility function types
type PickFunction = (obj: object, keys: string[]) => object;
type OmitFunction = (obj: object, keys: string[]) => object;
type AssignFunction = (target: object, ...sources: object[]) => object;

// Math utility function types
type MathFunction = (array: number[]) => number;
type MinifyNumFunction = (num: number, precision?: number) => string;

// String utility function types
type StringTransformFunction = (str: string) => string;