or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-loading.mddataflow.mdevents.mdexpressions.mdindex.mdparsing.mdscales.mdscenegraph.mdstatistics.mdtime.mdutilities.mdview.md

view.mddocs/

0

# View Management

1

2

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.

3

4

## Capabilities

5

6

### View Constructor

7

8

Creates a new View instance from a parsed runtime specification.

9

10

```typescript { .api }

11

/**

12

* Creates a new View instance from a parsed runtime specification

13

* @param runtime - Parsed Vega specification runtime

14

* @param options - Optional view configuration

15

*/

16

class View {

17

constructor(runtime: Runtime, options?: ViewOptions);

18

}

19

20

interface ViewOptions {

21

/** Background color for the visualization */

22

background?: Color;

23

/** DOM element or selector for data binding controls */

24

bind?: Element | string;

25

/** DOM container element or selector */

26

container?: Element | string;

27

/** Enable hover event processing */

28

hover?: boolean;

29

/** Data loader instance */

30

loader?: Loader;

31

/** Logger interface for debugging */

32

logger?: LoggerInterface;

33

/** Logging level (0=None, 1=Error, 2=Warn, 3=Info, 4=Debug) */

34

logLevel?: number;

35

/** Rendering backend ('canvas', 'svg', or 'none') */

36

renderer?: Renderers;

37

/** Custom tooltip handler function */

38

tooltip?: TooltipHandler;

39

/** Locale formatters for numbers and dates */

40

locale?: LocaleFormatters;

41

/** Expression function registry */

42

expr?: any;

43

/** Watch for device pixel ratio changes */

44

watchPixelRatio?: boolean;

45

}

46

47

type Color = string;

48

type Renderers = 'canvas' | 'svg' | 'none';

49

type TooltipHandler = (handler: any, event: MouseEvent, item: Item, value: any) => void;

50

51

interface LocaleFormatters {

52

format: (spec: string) => NumberFormat;

53

formatPrefix: (spec: string, value: number) => NumberFormat;

54

formatFloat: (spec: string) => NumberFormat;

55

formatSpan: (start: number, stop: number, count: number, spec: string) => NumberFormat;

56

timeFormat: (spec: string) => TimeFormat;

57

utcFormat: (spec: string) => TimeFormat;

58

timeParse: (spec: string) => TimeParse;

59

utcParse: (spec: string) => TimeParse;

60

}

61

```

62

63

### View Initialization and Configuration

64

65

Methods for initializing the view and configuring its rendering context.

66

67

```typescript { .api }

68

/**

69

* Initialize the view with a container element

70

* @param container - DOM element or CSS selector for the main container

71

* @param bindContainer - DOM element or CSS selector for data binding controls

72

* @returns The view instance for method chaining

73

*/

74

initialize(container?: Element | string, bindContainer?: Element | string): this;

75

76

/**

77

* Finalize the view by removing timers and event listeners

78

* @returns The view instance for method chaining

79

*/

80

finalize(): this;

81

82

/**

83

* Set or get the data loader

84

* @param loader - The loader instance to use

85

* @returns The view instance for method chaining, or current loader if no argument

86

*/

87

loader(loader: Loader): this;

88

loader(): Loader;

89

90

/**

91

* Set or get the logging level

92

* @param level - Logging level (0=None, 1=Error, 2=Warn, 3=Info, 4=Debug)

93

* @returns The view instance for method chaining, or current level if no argument

94

*/

95

logLevel(level: number): this;

96

logLevel(): number;

97

98

/**

99

* Set or get the logger instance

100

* @param logger - Logger interface implementation

101

* @returns The view instance for method chaining, or current logger if no argument

102

*/

103

logger(logger: LoggerInterface): this;

104

logger(): LoggerInterface;

105

106

/**

107

* Set or get the renderer type

108

* @param renderer - Renderer type ('canvas', 'svg', or 'none')

109

* @returns The view instance for method chaining, or current renderer if no argument

110

*/

111

renderer(renderer: Renderers): this;

112

renderer(): Renderers;

113

114

/**

115

* Set the tooltip handler

116

* @param handler - Custom tooltip handler function

117

* @returns The view instance for method chaining

118

*/

119

tooltip(handler: TooltipHandler): this;

120

```

121

122

### View Properties and Layout

123

124

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

125

126

```typescript { .api }

127

/**

128

* Set or get the view description

129

* @param s - Description string

130

* @returns The view instance for method chaining, or current description if no argument

131

*/

132

description(s: string): this;

133

description(): string;

134

135

/**

136

* Set or get the background color

137

* @param s - Background color

138

* @returns The view instance for method chaining, or current background if no argument

139

*/

140

background(s: Color): this;

141

background(): Color;

142

143

/**

144

* Set or get the view width

145

* @param w - Width in pixels

146

* @returns The view instance for method chaining, or current width if no argument

147

*/

148

width(w: number): this;

149

width(): number;

150

151

/**

152

* Set or get the view height

153

* @param h - Height in pixels

154

* @returns The view instance for method chaining, or current height if no argument

155

*/

156

height(h: number): this;

157

height(): number;

158

159

/**

160

* Set or get the view padding

161

* @param p - Padding specification

162

* @returns The view instance for method chaining, or current padding if no argument

163

*/

164

padding(p: Padding): this;

165

padding(): Padding;

166

167

/**

168

* Resize the view to fit its container

169

* @returns The view instance for method chaining

170

*/

171

resize(): this;

172

173

/**

174

* Get the container DOM element

175

* @returns The container element or null if not set

176

*/

177

container(): HTMLElement | null;

178

179

/**

180

* Get the view's coordinate origin

181

* @returns Array of [x, y] coordinates

182

*/

183

origin(): [number, number];

184

185

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

186

```

187

188

### Rendering and Execution

189

190

Methods for executing the dataflow and rendering the visualization.

191

192

```typescript { .api }

193

/**

194

* Run the dataflow synchronously

195

* @param encode - Optional encoding set to process

196

* @returns The view instance for method chaining

197

*/

198

run(encode?: string): this;

199

200

/**

201

* Run the dataflow asynchronously

202

* @returns Promise that resolves to the view instance

203

*/

204

runAsync(): Promise<View>;

205

206

/**

207

* Schedule a callback to run after the current dataflow pulse

208

* @param callback - Function to call after rendering

209

* @param enqueue - Whether to enqueue the callback if dataflow is not running

210

* @param priority - Priority level for callback execution

211

* @returns The view instance for method chaining

212

*/

213

runAfter(callback: (view: this) => void, enqueue?: boolean, priority?: number): this;

214

215

/**

216

* Mark an item as dirty for re-rendering

217

* @param item - The scene graph item to mark as dirty

218

*/

219

dirty(item: any): void;

220

221

/**

222

* Get the current scenegraph

223

* @returns The root scenegraph node

224

*/

225

scenegraph(): Scene;

226

227

interface Scene {

228

marktype: string;

229

items: Item[];

230

bounds: Bounds;

231

}

232

233

interface Item<T = any> {

234

datum: T;

235

mark: RuntimeMark;

236

}

237

238

interface Bounds {

239

x1: number;

240

y1: number;

241

x2: number;

242

y2: number;

243

}

244

```

245

246

### Signal Management

247

248

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

249

250

```typescript { .api }

251

/**

252

* Set or get a signal value

253

* @param name - Signal name

254

* @param value - New signal value (if setting)

255

* @returns The view instance for method chaining (if setting), or current value (if getting)

256

*/

257

signal(name: string, value: SignalValue): this;

258

signal(name: string): SignalValue;

259

260

/**

261

* Get the current view state including signals and data

262

* @param options - Options for state extraction

263

* @returns Object containing signals and data state

264

*/

265

getState(options?: {

266

signals?: (name?: string, operator?: any) => boolean;

267

data?: (name?: string, object?: any) => boolean;

268

recurse?: boolean;

269

}): { signals?: any; data?: any };

270

271

/**

272

* Set the view state from a previously extracted state object

273

* @param state - State object containing signals and data

274

* @returns The view instance for method chaining

275

*/

276

setState(state: { signals?: any; data?: any }): this;

277

278

/**

279

* Add a signal listener

280

* @param name - Signal name to listen to

281

* @param handler - Handler function called when signal changes

282

* @returns The view instance for method chaining

283

*/

284

addSignalListener(name: string, handler: SignalListenerHandler): this;

285

286

/**

287

* Remove a signal listener

288

* @param name - Signal name

289

* @param handler - Handler function to remove

290

* @returns The view instance for method chaining

291

*/

292

removeSignalListener(name: string, handler: SignalListenerHandler): this;

293

294

type SignalValue = any;

295

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

296

```

297

298

### Data Management

299

300

Methods for accessing and modifying datasets within the visualization.

301

302

```typescript { .api }

303

/**

304

* Get or set data for a named dataset

305

* @param name - Dataset name

306

* @param tuples - Data tuples to set (if setting)

307

* @returns Data array (if getting) or view instance for chaining (if setting)

308

*/

309

data(name: string): any[];

310

data(name: string, tuples: any): this;

311

312

/**

313

* Apply a changeset to a dataset

314

* @param name - Dataset name

315

* @param changeset - Changeset with insert/remove/modify operations

316

* @returns The view instance for method chaining

317

*/

318

change(name: string, changeset: Changeset): this;

319

320

/**

321

* Insert data tuples into a dataset

322

* @param name - Dataset name

323

* @param tuples - Data tuples to insert

324

* @returns The view instance for method chaining

325

*/

326

insert(name: string, tuples: any): this;

327

328

/**

329

* Remove data tuples from a dataset

330

* @param name - Dataset name

331

* @param tuples - Data tuples to remove

332

* @returns The view instance for method chaining

333

*/

334

remove(name: string, tuples: any): this;

335

336

/**

337

* Add a data listener to be notified of data changes

338

* @param name - Dataset name

339

* @param handler - Handler function called when data changes

340

* @returns The view instance for method chaining

341

*/

342

addDataListener(name: string, handler: DataListenerHandler): this;

343

344

/**

345

* Remove a data listener

346

* @param name - Dataset name

347

* @param handler - Handler function to remove

348

* @returns The view instance for method chaining

349

*/

350

removeDataListener(name: string, handler: DataListenerHandler): this;

351

352

/**

353

* Create a new changeset for data modifications

354

* @returns New changeset instance

355

*/

356

changeset(): Changeset;

357

358

interface Changeset {

359

insert(tuples: any[]): Changeset;

360

remove(tuples: any[]): Changeset;

361

modify(tuples: any[], field?: string, value?: any): Changeset;

362

}

363

364

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

365

```

366

367

### Event Handling

368

369

Methods for managing event listeners and interaction.

370

371

```typescript { .api }

372

/**

373

* Add an event listener for scenegraph events

374

* @param type - Event type ('click', 'mouseover', etc.)

375

* @param handler - Event handler function

376

* @returns The view instance for method chaining

377

*/

378

addEventListener(type: string, handler: EventListenerHandler): this;

379

380

/**

381

* Remove an event listener

382

* @param type - Event type

383

* @param handler - Event handler function to remove

384

* @returns The view instance for method chaining

385

*/

386

removeEventListener(type: string, handler: EventListenerHandler): this;

387

388

/**

389

* Add a resize listener

390

* @param handler - Handler function called when view is resized

391

* @returns The view instance for method chaining

392

*/

393

addResizeListener(handler: ResizeHandler): this;

394

395

/**

396

* Remove a resize listener

397

* @param handler - Handler function to remove

398

* @returns The view instance for method chaining

399

*/

400

removeResizeListener(handler: ResizeHandler): this;

401

402

/**

403

* Configure hover behavior

404

* @param hoverSet - Encoding set name for hover enter

405

* @param leaveSet - Encoding set name for hover exit

406

* @returns The view instance for method chaining

407

*/

408

hover(hoverSet?: EncodeEntryName, leaveSet?: EncodeEntryName): this;

409

410

/**

411

* Get event stream for specified source and type

412

* @param source - Event source

413

* @param type - Event type

414

* @param filter - Optional filter function

415

* @returns Event stream

416

*/

417

events(source: any, type: any, filter?: (_: any) => boolean): any;

418

419

/**

420

* Control global cursor visibility

421

* @param flag - Whether to show global cursor

422

* @returns Current cursor setting

423

*/

424

globalCursor(flag: boolean): any;

425

426

/**

427

* Control event preventDefault behavior

428

* @param flag - Whether to prevent default event behavior

429

*/

430

preventDefault(flag: boolean): void;

431

432

type EventListenerHandler = (event: ScenegraphEvent, item?: Item | null) => void;

433

type ResizeHandler = (width: number, height: number) => void;

434

type ScenegraphEvent = MouseEvent | TouchEvent | KeyboardEvent;

435

type EncodeEntryName = string;

436

```

437

438

### Scale Access

439

440

Methods for accessing scale functions within the view.

441

442

```typescript { .api }

443

/**

444

* Get a scale function by name

445

* @param name - Scale name

446

* @returns Scale function or undefined if not found

447

*/

448

scale(name: string): any;

449

```

450

451

### Image Export

452

453

Methods for exporting the visualization as images or markup.

454

455

```typescript { .api }

456

/**

457

* Export the view as an HTML5 Canvas

458

* @param scaleFactor - Scale factor for export resolution

459

* @param options - Canvas export options

460

* @returns Promise resolving to HTMLCanvasElement

461

*/

462

toCanvas(scaleFactor?: number, options?: ToCanvasOptions): Promise<HTMLCanvasElement>;

463

464

/**

465

* Export the view as SVG markup

466

* @param scaleFactor - Scale factor for export resolution

467

* @returns Promise resolving to SVG string

468

*/

469

toSVG(scaleFactor?: number): Promise<string>;

470

471

/**

472

* Export the view as a data URL

473

* @param type - Image format ('image/png', 'image/jpeg', etc.)

474

* @param scaleFactor - Scale factor for export resolution

475

* @returns Promise resolving to data URL string

476

*/

477

toImageURL(type: string, scaleFactor?: number): Promise<string>;

478

479

interface ToCanvasOptions {

480

type?: string;

481

context?: any;

482

externalContext?: any;

483

}

484

```

485

486

## Usage Examples

487

488

### Basic View Setup

489

490

```typescript

491

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

492

493

const spec = { /* your Vega specification */ };

494

const runtime = parse(spec);

495

496

const view = new View(runtime, {

497

renderer: 'canvas',

498

loader: loader(),

499

logLevel: vega.Warn

500

});

501

502

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

503

```

504

505

### Data Updates

506

507

```typescript

508

// Replace entire dataset

509

view.data('myData', newDataArray).run();

510

511

// Incremental updates

512

const cs = view.changeset()

513

.insert([{x: 1, y: 2}])

514

.remove([{x: 0, y: 1}]);

515

516

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

517

```

518

519

### Signal Interaction

520

521

```typescript

522

// Set signal values

523

view.signal('selectedCategory', 'A').run();

524

525

// Listen to signal changes

526

view.addSignalListener('selectedCategory', (name, value) => {

527

console.log(`Signal ${name} changed to:`, value);

528

});

529

```

530

531

### Event Handling

532

533

```typescript

534

// Add click handler

535

view.addEventListener('click', (event, item) => {

536

if (item) {

537

console.log('Clicked on:', item.datum);

538

}

539

});

540

541

// Add resize handler

542

view.addResizeListener((width, height) => {

543

console.log(`View resized to ${width}x${height}`);

544

});

545

```

546

547

### Image Export

548

549

```typescript

550

// Export as PNG

551

view.toImageURL('image/png').then(url => {

552

const link = document.createElement('a');

553

link.download = 'visualization.png';

554

link.href = url;

555

link.click();

556

});

557

558

// Export as SVG

559

view.toSVG().then(svg => {

560

const blob = new Blob([svg], {type: 'image/svg+xml'});

561

const url = URL.createObjectURL(blob);

562

// Use the URL...

563

});

564

```