Events and app interactions

Events and app interactions

ThoughtSpot supports a range of events that your app can listen to and respond to with appropriate actions. The embedded ThoughtSpot components emit events when they initialize and load, and when a user executes an action inside these components. The host application can also trigger events within the embedded ThoughtSpot objects, causing an alert or other action.

The SDK library includes the following event objects:

Embed eventsπŸ”—

Developers can register event listeners to listen to application actions such as component loading or user interactions with the embedded component and fire events. Embed events are emitted by the embedded ThoughtSpot components and are part of the EmbedEvent object.

Register event listenersπŸ”—

To register event listeners, import the EmbedEvent library into your application setup.

import {
  //...
  EmbedEvent
} from "@thoughtspot/visual-embed-sdk";

When you register an event listener, you can choose to log it in the console output or add a callback function to handle the event response in the .on(embedEvent, eventHandlerCallbackFunction) format.

In the following example, the EmbedEvent.Edit is emitted and logged in the console output when a user clicks the Edit button on the embedded Liveboard.

liveboardEmbed.on(EmbedEvent.Edit, payload => {
   console.log(`Liveboard edit', payload);
})

Start and end specificationπŸ”—

For some actions and events, you can register listeners to emit events when an action starts and ends. In this example, the EmbedEvent.DownloadAsPdf is emitted when the DownloadAsPdf starts and after the download is completed:

 //emit when the download workflow starts
 liveboardEmbed.on(EmbedEvent.DownloadAsPdf, payload => {
     console.log('download PDF', payload)
 }, {
     start: true
 })
 //emit when the download workflow ends
 liveboardEmbed.on(EmbedEvent.DownloadAsPdf, payload => {
     console.log('download PDF', payload)
 })

Common Use casesπŸ”—

Embed events can be used to trigger a specific response when the event is emitted, handle load and errors for embedded components, or modify a behavior in the embedded view.

Handle event response for embedded componentsπŸ”—

To handle event response when the event emits, you can add a callback function.

In this example, a callback function is added to show the loader when the embedded Liveboard initializes:

liveboardEmbed.on(EmbedEvent.Init, showLoader)
//show a loader
function showLoader() {
    document.getElementById("loader");
}

You can also trigger a host event when an embed event is fired. In this example, the HostEvent.SetVisibleVizs is triggered to set the visualizations on a Liveboard when EmbedEvent.LiveboardRendered fires.

 // Emit when the Liveboard is rendered
 liveboardEmbed.on(EmbedEvent.LiveboardRendered, () => {
     // Trigger the SetVisibleVizs host event
     liveboardEmbed.trigger(HostEvent.SetVisibleVizs, ['viz1', 'viz2']);
 });

Handle load and errors for embedded componentsπŸ”—

A common workflow is to use an overlay div element to hide the embed content until you know that SSO is completed, and the content is fully loaded. If an error occurs in the process, you may prefer to display your own custom message to the end user rather than showing embedded ThoughtSpot content in an error state.

Embed events fire at different points within the loading process. The following events are related to the load process:

  1. Init
    Fires at the beginning of the loading process.

  2. NoCookieAccess
    Some browsers (Safari in particular) default to strict settings on cookie origins that prohibit the standard SSO process. This event fires if cookies are restricted by a user’s browser.

  3. AuthExpire
    Fires if SSO does not complete and if the ThoughtSpot session times out at some point. Listen to the AuthExpire event in the load process to determine when it is safe to show the ThoughtSpot content and listen to it after loading to hide the ThoughtSpot login screen if the session expires for some reason.

  4. AuthInit
    Fires when the SSO process is completed correctly. The event does not fire when an SSO process fails. The logged-in user GUID is available in the AuthInit event response.

  5. Error
    Fires when an error occurs in the embedded app. For information about error types, see Error types.

  6. Load
    Fires as soon as the area for embedding is created, not when the content has begun or finished loading.

  7. LiveboardRendered
    Fires only on LiveboardEmbed components when the Liveboard or visualization container loads.

You can use both EmbedEvent.AuthExpire and EmbedEvent.AuthInit together to determine if the SSO process is completed correctly.
To determine if AuthExpire is firing because SSO did not complete or if the ThoughtSpot session has timed out, you can set a variable to act as a flag to determine if SSO is completed.
When AuthInit fires, set the flag to true. You can also associate a callback function to AuthExpire to look up the flag to determine which state change has caused the AuthExpire event to fire.

In the following example, the tsLoggedIn flag is set to indicate the SSO login state.

// Instantiate class for embedding a Liveboard
const embed = new LiveboardEmbed("#thoughtspot-embed", {
    liveboardId: '<Liveboard-guid>',
});
let tsLoggedIn = false;
embed
    .on(EmbedEvent.Init, showLoader)
    .on(EmbedEvent.NoCookieAccess, showCookieSettingsMsg)
    .on(EmbedEvent.AuthInit, (response) => {
        // Set that AuthInit has fired
        tsLoggedIn = true;
        // authInit returns object -> {type: 'authInit', data: {userGuid: <guid>} } }
        let userGUID = response.data.userGuid;
    })
    .on(EmbedEvent.AuthExpire, (response) => {
        // Handle if session dies while content shows
        if (tsLoggedIn == true) {
            tsSessionTimeoutCleanup();
        } else {
            // Display custom message if SSO issues
            showSSOFailedMsg();
        }
    })
    .on(EmbedEvent.Error, showGenericErrorMsg)
    .on(EmbedEvent.LiveboardRendered, hideLoader)
    .render()
Error types

The EmbedEvent.Error is fired when the following types of errors occur.

  • API
    API call failure error. This error event occurs when an API request is blocked.

    SearchEmbed.on(EmbedEvent.Error, (error) => {
        console.log(error);
        // { type: "Error", data: { errorType: "API", error: { message: '...', error: '...' } } }
    });
  • FULLSCREEN
    Error in presenting a Liveboard or visualization in the full screen mode.

    LiveboardEmbed.on(EmbedEvent.Error, (error) => {
        console.log(error);
        // { type: "Error", data: { errorType: "FULLSCREEN", error: {
        //   message: "Fullscreen API is not enabled",
        // } }}
    })
  • SINGLE_VALUE_FILTER
    Error in updating filter values. This error occurs when a single value filter is applied on a Liveboard and the user tries to update this filter with multiple values.

    LiveboardEmbed.on(EmbedEvent.Error, (error) => {
        console.log(error);
        // { type: "Error", data: { errorType: "SINGLE_VALUE_FILTER", error: {
        //  message: "Filter {filter_name}: Cannot pass multiple filtering elements to this single value filter.",
        // } }}
    })
  • NON_EXIST_FILTER
    Error in applying filter due to a non-existent filter.

    LiveboardEmbed.on(EmbedEvent.Error, (error) => {
        console.log(error);
        // { type: "Error", data: { errorType: "NON_EXIST_FILTER", error: {
        //  message: "UpdateFilters could not update the filter on {filter_name} as it is not an existing filter in the Liveboard. Please edit the Liveboard and add {filter_name} as a filter chip in order to update it programmatically.",
        // } }}
    })
  • INVALID_DATE_VALUE
    Error due to invalid date value in a filter. For example, if the column name is Commit Date and a correct date value is not specified, the INVALID_DATE_VALUE error event is fired.

    LiveboardEmbed.on(EmbedEvent.Error, (error) => {
        console.log(error);
        // { type: "Error", data: { errorType: "INVALID_DATE_VALUE", error: {
        //  message: "UpdateFilters could not update the filter on {filter_name} as invalid date value provided.",
        // } }}
    })
  • INVALID_OPERATOR
    Error due to an invalid operator in filter properties. For example, if you try to apply filters on the Revenue column with the operator as LT and specify multiple values, it may result in an error.

    LiveboardEmbed.on(EmbedEvent.Error, (error) => {
        console.log(error);
        // { type: "Error", data: { errorType: "INVALID_OPERATOR", error: {
        //  message: "UpdateFilters could not update the filter on {filter_name} as invalid operator value provided.",
        // } }}
    })

Modify a behaviorπŸ”—

Embed events can also be used to modify a specific behavior in the embedded app. For example, the hideResults parameter in the SearchEmbed constructor blocks the GO button from displaying the chart or table results. When this attribute is set to true, you can listen to the QueryChanged event to perform actions based on the user’s interaction within the SearchEmbed component.

Handle custom action eventsπŸ”—

If you have added a custom action set as a callback action, you must register an event handler to send data in a payload when the custom action is triggered:

searchEmbed.on(EmbedEvent.customAction, payload => {
    const data = payload.data;
    if (data.id === 'show-data') {
        console.log('Custom Action event:', data.embedAnswerData);
    }
})
liveboardEmbed.on(EmbedEvent.CustomAction, (payload) => {
     if (payload.data.id === 'show-data') {
      const showActionId = 'show-data';
          if (payload.id === showActionId \|\| payload.data.id === showActionId) {
               showData(payload);
          }
      })

Event configuration for React componentsπŸ”—

If you are using React components to embed, you can register to any EmbedEvent by using the on<EventName> convention, for example,onAlert, onCopyToClipboard.

To trigger events on ThoughtSpot components embedded in a React app, import the useEmbedRef hook.

import { LiveboardEmbed, EmbedEvent, useEmbedRef } from '@thoughtspot/visual-embed-sdk/react';

// ...
const MyComponent = ({ dataSources }) => {
     const onLoad = () => {
     console.log(EmbedEvent.Load, {});
     };

     return (
         <SearchEmbed
             dataSources={dataSources}
             onLoad = {logEvent("Load")}
         />
    );
};

Try out in PlaygroundπŸ”—

Try out the embed events in the < a href="https://try-everywhere.thoughtspot.cloud/v2/#/everywhere/playground/liveboard"> Visual Embed Playground and preview changes.

Try Embed event in Playground

Event enumerations and examplesπŸ”—

For information about the supported event objects and examples, see EmbedEvent.

Host eventsπŸ”—

Host events are triggered by the host application in which ThoughtSpot components are embedded. Host events use the .trigger() method to send the event message to embedded ThoughtSpot components in the .trigger(hostEvent, data) format. The host events are part of the HostEvent object; for example, HostEvent.SetVisibleVizs.

Register event listenersπŸ”—

To configure host events, import the HostEvent library into your application setup.

import {
  //...
  HostEvent
} from "@thoughtspot/visual-embed-sdk";

In the following example, the HostEvent.SetVisibleTabs triggers an action to display the tabs specified in the code on an embedded Liveboard.

liveboardEmbed.trigger(HostEvent.SetVisibleTabs, [
 '430496d6-6903-4601-937e-2c691821af3c',
 'f547ec54-2a37-4516-a222-2b06719af726'])

Event trigger and actionsπŸ”—

Host events can be assigned to a custom button or action, on clicking which the event is triggered and initiates the specified action.

Runtime filters can be set programmatically before loading the embedded ThoughtSpot content. Runtime filters can also be updated after the load time using HostEvent.UpdateRuntimeFilters. You can add a UI option or button in your embedding app and assign the HostEvent.UpdateRuntimeFilters to trigger the UpdateRuntimeFilters event when that button is clicked.

In this example, the host event is assigned to a button that updates runtime filters. When a user clicks this button, the HostEvent.UpdateRuntimeFilters is triggered and an action is initiated to update the filters with the attributes specified in the code.

 document.getElementById('updateFilters').addEventListener('click', e => {
     liveboardEmbed.trigger(HostEvent.UpdateRuntimeFilters, [{
             columnName: "state",
             operator: RuntimeFilterOp.EQ,
             values: ["michigan"]
         },
         {
             columnName: "item type",
             operator: RuntimeFilterOp.EQ,
             values: ["Jackets"]
         }
     ]);
 });

Filter from selectionπŸ”—

Filtering from a selection on a chart or table can be implemented by combining the EmbedEvent.VizPointClick or EmbedEvent.VizPointDoubleClick events with the HostEvent.UpdateRuntimeFilters event.

The callback function from the VizPointClick event will need to read the response, parse out the attributes from the response that will be sent to the Runtime Filters object, and then send the attributes and their target fields in the format used by UpdateRuntimeFilters.

Trigger events and complete actions without modalsπŸ”—

To provide an uninterrupted experience for workflows such as pinning an Answer to a Liveboard or saving a search result as an Answer, you can pre-define parameter values in host event objects and trigger actions directly. For HostEvent.Pin and HostEvent.SaveAnswer, the SDK provides the option to define a set of parameters to complete the Pin or Save action without opening a modal or showing a prompt for user’s input.

Parameters for HostEvent.PinπŸ”—

The Pin action is available on the charts and tables generated from a search query, saved Answers, and visualizations on a Liveboard. Generally, when a user initiates the pin action, the Pin to Liveboard modal opens and the user is prompted to specify the Liveboard to pin the object. The modal also allows the user to add or edit the title text of the visualization and create a new Liveboard if required.

With HostEvent.Pin, you can automate the pin workflow to programmatically add an Answer or visualization to a Liveboard. For example, to pin an object to an existing Liveboard, use the following parameters to the host event object:

  • vizId
    String. GUID of the saved Answer or visualization to pin to a Liveboard. Note that after you pin an Answer to a Liveboard, ThoughtSpot creates a copy of the Answer with a new GUID, which is independent of the original Answer object. Optional for pinning a new chart or table generated from a Search query.

  • liveboardId
    String. GUID of the Liveboard to pin the Answer. If there is no Liveboard, you must specify the newLiveboardName to create a new Liveboard.

  • newVizName
    String. Name string for the Answer that will be added as visualization to the Liveboard. Note that each time the user clicks, a new visualization object with a new GUID is generated.

  • tabId
    String. GUID of the Liveboard tab. Adds the Answer to the Liveboard tab specified in the code.

  • newLiveboardName String. Name string for the new Liveboard. Creates a new Liveboard object with the specified name.

  • newTabName
    String. Name string for the new Liveboard tab. Adds a new tab to the Liveboard specified in the code.

  • newVizName
    String. Name string for the visualization. When specified, it adds a new visualization or creates a copy of the Answer or visualization specified in vizId.

In this example, when the HostEvent.Pin is triggered, the Pin action is initiated to add a specific visualization to a specific Liveboard tab:

 const pinResponse = await appEmbed.trigger(HostEvent.Pin, {
    vizId: "8fbe44a8-46ad-4b16-8d39-184b2fada490",
    newVizName: "sales by item type",
    liveboardId: "fa68ae91-7588-4136-bacd-d71fb12dda69",
    tabId: "c135113c-fba0-4220-8e14-7a5f14e0e69f",
 })

In this example, when the HostEvent.Pin is triggered, the Pin action is initiated to add a new visualization to a Liveboard:

 const pinResponse = await searchEmbed.trigger(HostEvent.Pin, {
     newVizName: `Sales by region`,
     liveboardId: "5eb4f5bd-9017-4b87-bf9b-8d2bc9157a5b",
 })

In this example, when the HostEvent.Pin is triggered, the Pin action is initiated to create a new Liveboard with a tab and then pin the Answer or visualization to it.

 const pinResponse = await appEmbed.trigger(HostEvent.Pin, {
     newVizName: "Sales by item type for Arizona",
     newLiveboardName: "Sales",
     newTabName: "Southwest",
 })

If no parameters are defined in the HostEvent.Pin object, the event triggers the Pin action and opens the Pin to Liveboard modal.

searchEmbed.trigger(HostEvent.Pin);

Parameters for HostEvent.SaveAnswerπŸ”—

For HostEvent.SaveAnswer, you can pass the pre-defined attributes such as name and description of the Answer to save the Answer programmatically without showing the Describe your Answer prompt to user.

  • name
    String. Name string for the Answer object.

  • description
    String. Description text for the Answer

const saveAnswerResponse = await searchEmbed.trigger(HostEvent.SaveAnswer, {
    name: "Sales by states",
    description: "Total sales by states in MidWest",
});

If no parameters are defined in the HostEvent.SaveAnswer object, the event triggers the save action and opens the Describe your Answer modal.

searchEmbed.trigger(HostEvent.SaveAnswer);

Event configuration for React componentsπŸ”—

To trigger events on ThoughtSpot components embedded in a React app, use the useEmbedRef hook and set the ref to embedRef constructor prop with .trigger method.

import { LiveboardEmbed, HostEvent, useEmbedRef } from '@thoughtspot/visual-embed-sdk/react';

// ..
const embedRef = useEmbedRef < typeof LiveboardEmbed > ();

const resetFilter = () => {
    embedRef.current.trigger(HostEvent.UpdateRuntimeFilters, [{
            columnName: "state",
            operator: "EQ",
            values: []
        },
        {
            columnName: "product type",
            operator: "EQ",
            values: []
        }
    ]);
};

Try out in PlaygroundπŸ”—

To explore the host event functionality in the Playground, follow these steps:

  • Go to Develop > Visual Embed SDK > Playground.

  • Select the feature to embed, for example, Search.

  • Select the objects to load in the Playground.

  • In the event handler code, add a host event as shown in the following example:

    document.getElementById('tryBtn').addEventListener('click', e => {
      embed.trigger((HostEvent.DownloadAsPng)
    });
  • Click Run.

  • Click Try Event to trigger the action.

The following video shows how to register HostEvent.RemoveColumn and remove a column from the search query string using the Try button:

Try it out in Playground

Event enumerations and examplesπŸ”—

For information about the supported event objects and examples, see HostEvent.