### Example of a Configuration Option Source: https://github.com/vega/vega-embed/blob/main/_autodocs/MANIFEST.txt Configuration documents detail options, their types, default values, and usage examples. This snippet illustrates a typical configuration entry. ```typescript optionName: string; defaultValue: "someValue"; description: "This option controls behavior X."; usageExamples: [ "// Example usage: optionName = 'anotherValue'" ]; ``` -------------------------------- ### CSP-Compliant Setup Source: https://github.com/vega/vega-embed/blob/main/_autodocs/configuration.md Configure for Content Security Policy compliance using AST and a custom interpreter. ```typescript { ast: true, expr: customInterpreter } ``` -------------------------------- ### Install Vega-Embed Source: https://github.com/vega/vega-embed/blob/main/_autodocs/quick-reference.md Install the vega, vega-lite, and vega-embed packages using npm. Peer dependencies require vega and vega-lite to be installed. ```bash npm install vega vega-lite vega-embed ``` -------------------------------- ### TypeScript Syntax for Code Examples Source: https://github.com/vega/vega-embed/blob/main/_autodocs/MANIFEST.txt Code examples within the documentation primarily use TypeScript syntax. This ensures type safety and clarity for developers. ```typescript function example(param: string): boolean { // Function implementation return true; } ``` -------------------------------- ### Get Vega-Embed Version Information Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-overview.md Import and log the version numbers of vega-embed, vega, and vega-lite. Ensure you have these libraries installed. ```typescript import {version, vega, vegaLite} from 'vega-embed'; console.log('vega-embed:', version); console.log('vega:', vega.version); console.log('vega-lite:', vegaLite.version); ``` -------------------------------- ### Configure baseURL for Remote Datasets Source: https://github.com/vega/vega-embed/blob/main/test-baseurl.html Use the `loader.baseURL` option to specify the base URL for remote datasets. This example loads images from the vega-github.io datasets. ```javascript async function run() { const spec = { "$schema": "https://vega.github.io/schema/vega-lite/v6.json", "view": {"stroke": null}, "data": {"values": [{"image": "data/ffox.png"}, {"image": "data/gimp.png"}, {"image": "data/7zip.png"}]}, "mark": "text", "encoding": { "text": {"field": "image"}, "y": {"field": "image", "axis": null}, "tooltip": [{"field": "image"}] }, }; const result = await vegaEmbed('#vis', spec, { loader: { baseURL: 'https://vega.github.io/vega-datasets/' }, }); console.log(result); } run(); ``` -------------------------------- ### Dispatch to container (spec from URL) Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/wrapper-function.md Example of using the wrapper function when the first argument is a URL, dispatching to the container() function. ```typescript import embed from 'vega-embed'; const result = await embed('https://example.com/spec.json'); // Calls container() → HTMLDivElement with value property containing View ``` -------------------------------- ### Handling Version Mismatch Warnings Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md Example of a Vega-Lite v4 spec being used with Vega-Lite v5 installed, triggering a logger warning. This demonstrates how to check and update the log level or custom logger. ```typescript // Spec uses Vega-Lite v4, but v5 is installed const spec = { $schema: 'https://vega.github.io/schema/vega-lite/v4.json', mark: 'bar' }; const result = await embed('#vis', spec); // Warning: "The input spec uses Vega-Lite v4, but the current version of Vega-Lite is v5" ``` -------------------------------- ### Call container with local URL-like string Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/wrapper-function.md Example of using the wrapper with a local URL-like string, which is interpreted as a URL and dispatches to the container() function. ```typescript const result = await embed('/specs/my-chart.json', {actions: false}); // URL starts with / → calls container() ``` -------------------------------- ### View Control Methods Source: https://github.com/vega/vega-embed/blob/main/_autodocs/quick-reference.md The Vega View instance allows for dynamic control of the visualization, including setting and getting signals, listening to signal changes and mark events, accessing data, and exporting the view. ```APIDOC ## View Control The `view` object, accessible via `result.view`, provides methods to interact with the embedded Vega visualization. ### Methods - **`view.signal(name, value)`**: Sets a signal's value. Returns the view instance for chaining. - **`view.signal(name)`**: Gets the current value of a signal. - **`view.runAsync()`**: Runs the view asynchronously. - **`view.addSignalListener(name, handler)`**: Adds a listener for changes to a specific signal. - `name` (string): The name of the signal to listen to. - `handler` (function): The callback function executed when the signal changes. Receives `name` and `value`. - **`view.addMarkListener(name, handler)`**: Adds a listener for events on a specific mark. - `name` (string): The name of the mark to listen to. - `handler` (function): The callback function executed when the mark is interacted with. Receives `item` and `event`. - **`view.data(name)`**: Accesses the data associated with a specific data source. - **`view.toImageURL(type)`**: Exports the view as an image URL. - `type` (string): The image format ('png' or 'svg'). Returns a Promise resolving to the image URL. ### Cleanup - **`result.finalize()`**: It is crucial to call this function to release resources held by the embedded view when it is no longer needed. ``` -------------------------------- ### Data Visualization Dashboard Configuration Source: https://github.com/vega/vega-embed/blob/main/_autodocs/configuration.md Optimize for performance with canvas renderer and enable tooltips and hover effects for a dashboard setup. Export action is enabled, but source and editor are disabled. ```typescript { renderer: 'canvas', // Better performance for many marks tooltip: true, hover: true, actions: {export: true, source: false, editor: false} } ``` -------------------------------- ### Custom CSS for Actions Menu Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md Provides example CSS selectors for styling the actions menu container and its links when default styles are disabled. The container has the class `vega-actions`. ```css .vega-actions { /* Custom styles */ } .vega-actions a { display: block; padding: 8px 12px; } ``` -------------------------------- ### Accessing and Controlling the Vega View Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/result-interface.md The `view` property provides the primary interface for programmatic control of the visualization. You can use it to get or set signal values, access data tables, listen for signal or data changes, and export the visualization as an image. ```typescript const result = await embed('#vis', spec); const view = result.view; // Set a signal value view.signal('opacity', 0.5).runAsync(); // Get a signal value console.log(view.signal('opacity')); // 0.5 // Listen to signal changes view.addSignalListener('selected', (name, value) => { console.log('Selection changed:', value); }); // Access data table const data = view.data('table'); console.log(data.values()); // Array of data values ``` -------------------------------- ### Access Vega Libraries and Versions Source: https://github.com/vega/vega-embed/blob/main/_autodocs/quick-reference.md Import and log the versions of vega, vega-lite, and vega-embed. Demonstrates basic usage of Vega APIs like formatLocale and compile. ```typescript import {vega, vegaLite, version} from 'vega-embed'; console.log('vega-embed:', version); console.log('vega:', vega.version); console.log('vega-lite:', vegaLite.version); // Use Vega APIs vega.formatLocale({decimal: ',', thousands: '.'}); const compiled = vegaLite.compile(spec); ``` -------------------------------- ### Configuration Reference Source: https://github.com/vega/vega-embed/blob/main/_autodocs/README.md Detailed documentation for all `EmbedOptions`, covering rendering, styling, interactivity, data loading, and localization. ```APIDOC ## Configuration Reference (EmbedOptions) ### Description This comprehensive reference details all available `EmbedOptions` for customizing the behavior and appearance of Vega and Vega-Lite visualizations when embedded using `vega-embed`. It covers a wide range of settings organized into logical categories. ### Categories - **Rendering**: Options related to how the visualization is drawn. - **Styling**: Options for controlling the visual presentation. - **Theming**: Settings for applying themes to visualizations. - **Interactivity**: Options for enabling and configuring user interactions. - **Data Loading**: Settings for how data is fetched and managed. - **Localization**: Options for internationalization and language settings. - **Advanced**: Various other advanced configuration parameters. ### Key Considerations - **Precedence Rules**: How different configuration settings are prioritized. - **Security Considerations**: Important security aspects related to embedding and data loading. ``` -------------------------------- ### Apply Custom Configuration Source: https://github.com/vega/vega-embed/blob/main/_autodocs/quick-reference.md Apply custom configuration settings, such as setting the background color. ```json {config: {background: 'white'}} ``` -------------------------------- ### Errors & Error Handling Source: https://github.com/vega/vega-embed/blob/main/_autodocs/README.md Reference for all error conditions encountered during embedding, with examples and guidance on how to catch and fix them. ```APIDOC ## Errors & Error Handling ### Description This section provides a reference for the various error conditions that can occur when using the `vega-embed` library. It includes detailed explanations of each error, examples of how they might be triggered, and guidance on how to effectively catch and resolve them. ### Error Conditions - **Number of Errors**: Details 6 or more distinct error conditions. - **Examples**: Illustrative examples demonstrating how errors manifest. - **Catching Errors**: Guidance on using `try...catch` blocks and promise `.catch()` methods. - **Fixing Errors**: Practical advice and solutions for common error scenarios. - **Error Handling Patterns**: Recommended patterns for robust error management in applications using `vega-embed`. ``` -------------------------------- ### Data Exploration UI Configuration (Full Actions) Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md Enable all actions for data exploration, including export, source, compiled, and editor views, with optional header and footer content. ```typescript { actions: true, sourceHeader: '...', // Add syntax highlighting sourceFooter: '...' } ``` -------------------------------- ### actions-configuration.md Source: https://github.com/vega/vega-embed/blob/main/_autodocs/MANIFEST.txt Documentation for configuring the action menu that can be displayed with embedded visualizations. ```APIDOC ## Action Menu Configuration ### Description This section details the options available for configuring the action menu, which provides users with interactive controls such as 'Save Image', 'View Source', and 'Inspector'. ### Configuration Options - **actions** (boolean | object) - If `true`, enables the default action menu. If an object, allows for custom configuration of menu items. - **save** (boolean | string) - Enable/disable saving the visualization as an image. Can be a boolean or a custom filename. - **source** (boolean) - Enable/disable showing the source specification. - **inspector** (boolean) - Enable/disable the data inspector. ### Usage Example ```typescript embed('#vis', spec, { actions: { save: 'my-visualization.png', source: false } }); ``` ``` -------------------------------- ### Apply a Theme Source: https://github.com/vega/vega-embed/blob/main/_autodocs/quick-reference.md Apply a predefined theme to the visualization. ```json {theme: 'dark'} ``` -------------------------------- ### Configure Tooltip Options for Embed Source: https://github.com/vega/vega-embed/blob/main/_autodocs/configuration.md Illustrates how to configure tooltip display behavior, including delay and offsets, by passing a TooltipOptions object. ```typescript const result = await embed('#vis', spec, { tooltip: { delay: 300, // Milliseconds before showing tooltip offsetX: 10, // Horizontal offset offsetY: 10 // Vertical offset } }); ``` -------------------------------- ### Dispatch to embed (element + spec) Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/wrapper-function.md Example of using the wrapper function when the first argument is a DOM element or CSS selector, dispatching to the embed() function. ```typescript import embed from 'vega-embed'; const spec = {mark: 'bar', encoding: {x: {field: 'a'}}}; const result = await embed('#vis', spec); // Calls embed() → Result object with view, spec, vgSpec, finalize ``` -------------------------------- ### Enable CSP Compliance Source: https://github.com/vega/vega-embed/blob/main/_autodocs/quick-reference.md Enable settings for Content Security Policy (CSP) compliance. ```json {ast: true} ``` -------------------------------- ### isURL Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/utility-functions.md Checks if a string is an absolute or protocol-relative URL. It returns true if the string starts with 'http://', 'https://', or '//', and false otherwise. ```APIDOC ## isURL ### Description Checks if a string is an absolute or protocol-relative URL. ### Method N/A (Function Signature) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **s** (string) - Required - The string to check. ### Return Type `boolean` — `true` if the string starts with `http://`, `https://`, or `//`; `false` otherwise. ### Usage ```typescript import {isURL} from 'vega-embed'; isURL('http://example.com/spec.json'); // true isURL('https://example.com/spec.json'); // true isURL('//example.com/spec.json'); // true isURL('/local/spec.json'); // false isURL('spec.json'); // false ``` ``` -------------------------------- ### Access Vega Utilities Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/vega-and-vegaLite.md Demonstrates how to use the exported Vega module to create loggers, data loaders, and set locale formats. ```typescript import {vega} from 'vega-embed'; // Create a logger const logger = vega.logger(vega.Warn); // Create a data loader with custom options const loader = vega.loader({target: '_blank'}); // Set number format locale vega.formatLocale({decimal: ',', thousands: '.'}); ``` -------------------------------- ### Check if a string is a URL Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/utility-functions.md Checks if a string is an absolute or protocol-relative URL. Returns true for strings starting with 'http://', 'https://', or '//'. ```typescript export function isURL(s: string): boolean ``` ```typescript import {isURL} from 'vega-embed'; isURL('http://example.com/spec.json'); // true isURL('https://example.com/spec.json'); // true isURL('//example.com/spec.json'); // true isURL('/local/spec.json'); // false isURL('spec.json'); // false ``` -------------------------------- ### Compare Library Versions Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/version.md Import the library version and use `semver` to check if it meets a specific version requirement. ```typescript import {version} from 'vega-embed'; import satisfies from 'semver/functions/satisfies.js'; if (satisfies(version, '>=7.0.0')) { // Use features available in 7.0.0 or later } ``` -------------------------------- ### Customizing Logger for Warnings Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md Configure Vega-Embed to only show warnings and errors by setting a custom logger or adjusting the logLevel. This example sets the logger to only capture warnings and errors. ```typescript import {logger as vegaLogger} from 'vega'; const result = await embed('#vis', spec, { logger: vegaLogger(vegaLogger.Warn), // Only warnings and errors logLevel: 1 // Set to Error level }); ``` -------------------------------- ### EmbedOptions Source: https://github.com/vega/vega-embed/blob/main/_autodocs/types.md Configuration options for embedding Vega and Vega-Lite visualizations. ```APIDOC ## EmbedOptions | Option | Type | Required | Default | Description | |---|---|---|---|---| | `bind` | `HTMLElement | string` | No | — | DOM element or CSS selector for binding input elements to signals. | | `actions` | `boolean | Actions` | No | `{export: {svg: true, png: true}, source: true, compiled: false, editor: true}` | Show action links. `true` enables all, `false` disables all, or provide `Actions` object for granular control. | | `mode` | `Mode` | No | — | Explicitly set 'vega' or 'vega-lite'. If not provided, auto-detected from spec. | | `theme` | `keyof Omit` | No | — | Named theme from vega-themes package (e.g., 'dark', 'excel', 'ggplot2', 'quartz', 'vox'). | | `defaultStyle` | `boolean | string` | No | `true` | Inject default Vega-Embed styles. Set to `false` to use custom styles only, or provide a CSS string. | | `forceActionsMenu` | `boolean` | No | `false` | Force actions to display in a menu dropdown regardless of `defaultStyle` setting. | | `logLevel` | `number` | No | — | Vega logger level (0=None, 1=Error, 2=Warn, 3=Info, 4=Debug). | | `logger` | `Logger` | No | `vega.logger(vega.Warn)` | Custom Vega logger instance. | | `loader` | `Loader | LoaderOptions` | No | — | Vega data loader instance or configuration options. Controls how external data is fetched. | | `renderer` | `R` | No | `'svg'` | Renderer type: 'svg', 'canvas', or custom. | | `tooltip` | `TooltipHandler | TooltipOptions | boolean` | No | `true` | Tooltip behavior. `true` uses default Vega Tooltip, `false` disables, function for custom handler, or object for tooltip options. | | `patch` | `S | PatchFunc | Operation[]` | No | — | Specification patch as a function, RFC 6902 JSON Patch array, or URL string. Applied after Vega-Lite compilation. | | `width` | `number` | No | — | View width in pixels. Note: Vega-Lite may override this. | | `height` | `number` | No | — | View height in pixels. Note: Vega-Lite may override this. | | `padding` | `number | {left?: number; right?: number; top?: number; bottom?: number}` | No | — | View padding in pixels. | | `scaleFactor` | `number | {svg?: number; png?: number}` | No | `1` | Multiplier for export image dimensions. | | `config` | `S | Config` | No | — | Vega/Vega-Lite configuration object or URL to load from. Merged with theme config if theme is set. | | `sourceHeader` | `string` | No | `''` | HTML to inject into the `` of the source view page (for syntax highlighting, etc.). | | `sourceFooter` | `string` | No | `''` | HTML to inject before the closing `` tag of the source view page. | | `editorUrl` | `string` | No | `'https://vega.github.io/editor/'` | URL of the Vega editor for the "Open in Editor" action. | | `hover` | `boolean | Hover` | No | `true` for Vega, `false` for Vega-Lite | Enable hover event processing. For Vega only by default. | | `i18n` | `Partial` | No | English | Translation object for action text. Keys: `COMPILED_ACTION`, `EDITOR_ACTION`, `PNG_ACTION`, `SOURCE_ACTION`, `SVG_ACTION`. | | `downloadFileName` | `string` | No | `'visualization'` | File name for downloaded PNG/SVG exports (without extension). | | `formatLocale` | `Record` | No | — | d3-format locale definition for number formatting. Globally sets the default locale. | | `timeFormatLocale` | `Record` | No | — | d3-time-format locale definition for date/time formatting. Globally sets the default locale. | | `expressionFunctions` | `ExpressionFunction` | No | — | Custom Vega expression functions. Maps function name to function or `{fn: Function, visitor?: any}`. | | `ast` | `boolean` | No | `false` | Use Abstract Syntax Tree (AST) instead of native expression evaluation. Required for CSP compliance. | | `expr` | `typeof expressionInterpreter` | No | — | Custom Vega expression interpreter. Used when `ast` is true. | | `viewClass` | `typeof View` | No | `vega.View` | Custom View class extending Vega's View for custom rendering. | ``` -------------------------------- ### Catching Network Errors with try-catch Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md Use a try-catch block to handle potential network errors when embedding a specification from a URL. This example specifically checks for fetch-related TypeErrors. ```typescript try { const result = await embed('#vis', 'https://example.com/spec.json'); } catch (error) { if (error instanceof TypeError && error.message.includes('fetch')) { console.error('Network error loading specification'); } } ``` -------------------------------- ### Example of Invalid Vega-Lite Specification Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md This code snippet shows an invalid Vega-Lite specification with an encoding that references a non-existent field. This can lead to compilation errors when attempting to embed. ```typescript const spec = { mark: 'bar', encoding: {x: {field: 'nonexistent', type: 'nominal'}}, data: {values: [{a: 1}]} }; const result = await embed('#vis', spec); // May throw if compilation fails ``` -------------------------------- ### Check Library Versions Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/vega-and-vegaLite.md Illustrates how to access and log the version strings of both the Vega and Vega-Lite libraries using the exported modules. ```typescript import {vega, vegaLite} from 'vega-embed'; console.log('Vega version:', vega.version); console.log('Vega-Lite version:', vegaLite.version); ``` -------------------------------- ### EmbedOptions Source: https://github.com/vega/vega-embed/blob/main/_autodocs/types.md Comprehensive configuration object for embedding Vega visualizations, covering various aspects like rendering, theming, interaction, and more. ```APIDOC ## EmbedOptions ### Description Comprehensive configuration object for embedding visualizations. ### Type Definition ```typescript interface EmbedOptions { bind?: HTMLElement | string; actions?: boolean | Actions; mode?: Mode; theme?: keyof Omit; defaultStyle?: boolean | string; logLevel?: number; logger?: Logger; loader?: Loader | LoaderOptions; renderer?: R; tooltip?: TooltipHandler | TooltipOptions | boolean; patch?: S | PatchFunc | Operation[]; width?: number; height?: number; padding?: number | {left?: number; right?: number; top?: number; bottom?: number}; scaleFactor?: number | {svg?: number; png?: number}; config?: S | Config; sourceHeader?: string; sourceFooter?: string; editorUrl?: string; hover?: boolean | Hover; i18n?: Partial; downloadFileName?: string; formatLocale?: Record; timeFormatLocale?: Record; expressionFunctions?: ExpressionFunction; ast?: boolean; expr?: typeof expressionInterpreter; viewClass?: typeof View; forceActionsMenu?: boolean; } ``` ### Type Parameters - `S` (default: `string`): Type for string-based properties (config, patch). - `R` (default: `Renderers`): Renderer type. ### Fields - **bind** (`HTMLElement | string`) - Optional - Element to bind the view to. - **actions** (`boolean | Actions`) - Optional - Whether to show actions (download, zoom, etc.). - **mode** (`Mode`) - Optional - Embedding mode. - **theme** (`keyof Omit`) - Optional - The theme to apply. - **defaultStyle** (`boolean | string`) - Optional - Whether to apply default styling. - **logLevel** (`number`) - Optional - Logging level. - **logger** (`Logger`) - Optional - Custom logger instance. - **loader** (`Loader | LoaderOptions`) - Optional - Custom loader configuration. - **renderer** (`R`) - Optional - The renderer to use (e.g., 'svg', 'canvas'). - **tooltip** (`TooltipHandler | TooltipOptions | boolean`) - Optional - Tooltip configuration. - **patch** (`S | PatchFunc | Operation[]`) - Optional - Function or operations to patch the spec. - **width** (`number`) - Optional - Width of the visualization. - **height** (`number`) - Optional - Height of the visualization. - **padding** (`number | {left?: number; right?: number; top?: number; bottom?: number}`) - Optional - Padding around the visualization. - **scaleFactor** (`number | {svg?: number; png?: number}`) - Optional - Scale factor for SVG or PNG rendering. - **config** (`S | Config`) - Optional - Vega configuration object. - **sourceHeader** (`string`) - Optional - Header to prepend to the source code. - **sourceFooter** (`string`) - Optional - Footer to append to the source code. - **editorUrl** (`string`) - Optional - URL for the Vega editor. - **hover** (`boolean | Hover`) - Optional - Configuration for hover events. - **i18n** (`Partial`) - Optional - Internationalization settings. - **downloadFileName** (`string`) - Optional - Default file name for downloads. - **formatLocale** (`Record`) - Optional - Locale settings for number formatting. - **timeFormatLocale** (`Record`) - Optional - Locale settings for time formatting. - **expressionFunctions** (`ExpressionFunction`) - Optional - Custom expression functions. - **ast** (`boolean`) - Optional - Whether to output the AST. - **expr** (`typeof expressionInterpreter`) - Optional - Custom expression interpreter. - **viewClass** (`typeof View`) - Optional - Custom View class. - **forceActionsMenu** (`boolean`) - Optional - Whether to force the display of the actions menu. ``` -------------------------------- ### Access and Control View Signals Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/result-interface.md Get the Vega view object from the embed result to control visualization behavior by setting signal values and read their current values. ```typescript const result = await embed('#vis', spec); const view = result.view; // Change visualization behavior view.signal('color', 'red').runAsync(); view.signal('opacity', 0.7).runAsync(); // Read signal values const currentColor = view.signal('color'); console.log(currentColor); // 'red' ``` -------------------------------- ### Catching Vega Parsing Errors Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md Use a try-catch block to handle errors when parsing an invalid Vega specification. This example specifically checks for errors containing 'Invalid' in their message. ```typescript try { const result = await embed('#vis', spec, {mode: 'vega'}); } catch (error) { if (error instanceof Error && error.message.includes('Invalid')) { console.error('Invalid Vega specification:', error.message); } } ``` -------------------------------- ### container(spec[, opt]) Source: https://github.com/vega/vega-embed/blob/main/README.md Creates a container for a Vega or Vega-Lite visualization, suitable for use in environments like Observable. Returns a Promise that resolves to an HTML element with the Vega View instance attached. ```APIDOC ## container(spec[, opt]) ### Description Creates a container for a Vega or Vega-Lite visualization, designed for use with environments like Observable. Returns a Promise that resolves to an HTML element with the Vega `View` instance as its `value` property. ### Method container ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **spec** (String / Object) - A URL to the Vega specification or the specification object itself. * **opt** (Object) - Optional. A JavaScript object containing options for embedding. ### Returns * **Promise** - Resolves to an HTML element with a `value` property containing the Vega `View` instance. ``` -------------------------------- ### Log Library Version Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/version.md Import and log the current Vega-Embed library version to the console. ```typescript import {version} from 'vega-embed'; console.log(version); // e.g., "7.1.0" ``` -------------------------------- ### Example of Invalid Vega Specification Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md This code snippet demonstrates a syntactically invalid Vega specification due to an unrecognized mark type. Attempting to embed this spec would trigger a parsing error. ```typescript const spec = { $schema: 'https://vega.github.io/schema/vega/v5.json', marks: [{type: 'invalid-type'}] // Invalid mark type }; const result = await embed('#vis', spec); // Error: Invalid mark type 'invalid-type' ``` -------------------------------- ### Accessing Vega libraries and version via wrapper Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/wrapper-function.md Shows how to access Vega and Vega-Lite libraries, as well as the version of vega-embed, through properties of the wrapper function. ```typescript import embed from 'vega-embed'; // Access Vega libraries console.log(embed.vega.version); console.log(embed.vegaLite.version); // Access version console.log(embed.version); // Call functions directly const result1 = await embed.embed('#vis', spec); const result2 = await embed.container(spec); // Observable backwards compatibility const vl = embed.vl; // Same as embed.vegaLite ``` -------------------------------- ### utility-functions Source: https://github.com/vega/vega-embed/blob/main/_autodocs/MANIFEST.txt Reference for various helper functions provided by the vega-embed library. ```APIDOC ## Utility Functions ### Description This document lists and describes the utility functions available in the vega-embed library that can assist with various tasks related to visualization embedding and manipulation. *(Note: Specific utility functions and their signatures would be detailed here if explicitly listed in the source. As the source only mentions 'Helper functions', this is a placeholder.)* ### Example Usage *(Specific examples would depend on the actual utility functions available.)* ```typescript // Example placeholder // import { someUtility } from 'vega-embed'; // const processedData = someUtility(rawData); ``` ``` -------------------------------- ### Editor Action Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md Configure the "Open in Vega Editor" action to allow users to open the current visualization specification in the Vega Editor. ```APIDOC ### editor **Type:** `boolean` **Default:** `true` **Description:** Show "Open in Vega Editor" action link. Opens the Vega Editor in a new window with the visualization specification pre-loaded. For Vega-Lite specs, opens with the compiled Vega if a patch is applied, otherwise with the original spec. **Related Options:** - `editorUrl`: URL of the Vega editor (default: `https://vega.github.io/editor/`) **Usage:** ```typescript // Use default Vega Editor {actions: {editor: true}} // Use custom editor URL {actions: {editor: true}, editorUrl: 'https://my-custom-editor.com/'} // Hide editor action {actions: {editor: false}} ``` ``` -------------------------------- ### Versions & Libraries Source: https://github.com/vega/vega-embed/blob/main/_autodocs/README.md Information on accessing the versions of Vega and Vega-Lite used by vega-embed, along with references to their respective modules. ```APIDOC ## Versions & Libraries ### Description This section provides details on how to access the version information for the `vega` and `vega-lite` libraries bundled with `vega-embed`. It also includes references to the modules themselves, allowing for direct use of their APIs if needed. ### Exports - **version**: A constant string representing the version of the `vega-embed` library. - **vega**: An object representing the Vega library. Includes a `version` property. - **vegaLite**: An object representing the Vega-Lite library. Includes a `version` property. ``` -------------------------------- ### Source Action Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md Configure the "View Source" action to display the input specification as formatted JSON in a new browser window. ```APIDOC ### source **Type:** `boolean` **Default:** `true` (for `embed()`), `false` (for `container()`) **Description:** Show "View Source" action to open the input specification as formatted JSON. When clicked, opens a new browser window with the original specification (before compilation or patching) displayed as pretty-printed JSON. **Related Options:** - `sourceHeader`: HTML to inject into page `` - `sourceFooter`: HTML to inject before `` **Usage:** ```typescript // Show source link {actions: {source: true}} // Hide source link {actions: {source: false}} // Add syntax highlighting to source view { actions: {source: true}, sourceHeader: ``, sourceFooter: ` ` } ``` ``` -------------------------------- ### Static Display UI Configuration (Export Only) Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md Configure the player for static display, enabling only the export action and disabling source, compiled, and editor views. ```typescript { actions: { export: true, source: false, compiled: false, editor: false } } ``` -------------------------------- ### Vega-Lite with Compilation View Configuration Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md Enable all actions including export, source, compiled, and editor views, suitable for Vega-Lite development with compilation. ```typescript { actions: { export: true, source: true, compiled: true, editor: true } } ``` -------------------------------- ### container(spec, opts?) Source: https://github.com/vega/vega-embed/blob/main/_autodocs/00-START-HERE.md Observable-compatible wrapper that creates an HTML element containing the Vega View. Useful for integrating with reactive programming patterns. ```APIDOC ## container(spec, opts?) ### Description Observable-compatible wrapper that creates an element with the View. ### Parameters - **spec** (VisualizationSpec) - The Vega or Vega-Lite visualization specification. - **opts?** (EmbedOptions) - Optional configuration options for embedding. ### Request Example ```typescript const wrapper = await container(spec, {actions: false}); const view = wrapper.value; ``` ### Return Value - **object** - An object with a `value` property containing the Vega View. ``` -------------------------------- ### Dashboard UI Configuration (Minimal Actions) Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md Configure the player to show minimal UI elements, disabling export, source, compiled, and editor actions. ```typescript { actions: { export: false, source: false, compiled: false, editor: false } } // or simply: {actions: false} ``` -------------------------------- ### Pre-compiling Vega-Lite Specifications Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md Pre-compile Vega-Lite specifications using `vega-lite.compile()` within a try-catch block to catch compilation errors early. This allows for validation before attempting to embed the visualization. ```typescript import {compile} from 'vega-lite'; // Pre-compile to catch errors early try { const compiled = compile(vlSpec); const result = await embed('#vis', vlSpec); } catch (error) { console.error('Spec validation failed'); } ``` -------------------------------- ### View Instance Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/result-interface.md The Vega View instance is the primary interface for programmatically controlling the visualization. It allows interaction with signals, data, marks, and exporting the visualization. ```APIDOC ## view ### Description The Vega View instance that has been initialized and rendered in the DOM. This is the primary interface for programmatically controlling the visualization. ### Type Vega's `View` class instance ### Key Methods | Method | Signature | Purpose | |---|---|---| | `signal(name, value)` | `(name: string, value?: any) => View | any` | Get or set a signal value | | `data(name)` | `(name: string) => VisualizationData` | Access a data table | | `addSignalListener(name, handler)` | `(name: string, handler: (name, value) => void)` | Listen to signal changes | | `addDataListener(name, handler)` | `(name: string, handler: (name, changes) => void)` | Listen to data updates | | `addMarkListener(markName, handler)` | `(markName: string, handler: (item, event) => void)` | Listen to mark interactions | | `toImageURL(type, scaleFactor)` | `(type: 'svg' | 'png', scaleFactor?: number) => Promise` | Export visualization as data URL | | `finalize()` | `() => void` | Clean up resources and unregister listeners | ### Example ```typescript const result = await embed('#vis', spec); const view = result.view; // Set a signal value view.signal('opacity', 0.5).runAsync(); // Get a signal value console.log(view.signal('opacity')); // 0.5 // Listen to signal changes view.addSignalListener('selected', (name, value) => { console.log('Selection changed:', value); }); // Access data table const data = view.data('table'); console.log(data.values()); // Array of data values ``` ``` -------------------------------- ### Configuring Loader Credentials Source: https://github.com/vega/vega-embed/blob/main/_autodocs/errors.md Fix network loading issues by configuring loader options, such as setting credentials to 'same-origin' for requests. ```typescript const result = await embed('#vis', specUrl, { loader: { http: { credentials: 'same-origin' } } }); ``` -------------------------------- ### Options Object Source: https://github.com/vega/vega-embed/blob/main/README.md Configuration options that can be passed to the embed function or specified within the Vega/Vega-Lite spec. ```APIDOC ## Options ### Description Options can be passed to the `embed` function or set via `usermeta.embedOptions` within the Vega/Vega-Lite specification to configure embedding behavior. ### Parameters * **mode** (String) - Specifies whether to parse the spec as 'vega' or 'vega-lite'. Defaults to parsing the `$schema` URL, or 'vega' if neither is specified. * **config** (Object) - Vega configuration object. * **theme** (String) - The theme to apply. * **defaultStyle** (Boolean) - Whether to apply default styles. * **bind** (Object) - An object for binding interactions. * **renderer** (String) - The rendering mode (e.g., 'svg', 'canvas'). * **loader** (Object) - A custom loader object. * **logger** (Object) - A custom logger object. * **logLevel** (Number) - The logging level. * **tooltip** (Object) - Tooltip configuration. * **patch** (Function) - A function to patch the spec. * **width** (Number) - The desired width of the visualization. * **height** (Number) - The desired height of the visualization. * **padding** (Number) - The padding around the visualization. * **actions** (Object) - Configuration for action buttons (export, source, compiled, editor). * **export** (Boolean) - Enable/disable export action. * **source** (Boolean) - Enable/disable source action. * **compiled** (Boolean) - Enable/disable compiled spec action. * **editor** (Boolean) - Enable/disable editor action. * **scaleFactor** (Number) - Scaling factor for the view. * **editorUrl** (String) - URL for the Vega editor. * **sourceHeader** (String) - Header text for the source view. * **sourceFooter** (String) - Footer text for the source view. * **hover** (Object) - Hover interaction configuration. * **hoverSet** (Object) - Configuration for hover set. * **updateSet** (Object) - Configuration for hover update. * **downloadFileName** (String) - Default file name for downloads. * **formatLocale** (Object) - Locale settings for number formatting. * **timeFormatLocale** (Object) - Locale settings for time formatting. * **expressionFunctions** (Object) - Custom expression functions. * **ast** (Boolean) - Whether to output the AST. * **expr** (Boolean) - Whether to output expressions. * **i18n** (Object) - Internationalization strings for action buttons. ``` -------------------------------- ### container() Source: https://github.com/vega/vega-embed/blob/main/_autodocs/README.md An Observable-compatible wrapper that creates a DOM element with the Vega View attached as a `.value` property. ```APIDOC ## container() ### Description Creates a DOM element that acts as a container for a Vega visualization. The Vega View is attached to the `.value` property of this element, making it compatible with Observable's reactive programming model. ### Parameters - **spec** (VisualizationSpec | string) - The Vega or Vega-Lite specification object or a URL to the specification. - **opts** (EmbedOptions) - Optional configuration options for embedding. ### Returns Promise - A promise that resolves with a DOM element that has a `value` property containing the Vega View. ``` -------------------------------- ### Basic Container Usage Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/container.md Use this snippet for basic embedding of a Vega visualization specification in an Observable notebook. Assign the result to a `viewof` variable to make it reactive. ```typescript viewof chart = container(spec) ``` -------------------------------- ### Script Tag Usage with Global vegaEmbed Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/wrapper-function.md Illustrates how to use the wrapper function when included via a script tag, where it becomes the global `vegaEmbed` object. ```html ``` -------------------------------- ### Configure Loader Options for Embed Source: https://github.com/vega/vega-embed/blob/main/_autodocs/configuration.md Shows how to pass a LoaderOptions object to configure link target and HTTP request credentials for embedded visualizations. ```typescript const result = await embed('#vis', spec, { loader: { target: '_blank', // How to open links http: { credentials: 'same-origin' // Send cookies with requests } } }); ``` -------------------------------- ### Compile Vega-Lite Manually Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/vega-and-vegaLite.md Shows how to use the exported Vega-Lite module to compile a Vega-Lite specification into a Vega specification. ```typescript import {vegaLite} from 'vega-embed'; const vlSpec = { mark: 'bar', encoding: {x: {field: 'a', type: 'nominal'}} }; const vgSpec = vegaLite.compile(vlSpec).spec; ``` -------------------------------- ### TooltipOptions Type Source: https://github.com/vega/vega-embed/blob/main/_autodocs/types.md Configuration object for customizing the behavior and appearance of Vega Tooltip. ```APIDOC ## TooltipOptions Type ### Description Configuration object for Vega Tooltip. ### Options Includes options for positioning, styling, and delay. Most properties have sensible defaults. ``` -------------------------------- ### Send a message to the Vega Editor window Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/utility-functions.md Opens the editor URL in a new window and repeatedly sends visualization data using the postMessage API until acknowledged or a timeout occurs. ```typescript export default function post(window: Window, url: string, data: MessageData): void ``` -------------------------------- ### Create Container for Vega Visualization Source: https://github.com/vega/vega-embed/blob/main/README.md The `container` function is designed for environments like Observable. It returns a Promise that resolves to an HTML element containing the Vega view. This is useful when you need to create and manage the container element dynamically. ```javascript container(spec[, opt]) ``` -------------------------------- ### NPM Package Exports Configuration Source: https://github.com/vega/vega-embed/blob/main/_autodocs/module-exports.md Defines the main entry point and type definitions for the NPM package using the 'exports' field in package.json. ```json { "exports": { "types": "./build/embed.d.ts", "default": "./build/embed.js" } } ``` -------------------------------- ### container() function Source: https://github.com/vega/vega-embed/blob/main/_autodocs/00-START-HERE.md This function is designed for use within Observable notebooks, providing a way to create reactive HTML elements for Vega visualizations. ```APIDOC ## container() ### Description Creates a reactive HTML element for embedding Vega visualizations, suitable for use in Observable notebooks. ### Method Function call ### Parameters - **el** (string | HTMLElement | null) - The HTML element or selector to embed the visualization into. - **spec** (VisualizationSpec | string | null) - The visualization specification or a URL to a JSON file containing the specification. - **options** (EmbedOptions | null) - Optional configuration options for embedding. ### Request Example ```javascript vegaEmbed.container(element, spec, options); ``` ### Response #### Success Response - **HTMLElement** - The container element with the embedded visualization. ``` -------------------------------- ### Actions Interface Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-reference/actions-configuration.md The `Actions` interface defines the available configuration options for controlling the action menu and toolbar. ```APIDOC ## Actions Interface ```typescript interface Actions { export?: boolean | {svg?: boolean; png?: boolean}; source?: boolean; compiled?: boolean; editor?: boolean; } ``` ``` -------------------------------- ### Enable All Actions in Embed Source: https://github.com/vega/vega-embed/blob/main/_autodocs/configuration.md Configures the embed options to enable all available actions, which is the default behavior. ```json { actions: true // Equivalent to: // { // export: {svg: true, png: true}, // source: true, // compiled: false, // Only for Vega-Lite // editor: true // } } ``` -------------------------------- ### Importing Vega-Embed and Vega-Lite Types Source: https://github.com/vega/vega-embed/blob/main/_autodocs/quick-reference.md Import necessary types from 'vega-embed' for results, options, and configurations. Use 'vega-lite' types for defining specifications. ```typescript // Import types import type { Result, EmbedOptions, VisualizationSpec, Mode, Actions, Config } from 'vega-embed'; // Type your specs import type {TopLevelSpec} from 'vega-lite'; const vlSpec: TopLevelSpec = { mark: 'bar', encoding: {...} }; ``` -------------------------------- ### Embed Options Configuration Source: https://github.com/vega/vega-embed/blob/main/_autodocs/00-START-HERE.md Illustrates the various options available for configuring how a visualization is embedded, including rendering, styling, interactivity, and data loading. ```typescript { // Rendering renderer: 'svg', // or 'canvas' width: 800, height: 600, // Styling theme: 'dark', // vega-themes defaultStyle: true, // Interactivity tooltip: true, hover: true, actions: { // which buttons to show export: true, source: false, compiled: false, editor: true }, // Data & Config loader: {...}, config: {...}, patch: function(spec) {...}, // Advanced ast: false, // for CSP compliance expressionFunctions: {} } ``` -------------------------------- ### guessMode(spec, logger, providedMode?) Source: https://github.com/vega/vega-embed/blob/main/_autodocs/api-overview.md Automatically detects whether a given visualization specification is for Vega or Vega-Lite. It can optionally accept a logger instance and an explicitly provided mode. ```APIDOC ## guessMode(spec, logger, providedMode?) ### Description Automatically detects whether a specification is Vega or Vega-Lite. ### Method Not applicable (JavaScript function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **spec** (object) - Required - The Vega or Vega-Lite visualization specification. - **logger** (Vega logger instance) - Required - An instance of a Vega logger. - **providedMode?** (string) - Optional - An explicit mode ('vega' or 'vega-lite') to use if provided. ### Returns 'vega' or 'vega-lite' ### Use case Determining spec type when not explicitly provided ```