or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

data-stores.mdevents.mdindex.mdplugins.mdrevo-grid-component.mdtypes-interfaces.mdutilities.md
tile.json

utilities.mddocs/

Utilities and Services

RevoGrid provides comprehensive utility functions and service classes for common operations including data manipulation, column management, dimension calculations, viewport handling, and observable state management.

Capabilities

Data Utilities

Utility functions for data manipulation and array operations.

/**
 * Generate array of numbers in range
 * @param size - Number of elements to generate
 * @param startAt - Starting number (default: 0)
 * @returns Array of sequential numbers
 */
function range(size: number, startAt?: number): number[];

/**
 * Find element position using binary search algorithm
 * @param el - Element to find
 * @param compareFn - Comparison function
 * @returns Index of element or insertion point
 */
function findPositionInArray<T>(
  el: T, 
  compareFn: (a: T, b: T) => number
): number;

/**
 * Insert element in sorted array maintaining order
 * @param arr - Sorted array
 * @param el - Element to insert
 * @param fn - Comparison function
 * @returns Updated array
 */
function pushSorted<T>(
  arr: T[], 
  el: T, 
  fn: (a: T, b: T) => number
): T[];

/**
 * Merge two sorted arrays into one sorted array
 * @param arr1 - First sorted array
 * @param arr2 - Second sorted array  
 * @param compareFn - Comparison function (optional)
 * @returns Merged sorted array
 */
function mergeSortedArray<T>(
  arr1: T[], 
  arr2: T[], 
  compareFn?: (a: T, b: T) => number
): T[];

/**
 * Scale value from one range to another
 * @param value - Value to scale
 * @param from - Source range [min, max]
 * @param to - Target range [min, max]
 * @returns Scaled value
 */
function scaleValue(
  value: number, 
  from: [number, number], 
  to: [number, number]
): number;

/**
 * Async timeout utility function
 * @param delay - Delay in milliseconds (default: 0)
 * @returns Promise that resolves after delay
 */
function timeout(delay?: number): Promise<void>;

/**
 * Calculate system scrollbar size
 * @param document - Document object
 * @returns Scrollbar width in pixels
 */
function getScrollbarSize(document: Document): number;

/**
 * TypeScript mixin utility function
 * @param derivedCtor - Target constructor
 * @param constructors - Source constructors to mix in
 */
function applyMixins(derivedCtor: any, constructors: any[]): void;

Usage Example:

import { range, findPositionInArray, pushSorted, scaleValue } from '@revolist/revogrid';

// Generate array of numbers
const indices = range(10, 1); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Binary search in sorted array
const sortedNumbers = [1, 3, 5, 7, 9, 11];
const position = findPositionInArray(6, (a, b) => a - b); // Returns 3 (insertion point)

// Insert maintaining sort order
const newArray = pushSorted([1, 3, 7, 9], 5, (a, b) => a - b); // [1, 3, 5, 7, 9]

// Scale values between ranges
const scaled = scaleValue(5, [0, 10], [0, 100]); // 50 (5 is halfway between 0-10, so 50 is halfway between 0-100)

// Async delay
async function delayedOperation() {
  console.log('Starting...');
  await timeout(1000); // Wait 1 second
  console.log('Completed!');
}

Column Utilities

Utilities for processing and managing column definitions.

/**
 * Process column definitions and groupings into flat collection
 * @param columns - Column definitions (can include groups)
 * @param level - Current nesting level for groups
 * @param columnTypes - Reusable column type definitions
 * @returns Processed column collection
 */
function getColumns(
  columns: (ColumnRegular | ColumnGrouping)[], 
  level?: number,
  columnTypes?: {[name: string]: ColumnType}
): ColumnCollection;

/**
 * Find column definition by property name
 * @param columns - Array of column definitions
 * @param prop - Column property to find
 * @returns Column definition or undefined
 */
function getColumnByProp(
  columns: ColumnRegular[], 
  prop: ColumnProp
): ColumnRegular | undefined;

/**
 * Column collection result from processing
 */
interface ColumnCollection {
  /** Flattened column definitions */
  columns: ColumnRegular[];
  /** Column grouping information */
  groups: ColumnGrouping[];
  /** Column order mapping */
  order: Record<string, number>;
  /** Maximum group depth */
  maxLevel: number;
}

Usage Example:

import { getColumns, getColumnByProp, ColumnRegular, ColumnGrouping } from '@revolist/revogrid';

// Define columns with grouping
const columnDefs: (ColumnRegular | ColumnGrouping)[] = [
  { prop: 'id', name: 'ID' },
  {
    name: 'Personal Info',
    children: [
      { prop: 'firstName', name: 'First Name' },
      { prop: 'lastName', name: 'Last Name' }
    ]
  },
  { prop: 'email', name: 'Email' }
];

// Process columns
const processed = getColumns(columnDefs, 0);
console.log('Processed columns:', processed.columns.length); // 4 (flattened)
console.log('Groups:', processed.groups); // Grouping information
console.log('Max level:', processed.maxLevel); // 1 (one level of grouping)

// Find specific column
const emailColumn = getColumnByProp(processed.columns, 'email');
console.log('Email column:', emailColumn?.name);

Event Utilities

Utilities for handling DOM events across different input types.

/**
 * Get property value from event (handles touch/mouse events)
 * @param event - DOM event (mouse or touch)
 * @param property - Property to extract ('clientX', 'clientY', etc.)
 * @returns Property value from event
 */
function getPropertyFromEvent(event: Event, property: string): any;

/**
 * Keyboard key code constants
 */
const KEY_CODES: {
  readonly ARROW_LEFT: number;
  readonly ARROW_UP: number;
  readonly ARROW_RIGHT: number;
  readonly ARROW_DOWN: number;
  readonly ENTER: number;
  readonly ESCAPE: number;
  readonly TAB: number;
  readonly SPACE: number;
  readonly DELETE: number;
  readonly BACKSPACE: number;
  readonly HOME: number;
  readonly END: number;
  readonly PAGE_UP: number;
  readonly PAGE_DOWN: number;
  readonly F2: number;
};

Usage Example:

import { getPropertyFromEvent, KEY_CODES } from '@revolist/revogrid';

// Handle mouse and touch events uniformly
function handlePointerEvent(event: MouseEvent | TouchEvent) {
  const x = getPropertyFromEvent(event, 'clientX');
  const y = getPropertyFromEvent(event, 'clientY');
  console.log('Pointer position:', { x, y });
}

// Handle keyboard navigation
function handleKeyDown(event: KeyboardEvent) {
  switch (event.keyCode) {
    case KEY_CODES.ARROW_LEFT:
      moveLeft();
      break;
    case KEY_CODES.ARROW_RIGHT:
      moveRight();
      break;
    case KEY_CODES.ENTER:
      startEdit();
      break;
    case KEY_CODES.ESCAPE:
      cancelEdit();
      break;
    case KEY_CODES.F2:
      toggleEdit();
      break;
  }
}

Browser Utilities

Utilities for browser feature detection and measurements.

/**
 * Calculate system scrollbar size for current browser
 * @param document - Document object
 * @returns Scrollbar width in pixels
 */
function getScrollbarSize(document: Document): number;

Usage Example:

import { getScrollbarSize } from '@revolist/revogrid';

// Get scrollbar size for layout calculations
const scrollbarWidth = getScrollbarSize(document);
console.log('System scrollbar width:', scrollbarWidth); // Usually 15-17px

// Use for layout adjustments
function adjustGridLayout() {
  const containerWidth = container.clientWidth;
  const contentWidth = containerWidth - scrollbarWidth;
  grid.style.width = `${contentWidth}px`;
}

Observable System

Reactive state management system used internally by RevoGrid.

/**
 * Observable interface for reactive state management
 */
interface Observable<T> {
  /** Subscribe to state changes */
  onChange(callback: (newState: T, oldState?: T) => void): () => void;
  
  /** Get current state value */
  get(): T;
  
  /** Set new state value */
  set(state: T): void;
  
  /** Update state using function */
  update(updater: (currentState: T) => T): void;
}

/**
 * Store types for different grid stores
 */
interface StoreTypes {
  /** Data source store */
  DataSourceStore: Observable<DataSourceState>;
  /** Column store */
  ColumnStore: Observable<ColumnCollection>;
  /** Dimension store */
  DimensionStore: Observable<DimensionSettingsState>;
  /** Viewport store */
  ViewportStore: Observable<ViewportState>;
  /** Selection store */
  SelectionStore: Observable<SelectionStoreState>;
}

Usage Example:

// Access grid stores through providers
const providers = await grid.getProviders();

// Subscribe to data changes
const dataStore = await grid.getSourceStore('rgRow');
const unsubscribe = dataStore.onChange((newState, oldState) => {
  console.log('Data changed:', {
    oldCount: oldState?.source.length || 0,
    newCount: newState.source.length
  });
  
  // React to data changes
  updateDataSummary(newState.source);
});

// Get current state
const currentData = dataStore.get();
console.log('Current data:', currentData.source);

// Clean up subscription when done
// unsubscribe();

Data Provider Service

Service class for managing grid data sources and operations.

/**
 * Data provider service for managing grid data
 */
class DataProvider {
  /**
   * Set data source for specific dimension
   * @param source - Data array
   * @param type - Dimension type
   * @param disableVirtual - Disable virtualization for this data
   */
  setData(source: DataType[], type: DimensionRows, disableVirtual?: boolean): void;

  /**
   * Update specific cell data
   * @param details - Cell update details
   * @param refresh - Whether to refresh grid view
   */
  setCellData(details: SetCellData, refresh?: boolean): void;

  /**
   * Update range of data
   * @param data - Range update data
   * @param type - Dimension type
   */
  setRangeData(data: RangeUpdateData, type: DimensionRows): void;

  /**
   * Refresh data for specific dimension type
   * @param type - Dimension type to refresh
   */
  refresh(type?: DimensionRows): void;

  /**
   * Change row order (for drag and drop)
   * @param details - Order change details
   */
  changeOrder(details: RowOrderChangeDetails): void;

  /**
   * Set trimmed/hidden rows
   * @param trimmed - Trimmed row configuration
   * @param type - Dimension type
   */
  setTrimmed(trimmed: Record<number, boolean>, type: DimensionRows): void;
}

Column Data Provider Service

Service class for managing column definitions and operations.

/**
 * Column data provider service
 */
class ColumnDataProvider {
  /**
   * Set processed column collection
   * @param collection - Processed column collection
   */
  setColumns(collection: ColumnCollection): void;

  /**
   * Update existing columns
   * @param cols - Updated column definitions
   */
  updateColumns(cols: ColumnRegular[]): void;

  /**
   * Get all column definitions
   * @returns Array of column definitions
   */
  getColumns(): ColumnRegular[];

  /**
   * Get column by index for specific dimension
   * @param index - Column index
   * @param type - Column dimension type
   * @returns Column definition or undefined
   */
  getColumn(index: number, type: DimensionCols): ColumnRegular | undefined;

  /**
   * Get column index by property name
   * @param prop - Column property
   * @param type - Column dimension type
   * @returns Column index or -1 if not found
   */
  getColumnIndexByProp(prop: ColumnProp, type: DimensionCols): number;
}

Dimension Provider Service

Service class for managing dimension calculations and viewport sizing.

/**
 * Dimension provider service for calculations
 */
class DimensionProvider {
  /**
   * Update dimension settings
   * @param settings - New dimension settings
   * @param type - Dimension type
   */
  setSettings(settings: DimensionSettingsState, type: DimensionRows | DimensionCols): void;

  /**
   * Apply new column configuration
   * @param columns - Column definitions
   * @param disableVirtual - Disable virtualization
   * @param init - Is initialization
   */
  applyNewColumns(columns: ColumnRegular[], disableVirtual?: boolean, init?: boolean): void;

  /**
   * Set custom sizes for items
   * @param type - Dimension type
   * @param sizes - Custom size mapping
   */
  setCustomSizes(type: DimensionRows | DimensionCols, sizes: ViewSettingSizeProp): void;

  /**
   * Clear size data
   * @param type - Dimension type
   * @param length - New length
   */
  clearSize(type: DimensionRows | DimensionCols, length: number): void;

  /**
   * Get viewport position information
   * @param params - Position parameters
   * @returns Position details
   */
  getViewPortPos(params: ViewportPositionParams): PositionItem;

  /**
   * Get full content size
   * @returns Content size for all dimensions
   */
  getFullSize(): MultiDimensionType;
}

/**
 * Viewport position parameters
 */
interface ViewportPositionParams {
  /** Coordinate to find */
  coordinate: number;
  /** Dimension type */
  type: DimensionRows | DimensionCols;
}

/**
 * Position item information
 */
interface PositionItem {
  /** Item index */
  index: number;
  /** Item position */
  position: number;
  /** Item size */
  size: number;
}

/**
 * View setting size properties
 */
interface ViewSettingSizeProp {
  [index: number]: number;
}

Usage Example:

// Access providers through grid
const providers = await grid.getProviders();

// Use data provider
const dataProvider = providers.data;
dataProvider.setCellData({
  row: 0,
  col: 'name',
  val: 'Updated Name',
  rowSource: 'rgRow'
});

// Use column provider
const columnProvider = providers.column;
const columns = columnProvider.getColumns();
console.log('Current columns:', columns.length);

// Find column index
const nameColumnIndex = columnProvider.getColumnIndexByProp('name', 'rgCol');

// Use dimension provider
const dimensionProvider = providers.dimension;
const contentSize = dimensionProvider.getFullSize();
console.log('Content size:', contentSize);

// Set custom column sizes
dimensionProvider.setCustomSizes('rgCol', {
  0: 150, // First column 150px
  1: 200, // Second column 200px
  2: 100  // Third column 100px
});

Selection Store Connector

Service class for managing selection state across grid components.

/**
 * Selection store connector service
 */
class SelectionStoreConnector {
  /**
   * Set edit state for cell
   * @param val - Edit state value or null to clear
   */
  setEdit(val: EditCellStore | null): void;

  /**
   * Select all cells in grid
   */
  selectAll(): void;

  /**
   * Clear all selections and focus
   */
  clearAll(): void;

  /**
   * Handle focus navigation to next cell
   * @param event - Navigation event details
   */
  beforeNextFocusCell(event: BeforeNextFocusCellEvent): void;
}

/**
 * Before next focus cell event
 */
interface BeforeNextFocusCellEvent {
  /** Current focused cell */
  currentCell: Cell;
  /** Direction of navigation */
  direction: 'up' | 'down' | 'left' | 'right';
  /** Whether to wrap around edges */
  wrap: boolean;
}

Usage Example:

// Access selection connector
const providers = await grid.getProviders();
const selection = providers.selection;

// Select all cells
selection.selectAll();

// Clear selections
selection.clearAll();

// Set edit mode for specific cell
selection.setEdit({
  row: 2,
  col: 'email',
  val: 'editing...',
  rowType: 'rgRow'
});

// Clear edit mode
selection.setEdit(null);