@perspective-dev/viewer
    Preparing search index...

    The <perspective-viewer> custom element.

    JavaScript Examples

    Create a new <perspective-viewer>:

    const viewer = document.createElement("perspective-viewer");
    window.body.appendChild(viewer);

    Complete example including loading and restoring the [Table]:

    import perspective from "@perspective-dev/viewer";
    import perspective from "@perspective-dev/client";

    const viewer = document.createElement("perspective-viewer");
    const worker = await perspective.worker();

    await worker.table("x\n1", {name: "table_one"});
    await viewer.load(worker);
    await viewer.restore({table: "table_one"});
    Index

    Constructors

    Methods

    • Returns void

    • Add a new, independent panel to this viewer's layout, rendering the supplied [ViewerConfigInitial] into it. Unlike [Self::restore]'s update-shaped argument, a new panel has no prior state, so table is REQUIRED — a table-less call rejects before the layout is touched. The panel uses the default [perspective_client::Client] (the first passed to [Self::load]) to resolve its table. Returns the generated panel id.

      The element-level settings field does not exist on the argument type (it is shared across the element, not per-panel).

      Parameters

      Returns Promise<any>

    • Configure the embedded LLM agent (see prompt()), replacing any prior configuration and conversation.

      The agent core is provider-agnostic: one OpenAI-chat-completions protocol over primitive connection fields. Exactly one of config.url or config.engine is required; the providers presets exported by this package are plain spreadable collections of these fields ({...providers.anthropic, apiKey}).

      • config.url - a full chat-completions endpoint URL (any OpenAI-compatible service: Anthropic/Gemini compatibility endpoints, LM Studio, Ollama, OpenRouter, a proxy...).
      • config.engine - an in-page engine object with an OpenAI-compatible chat.completions.create(request) method (e.g. WebLLM's MLCEngine); mutually exclusive with url.
      • config.headers - extra request headers, sent verbatim.
      • config.apiKey - sugar for the Authorization: Bearer header.
      • config.model - model id sent with each request; local servers and engines generally answer with whatever model is loaded.
      • config.name - cosmetic label for the chat badge (presets set this).
      • config.systemPrompt - extra system-prompt context appended to the agent's built-in instructions.
      • config.maxTurns - max model turns (tool-call rounds + the final answer) per prompt() call. Defaults to 16.
      • config.docs - the agent metadata bundle, which supplies the search_docs corpus and the rich tool parameter schemas: the packaged dist/docs/perspective-docs.json asset as a parsed object (import docs from "…json" with { type: "json" }), a fetch() Response, an ArrayBuffer, a JSON string, or a Promise of any of those — and/or an inline array of {title?, text} entries for host data definitions. Omitted, search_docs searches an empty corpus and the parameter schemas degrade to permissive objects.
      • config.systemRole - where the preamble (plus systemPrompt) is placed: "system" (default) or "user". Some engines refuse a system message alongside tools because they substitute their own — WebLLM's Hermes function calling throws CustomSystemPromptError on ANY system message — and those need "user", which folds the same text into the opening user turn.
      • config.entitlements - access grants limiting which tools the agent is offered (and may call): any of "read_view", "configure_view", "manage_layout", "read_docs", "read_data". Omitted, all but "read_data" are granted; ["read_view", "read_docs"] yields a read-only agent.

      JavaScript Examples

      import { providers } from "@perspective-dev/viewer";

      viewer.agentConfig({
      ...providers.anthropic,
      apiKey: "sk-ant-...",
      docs: fetch(
      "node_modules/@perspective-dev/viewer/dist/docs/perspective-docs.json",
      ),
      });

      Parameters

      • config: any

      Returns void

    • Run one conversational turn of the embedded LLM agent (configured via agentConfig()), resolving with the agent's final text response after any tool calls have been applied to this element. Turns share a conversation history (and the chat sidebar's transcript) until agentReset(); a call made while a turn is already running rejects. Tool activity is emitted as perspective-agent-tool CustomEvents on this element.

      JavaScript Examples

      await viewer.agentPrompt("Show me sales by region as a bar chart");
      

      Parameters

      • prompt: string

      Returns Promise<any>

    • Clear the agent's conversation (history and chat transcript), keeping its configuration. Cancels any in-flight turn.

      Returns Promise<any>

    • Returns void

    • Copy this viewer's View or Table data as CSV to the system clipboard.

      Arguments

      • method - The ExportMethod (serialized as a String) to use to render the data to the Clipboard.

      JavaScript Examples

      myDownloadButton.addEventListener("click", async () => {
      await viewer.copy();
      })

      Parameters

      Returns Promise<any>

    • Delete all internal [View]s and all associated state, rendering this <perspective-viewer> unusable and freeing all associated resources. Does not delete any supplied [Table] (as this is constructed by the callee).

      Calling any method on a <perspective-viewer> after [Self::delete] will throw.

      Allowing a <perspective-viewer> to be garbage-collected without calling [PerspectiveViewerElement::delete] will leak WASM memory!

      JavaScript Examples

      await viewer.delete();
      

      Returns Promise<any>

    • Download this viewer's internal [View] data via a browser download event.

      Arguments

      • method - The ExportMethod to use to render the data to download.

      JavaScript Examples

      myDownloadButton.addEventListener("click", async () => {
      await viewer.download();
      })

      Parameters

      Returns Promise<any>

    • Remove a [Client] from this <perspective-viewer> and dispose every panel bound to it (each panel's View is deleted and its Table reference released).

      Arguments

      • options - An optional {client?: string} dict naming the client to eject; the active panel's client when omitted.

      JavaScript Examples

      await viewer.eject();
      await viewer.eject({client: "remote"});

      Parameters

      Returns Promise<any>

    • Exports this viewer's internal [View] as a JavaSript data, the exact type of which depends on the method but defaults to String in CSV format.

      This method is only really useful for the "plugin" method, which will use the configured plugin's export (e.g. PNG for @perspective-dev/viewer-charts). Otherwise, prefer to call the equivalent method on the underlying [View] directly.

      Arguments

      • method - The ExportMethod to use to render the data to download.

      JavaScript Examples

      const data = await viewer.export("plugin");
      

      Parameters

      Returns Promise<any>

    • Flush any pending modifications to this <perspective-viewer>. Since <perspective-viewer>'s API is almost entirely async, it may take some milliseconds before any user-initiated changes to the [View] affects the rendered element. If you want to make sure all pending actions have been rendered, call and await [Self::flush].

      [Self::flush] will resolve immediately if there is no [Table] set.

      JavaScript Examples

      In this example, [Self::restore] is called without await, but the eventual render which results from this call can still be awaited by immediately awaiting [Self::flush] instead.

      viewer.restore(config);
      await viewer.flush();

      Returns Promise<any>

    • Returns void

    • The id of the active panel — the one the settings panel and status-bar toolbar target — or null when the element has zero panels.

      Returns any

    • Get an Array of all of the plugin custom elements registered for this element. This may not include plugins which called [registerPlugin] after the host has rendered for the first time.

      Returns any[]

    • Get the underlying [Client] for this viewer (as passed to, or associated with the [Table] passed to, [PerspectiveViewerElement::load]).

      Arguments

      • wait_for_client - whether to wait for [PerspectiveViewerElement::load] to be called, or fail immediately if [PerspectiveViewerElement::load] has not yet been called.

      JavaScript Examples

      const client = await viewer.getClient();
      

      Parameters

      Returns Promise<any>

    • Get this viewer's edit port for the named panel's [Table] (see [Table::update] for details on ports), or the active panel when panel is omitted.

      Parameters

      Returns number

    • Get the ids of all panels in this viewer's layout, in insertion order.

      Returns any[]

    • Gets a plugin Custom Element with the name field, or get the active plugin if no name is provided.

      Arguments

      • name - The name property of a perspective plugin Custom Element, or None for the active plugin's Custom Element.

      Parameters

      • Optionalname: string | null

      Returns any

    • Get render statistics. Some fields of the returned stats object are relative to the last time [PerspectiveViewerElement::getRenderStats] was called, ergo calling this method resets these fields.

      JavaScript Examples

      const {virtual_fps, actual_fps} = await viewer.getRenderStats();
      

      Parameters

      Returns any

    • Return a [perspective_js::JsViewWindow] for the currently selected region of the named panel, or the active panel when panel is omitted.

      Parameters

      Returns ViewWindow | undefined

    • Get the underlying [Table] for this viewer (as passed to [PerspectiveViewerElement::load] or as the table field to [PerspectiveViewerElement::restore]).

      Arguments

      • wait_for_table - whether to wait for [PerspectiveViewerElement::load] to be called, or fail immediately if [PerspectiveViewerElement::load] has not yet been called.

      JavaScript Examples

      const table = await viewer.getTable();
      

      Parameters

      Returns Promise<any>

    • Get the underlying [View] for this viewer.

      Use this method to get promgrammatic access to the [View] as currently configured by the user, for e.g. serializing as an Apache Arrow before passing to another library.

      The [View] returned by this method is owned by the [PerspectiveViewerElement] and may be invalidated by [View::delete] at any time. Plugins which rely on this [View] for their [HTMLPerspectiveViewerPluginElement::draw] implementations should treat this condition as a cancellation by silently aborting on "View already deleted" errors from method calls.

      JavaScript Examples

      const view = await viewer.getView();
      

      Parameters

      Returns Promise<any>

    • Get a copy of the [ViewConfig] for the current [View]. This is non-blocking as it does not need to access the plugin (unlike [PerspectiveViewerElement::save]), and also makes no API calls to the server (unlike [PerspectiveViewerElement::getView] followed by [View::get_config])

      Parameters

      Returns Promise<any>

    • Loads a [Client], or optionally [Table], or optionally a Javascript Promise which returns a [Client] or [Table], in this viewer.

      Loading a [Client] does not render, but subsequent calls to [PerspectiveViewerElement::restore] will use this [Client] to look up the proviced table name field for the provided [ViewerConfigUpdate].

      Loading a [Table] is equivalent to subsequently calling [Self::restore] with the table field set to [Table::get_name], and will render the UI in its default state when [Self::load] resolves. If you plan to call [Self::restore] anyway, prefer passing a [Client] argument to [Self::load] as it will conserve one render.

      When [PerspectiveViewerElement::load] resolves, the first frame of the UI + visualization is guaranteed to have been drawn. Awaiting the result of this method in a try/catch block will capture any errors thrown during the loading process, or from the [Client] Promise itself.

      [PerspectiveViewerElement::load] may also be called with a [Table], which is equivalent to:

      await viewer.load(await table.get_client());
      await viewer.restore({name: await table.get_name()})

      If you plan to call [PerspectiveViewerElement::restore] immediately after [PerspectiveViewerElement::load] yourself, as is commonly done when loading and configuring a new <perspective-viewer>, you should use a [Client] as an argument and set the table field in the restore call as

      A [Table] can be created using the @perspective-dev/client library from NPM (see [perspective_js] documentation for details).

      JavaScript Examples

      import perspective from "@perspective-dev/client";

      const worker = await perspective.worker();
      viewer.load(worker);

      ... or

      const table = await worker.table(data, {name: "superstore"});
      viewer.load(table);

      Complete example:

      const viewer = document.createElement("perspective-viewer");
      const worker = await perspective.worker();

      await worker.table("x\n1", {name: "table_one"});
      await viewer.load(worker);
      await viewer.restore({table: "table_one", columns: ["x"]});

      ... or, if you don't want to pass your own arguments to restore:

      const viewer = document.createElement("perspective-viewer");
      const worker = await perspective.worker();

      const table = await worker.table("x\n1", {name: "table_one"});
      await viewer.load(table);

      Parameters

      Returns Promise<any>

    • Remove the panel with id name from the layout, disposing its engines (its View is deleted and its Table reference released). The last remaining panel cannot be removed (resolves as a no-op). Resolves after the panel's teardown run completes, carrying any teardown error — previously fire-and-forget and silently dropped (invariant I6). See also [Self::addPanel].

      Parameters

      • name: string

      Returns Promise<any>

    • Reset a panel's ViewerConfig to its data-relative default.

      Without a panel, this is ELEMENT-LEVEL: EVERY panel is reset and the cross-filter overlay cleared (symmetric with whole-element [Self::save] / [Self::restore]). With {panel}, only that panel is reset — the other panels and the overlay are left untouched.

      Arguments

      • reset_all - If set, will clear expressions and column settings as well.
      • options - An optional {panel?: string}; the panel to reset, or every panel when omitted.

      JavaScript Examples

      await viewer.reset();                     // every panel
      await viewer.reset(true, {panel: "p1"}); // just "p1", + expressions

      Parameters

      • Optionalreset_all: boolean | null
      • Optionaloptions: PanelOptions | null

      Returns Promise<any>

    • If this element is in an errored state, this method will clear it and re-render. Calling this method is equivalent to clicking the error reset button in the UI.

      Returns Promise<any>

    • Set the available theme names available in the status bar UI.

      Calling [Self::resetThemes] may cause the current theme to switch, if e.g. the new theme set does not contain the current theme.

      JavaScript Examples

      Restrict <perspective-viewer> theme options to only default light and dark themes, regardless of what is auto-detected from the page's CSS:

      viewer.resetThemes(["Pro Light", "Pro Dark"])
      

      Parameters

      • Optionalthemes: any[] | null

      Returns Promise<any>

    • Recalculate the viewer's dimensions and redraw.

      Use this method to tell <perspective-viewer> its dimensions have changed when auto-size mode has been disabled via [Self::setAutoSize]. [Self::resize] resolves when the resize-initiated redraw of this element has completed.

      Arguments

      • options - An optional object with the following fields:
        • dimensions - An optional object {width, height} providing explicit size hints (in pixels) for the plugin container. When provided, the plugin element will be temporarily sized to these dimensions during resize, then reset.

      JavaScript Examples

      await viewer.resize()
      await viewer.resize({dimensions: {width: 800, height: 600}})

      Parameters

      • Optionaloptions: any

      Returns Promise<any>

    • Restore a single panel from a full/partial [perspective_js::JsViewConfig] (its user-configurable state, including the Table name) — the active panel, or a specific panel via the optional {panel} selector.

      If panel names no existing panel, a NEW panel is created with that id and the config restored into it (an upsert). As with a created panel, the element-level settings/theme fields are ignored in that case. Unlike [Self::addPanel], the argument is a PATCH, so a table is optional: creating without one yields a DEFERRED panel that the next [Self::load] binds. Such a panel renders but cannot be serialized — [Self::save] rejects with "Panel has no table" until it is bound.

      On an empty element with a pending [Self::load] whose payload is not yet classified, the active-target form (no panel) instead claims and restores into that load's reserved first panel — see [Self::load].

      This restores a SINGLE panel; a whole-element config (with a panels map) must be applied via [Self::restoreWorkspace] — its panels / layout keys are ignored here.

      One of the best ways to use [Self::restore] is by first configuring a <perspective-viewer> as you wish, then using either the Debug panel or "Copy" -> "config.json" from the toolbar menu to snapshot the [Self::restore] argument as JSON.

      Arguments

      • update - The config to restore to, as returned by [Self::save] in either "json", "string" or "arraybuffer" format.
      • options.panel - The panel to target, or the active panel when omitted.
      • options.suppress_errors - when true, a failed restore only rejects the returned Promise; the error is NOT committed to the viewer's visible error state and the session remains usable. The view config is rolled back to its pre-call value, so a rejected patch cannot re-merge into a later restore. Element-level state the call already applied (theme, title, a plugin swap) is NOT undone — restore a known-good config to recover those exactly.

      JavaScript Examples

      Loads a default plugin for the table named "superstore":

      await viewer.restore({table: "superstore"});
      

      Apply a group_by to the same viewer element, without modifying/resetting other fields - you can omit the table field, this has already been set once and is not modified:

      await viewer.restore({group_by: ["State"]});
      

      Parameters

      Returns Promise<void>

    • Restore the ENTIRE element from a whole-element [WorkspaceConfigUpdate] ({version, active?, layout, panels, ...}) — the multi-panel counterpart of [Self::restore]. Every existing panel is replaced by the panels entries, and the layout tree + master/detail cross-filter state re-applied. Unlike [Self::restore], this never falls back to the single-panel path.

      JavaScript Examples

      await viewer.restoreWorkspace(await otherViewer.saveWorkspace());
      

      Parameters

      Returns Promise<void>

    • Restyle all plugins from current document.

      [Self::restyleElement] must be called for many runtime changes to CSS properties to be reflected in an already-rendered <perspective-viewer>.

      JavaScript Examples

      viewer.style = "--psp--color: red";
      await viewer.restyleElement();

      Returns Promise<any>

    • Save a single panel's user-configurable state as a [ViewerConfig], one which can be restored via [Self::restore] — the active panel, or a specific panel via the optional {panel} selector.

      This saves a SINGLE panel; to snapshot the ENTIRE element (every panel + layout + cross-filters) use [Self::saveWorkspace].

      Arguments

      • options - An optional {panel?: string}; the panel to save, or the active panel when omitted.

      JavaScript Examples

      Get the current group_by setting:

      const {group_by} = await viewer.save();
      

      Reset workflow attached to an external button myResetButton:

      const token = await viewer.save();
      myResetButton.addEventListener("click", async () => {
      await viewer.restore(token);
      });

      Parameters

      Returns Promise<ViewerConfig>

    • Save the ENTIRE element to a whole-element [WorkspaceConfig] ({version, active?, layout, panels, ...}) — the multi-panel counterpart of [Self::save]. Unlike [Self::save] (which emits a single ViewerConfig for one panel), this ALWAYS emits the whole-element format, restorable via [Self::restoreWorkspace].

      JavaScript Examples

      const token = await viewer.saveWorkspace();
      await viewer.restoreWorkspace(token);

      Returns Promise<WorkspaceConfig>

    • Make the panel with id name the active panel, re-targeting the settings panel and status-bar toolbar (and the root's session/renderer subscriptions) to its engines. Resolves after the activation-chrome redraws on both sides of the switch have completed (invariant I6).

      Parameters

      • name: string

      Returns Promise<any>

    • Sets the auto-pause behavior of this component.

      When true, this <perspective-viewer> will skip rendering whenever it cannot be seen — tracked via an IntersectionObserver on itself (scrolled out of the viewport, display: none) combined with the document's page visibility (backgrounded browser tab, minimized window). Auto-pause is enabled by default.

      Arguments

      • autopause Whether to enable auto-pause behavior or not.

      JavaScript Examples

      Disable auto-size behavior:

      viewer.setAutoPause(false);
      

      Parameters

      • autopause: boolean

      Returns Promise<any>

    • Sets the auto-size behavior of this component.

      When true, this <perspective-viewer> will register a ResizeObserver on itself and call [Self::resize] whenever its own dimensions change. However, when embedded in a larger application context, you may want to call [Self::resize] manually to avoid over-rendering; in this case auto-sizing can be disabled via this method. Auto-size behavior is enabled by default.

      Arguments

      • autosize - Whether to enable auto-size behavior or not.

      JavaScript Examples

      Disable auto-size behavior:

      viewer.setAutoSize(false);
      

      Parameters

      • autosize: boolean

      Returns void

    • Set the selection [perspective_js::JsViewWindow] for the named panel, or the active panel when panel is omitted.

      Parameters

      • Optionalwindow: ViewWindow | null
      • Optionaloptions: PanelOptions | null

      Returns void

    • Determines the render throttling behavior. Can be an integer, for millisecond window to throttle render event; or, if None, adaptive throttling will be calculated from the measured render time of the last 5 frames.

      Arguments

      • throttle - The throttle rate in milliseconds (f64), or None for adaptive throttling.

      JavaScript Examples

      Only draws at most 1 frame/sec:

      viewer.setThrottle(1000);
      

      Parameters

      • Optionalval: number | null

      Returns void

    • Asynchronously opens the column settings for a specific column. When finished, the <perspective-viewer> element will emit a "perspective-toggle-column-settings" CustomEvent. The event's details property has two fields: {open: bool, column_name?: string}. The CustomEvent is also fired whenever the user toggles the sidebar manually.

      Parameters

      Returns Promise<any>

    • Toggle (or force) the config panel open/closed.

      Arguments

      • force - Force the state of the panel open or closed, or None to toggle.

      JavaScript Examples

      await viewer.toggleConfig();
      

      Parameters

      • Optionalforce: boolean | null

      Returns Promise<any>