CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vega

A declarative visualization grammar for creating interactive data visualizations through JSON specifications.

Pending
Overview
Eval results
Files

view.mddocs/

View Management

The View class is the central orchestrator for Vega visualizations, managing the complete lifecycle from initialization to rendering, data binding, signal management, and interaction handling.

Capabilities

View Constructor

Creates a new View instance from a parsed runtime specification.

/**
 * Creates a new View instance from a parsed runtime specification
 * @param runtime - Parsed Vega specification runtime
 * @param options - Optional view configuration
 */
class View {
  constructor(runtime: Runtime, options?: ViewOptions);
}

interface ViewOptions {
  /** Background color for the visualization */
  background?: Color;
  /** DOM element or selector for data binding controls */
  bind?: Element | string;
  /** DOM container element or selector */
  container?: Element | string;
  /** Enable hover event processing */
  hover?: boolean;
  /** Data loader instance */
  loader?: Loader;
  /** Logger interface for debugging */
  logger?: LoggerInterface;
  /** Logging level (0=None, 1=Error, 2=Warn, 3=Info, 4=Debug) */
  logLevel?: number;
  /** Rendering backend ('canvas', 'svg', or 'none') */
  renderer?: Renderers;
  /** Custom tooltip handler function */
  tooltip?: TooltipHandler;
  /** Locale formatters for numbers and dates */
  locale?: LocaleFormatters;
  /** Expression function registry */
  expr?: any;
  /** Watch for device pixel ratio changes */
  watchPixelRatio?: boolean;
}

type Color = string;
type Renderers = 'canvas' | 'svg' | 'none';
type TooltipHandler = (handler: any, event: MouseEvent, item: Item, value: any) => void;

interface LocaleFormatters {
  format: (spec: string) => NumberFormat;
  formatPrefix: (spec: string, value: number) => NumberFormat;
  formatFloat: (spec: string) => NumberFormat;
  formatSpan: (start: number, stop: number, count: number, spec: string) => NumberFormat;
  timeFormat: (spec: string) => TimeFormat;
  utcFormat: (spec: string) => TimeFormat;
  timeParse: (spec: string) => TimeParse;
  utcParse: (spec: string) => TimeParse;
}

View Initialization and Configuration

Methods for initializing the view and configuring its rendering context.

/**
 * Initialize the view with a container element
 * @param container - DOM element or CSS selector for the main container
 * @param bindContainer - DOM element or CSS selector for data binding controls
 * @returns The view instance for method chaining
 */
initialize(container?: Element | string, bindContainer?: Element | string): this;

/**
 * Finalize the view by removing timers and event listeners
 * @returns The view instance for method chaining
 */
finalize(): this;

/**
 * Set or get the data loader
 * @param loader - The loader instance to use
 * @returns The view instance for method chaining, or current loader if no argument
 */
loader(loader: Loader): this;
loader(): Loader;

/**
 * Set or get the logging level
 * @param level - Logging level (0=None, 1=Error, 2=Warn, 3=Info, 4=Debug)
 * @returns The view instance for method chaining, or current level if no argument
 */
logLevel(level: number): this;
logLevel(): number;

/**
 * Set or get the logger instance
 * @param logger - Logger interface implementation
 * @returns The view instance for method chaining, or current logger if no argument
 */
logger(logger: LoggerInterface): this;
logger(): LoggerInterface;

/**
 * Set or get the renderer type
 * @param renderer - Renderer type ('canvas', 'svg', or 'none')
 * @returns The view instance for method chaining, or current renderer if no argument
 */
renderer(renderer: Renderers): this;
renderer(): Renderers;

/**
 * Set the tooltip handler
 * @param handler - Custom tooltip handler function
 * @returns The view instance for method chaining
 */
tooltip(handler: TooltipHandler): this;

View Properties and Layout

Methods for managing view dimensions, background, padding, and other layout properties.

/**
 * Set or get the view description
 * @param s - Description string
 * @returns The view instance for method chaining, or current description if no argument
 */
description(s: string): this;
description(): string;

/**
 * Set or get the background color
 * @param s - Background color
 * @returns The view instance for method chaining, or current background if no argument
 */
background(s: Color): this;
background(): Color;

/**
 * Set or get the view width
 * @param w - Width in pixels
 * @returns The view instance for method chaining, or current width if no argument
 */
width(w: number): this;
width(): number;

/**
 * Set or get the view height
 * @param h - Height in pixels
 * @returns The view instance for method chaining, or current height if no argument
 */
height(h: number): this;
height(): number;

/**
 * Set or get the view padding
 * @param p - Padding specification
 * @returns The view instance for method chaining, or current padding if no argument
 */
padding(p: Padding): this;
padding(): Padding;

/**
 * Resize the view to fit its container
 * @returns The view instance for method chaining
 */
resize(): this;

/**
 * Get the container DOM element
 * @returns The container element or null if not set
 */
container(): HTMLElement | null;

/**
 * Get the view's coordinate origin
 * @returns Array of [x, y] coordinates
 */
origin(): [number, number];

type Padding = number | { left?: number; right?: number; top?: number; bottom?: number };

Rendering and Execution

Methods for executing the dataflow and rendering the visualization.

/**
 * Run the dataflow synchronously
 * @param encode - Optional encoding set to process
 * @returns The view instance for method chaining
 */
run(encode?: string): this;

/**
 * Run the dataflow asynchronously
 * @returns Promise that resolves to the view instance
 */
runAsync(): Promise<View>;

/**
 * Schedule a callback to run after the current dataflow pulse
 * @param callback - Function to call after rendering
 * @param enqueue - Whether to enqueue the callback if dataflow is not running
 * @param priority - Priority level for callback execution
 * @returns The view instance for method chaining
 */
runAfter(callback: (view: this) => void, enqueue?: boolean, priority?: number): this;

/**
 * Mark an item as dirty for re-rendering
 * @param item - The scene graph item to mark as dirty
 */
dirty(item: any): void;

/**
 * Get the current scenegraph
 * @returns The root scenegraph node
 */
scenegraph(): Scene;

interface Scene {
  marktype: string;
  items: Item[];
  bounds: Bounds;
}

interface Item<T = any> {
  datum: T;
  mark: RuntimeMark;
}

interface Bounds {
  x1: number;
  y1: number;
  x2: number;
  y2: number;
}

Signal Management

Methods for managing signals, which are reactive variables that drive visualization updates.

/**
 * Set or get a signal value
 * @param name - Signal name
 * @param value - New signal value (if setting)
 * @returns The view instance for method chaining (if setting), or current value (if getting)
 */
signal(name: string, value: SignalValue): this;
signal(name: string): SignalValue;

/**
 * Get the current view state including signals and data
 * @param options - Options for state extraction
 * @returns Object containing signals and data state
 */
getState(options?: {
  signals?: (name?: string, operator?: any) => boolean;
  data?: (name?: string, object?: any) => boolean;
  recurse?: boolean;
}): { signals?: any; data?: any };

/**
 * Set the view state from a previously extracted state object
 * @param state - State object containing signals and data
 * @returns The view instance for method chaining
 */
setState(state: { signals?: any; data?: any }): this;

/**
 * Add a signal listener
 * @param name - Signal name to listen to
 * @param handler - Handler function called when signal changes
 * @returns The view instance for method chaining
 */
addSignalListener(name: string, handler: SignalListenerHandler): this;

/**
 * Remove a signal listener
 * @param name - Signal name
 * @param handler - Handler function to remove
 * @returns The view instance for method chaining
 */
removeSignalListener(name: string, handler: SignalListenerHandler): this;

type SignalValue = any;
type SignalListenerHandler = (name: string, value: SignalValue) => void;

Data Management

Methods for accessing and modifying datasets within the visualization.

/**
 * Get or set data for a named dataset
 * @param name - Dataset name
 * @param tuples - Data tuples to set (if setting)
 * @returns Data array (if getting) or view instance for chaining (if setting)
 */
data(name: string): any[];
data(name: string, tuples: any): this;

/**
 * Apply a changeset to a dataset
 * @param name - Dataset name
 * @param changeset - Changeset with insert/remove/modify operations
 * @returns The view instance for method chaining
 */
change(name: string, changeset: Changeset): this;

/**
 * Insert data tuples into a dataset
 * @param name - Dataset name
 * @param tuples - Data tuples to insert
 * @returns The view instance for method chaining
 */
insert(name: string, tuples: any): this;

/**
 * Remove data tuples from a dataset
 * @param name - Dataset name
 * @param tuples - Data tuples to remove
 * @returns The view instance for method chaining
 */
remove(name: string, tuples: any): this;

/**
 * Add a data listener to be notified of data changes
 * @param name - Dataset name
 * @param handler - Handler function called when data changes
 * @returns The view instance for method chaining
 */
addDataListener(name: string, handler: DataListenerHandler): this;

/**
 * Remove a data listener
 * @param name - Dataset name
 * @param handler - Handler function to remove
 * @returns The view instance for method chaining
 */
removeDataListener(name: string, handler: DataListenerHandler): this;

/**
 * Create a new changeset for data modifications
 * @returns New changeset instance
 */
changeset(): Changeset;

interface Changeset {
  insert(tuples: any[]): Changeset;
  remove(tuples: any[]): Changeset;
  modify(tuples: any[], field?: string, value?: any): Changeset;
}

type DataListenerHandler = (name: string, value: any) => void;

Event Handling

Methods for managing event listeners and interaction.

/**
 * Add an event listener for scenegraph events
 * @param type - Event type ('click', 'mouseover', etc.)
 * @param handler - Event handler function
 * @returns The view instance for method chaining
 */
addEventListener(type: string, handler: EventListenerHandler): this;

/**
 * Remove an event listener
 * @param type - Event type
 * @param handler - Event handler function to remove
 * @returns The view instance for method chaining
 */
removeEventListener(type: string, handler: EventListenerHandler): this;

/**
 * Add a resize listener
 * @param handler - Handler function called when view is resized
 * @returns The view instance for method chaining
 */
addResizeListener(handler: ResizeHandler): this;

/**
 * Remove a resize listener
 * @param handler - Handler function to remove
 * @returns The view instance for method chaining
 */
removeResizeListener(handler: ResizeHandler): this;

/**
 * Configure hover behavior
 * @param hoverSet - Encoding set name for hover enter
 * @param leaveSet - Encoding set name for hover exit
 * @returns The view instance for method chaining
 */
hover(hoverSet?: EncodeEntryName, leaveSet?: EncodeEntryName): this;

/**
 * Get event stream for specified source and type
 * @param source - Event source
 * @param type - Event type
 * @param filter - Optional filter function
 * @returns Event stream
 */
events(source: any, type: any, filter?: (_: any) => boolean): any;

/**
 * Control global cursor visibility
 * @param flag - Whether to show global cursor
 * @returns Current cursor setting
 */
globalCursor(flag: boolean): any;

/**
 * Control event preventDefault behavior
 * @param flag - Whether to prevent default event behavior
 */
preventDefault(flag: boolean): void;

type EventListenerHandler = (event: ScenegraphEvent, item?: Item | null) => void;
type ResizeHandler = (width: number, height: number) => void;
type ScenegraphEvent = MouseEvent | TouchEvent | KeyboardEvent;
type EncodeEntryName = string;

Scale Access

Methods for accessing scale functions within the view.

/**
 * Get a scale function by name
 * @param name - Scale name
 * @returns Scale function or undefined if not found
 */
scale(name: string): any;

Image Export

Methods for exporting the visualization as images or markup.

/**
 * Export the view as an HTML5 Canvas
 * @param scaleFactor - Scale factor for export resolution
 * @param options - Canvas export options
 * @returns Promise resolving to HTMLCanvasElement
 */
toCanvas(scaleFactor?: number, options?: ToCanvasOptions): Promise<HTMLCanvasElement>;

/**
 * Export the view as SVG markup
 * @param scaleFactor - Scale factor for export resolution
 * @returns Promise resolving to SVG string
 */
toSVG(scaleFactor?: number): Promise<string>;

/**
 * Export the view as a data URL
 * @param type - Image format ('image/png', 'image/jpeg', etc.)
 * @param scaleFactor - Scale factor for export resolution
 * @returns Promise resolving to data URL string
 */
toImageURL(type: string, scaleFactor?: number): Promise<string>;

interface ToCanvasOptions {
  type?: string;
  context?: any;
  externalContext?: any;
}

Usage Examples

Basic View Setup

import { parse, View, loader } from "vega";

const spec = { /* your Vega specification */ };
const runtime = parse(spec);

const view = new View(runtime, {
  renderer: 'canvas',
  loader: loader(),
  logLevel: vega.Warn
});

view.initialize('#visualization').run();

Data Updates

// Replace entire dataset
view.data('myData', newDataArray).run();

// Incremental updates
const cs = view.changeset()
  .insert([{x: 1, y: 2}])
  .remove([{x: 0, y: 1}]);

view.change('myData', cs).run();

Signal Interaction

// Set signal values
view.signal('selectedCategory', 'A').run();

// Listen to signal changes
view.addSignalListener('selectedCategory', (name, value) => {
  console.log(`Signal ${name} changed to:`, value);
});

Event Handling

// Add click handler
view.addEventListener('click', (event, item) => {
  if (item) {
    console.log('Clicked on:', item.datum);
  }
});

// Add resize handler
view.addResizeListener((width, height) => {
  console.log(`View resized to ${width}x${height}`);
});

Image Export

// Export as PNG
view.toImageURL('image/png').then(url => {
  const link = document.createElement('a');
  link.download = 'visualization.png';
  link.href = url;
  link.click();
});

// Export as SVG
view.toSVG().then(svg => {
  const blob = new Blob([svg], {type: 'image/svg+xml'});
  const url = URL.createObjectURL(blob);
  // Use the URL...
});

Install with Tessl CLI

npx tessl i tessl/npm-vega

docs

data-loading.md

dataflow.md

events.md

expressions.md

index.md

parsing.md

scales.md

scenegraph.md

statistics.md

time.md

utilities.md

view.md

tile.json