@mongodb-js/charts-embed-dom
TypeScript icon, indicating that this package has built-in type declarations

3.2.1 • Public • Published

MongoDB Charts Embedding SDK

Programmatically embed and control MongoDB Charts in your application.

npm npm

Example Usage

import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';

const sdk = new ChartsEmbedSDK({
  baseUrl: 'https://charts.mongodb.com/charts-charts-fixture-tenant-zdvkh',
});

// embed a chart
const chart = sdk.createChart({
  chartId: '48043c78-f1d9-42ab-a2e1-f2d3c088f864',
});

// render the chart into a container
chart
  .render(document.getElementById('chart'))
  .catch(() => window.alert('Chart failed to initialise'));

// refresh the chart whenever #refreshButton is clicked
document
  .getElementById('refreshButton')
  .addEventListener('click', () => chart.refresh());

// embed a dashboard
const dashboard = sdk.createDashboard({
  dashboardId: '61d02578-6148-4c87-9cad-1fbaef50a0d3',
});

// render the chart into a container
dashboard
  .render(document.getElementById('dashboard'))
  .catch(() => window.alert('Dashboard failed to initialise'));

Getting Started

Installation

module formats: umd, cjs, and esm

  1. Install the @mongodb-js/charts-embed-dom package
# yarn
yarn add @mongodb-js/charts-embed-dom

# npm
npm install @mongodb-js/charts-embed-dom --save
  1. Use the package
import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
  1. Profit 📈

Distribution Bundle

A universal module definition bundle is also published on npm under the /dist folder for consumption.

You can use the UMD to run @mongodb-js/charts-embed-sdk directly in the browser.

<!-- library  -->
<script src="https://unpkg.com/@mongodb-js/charts-embed-dom"></script>

<script>
  const ChartsEmbedSDK = window.ChartsEmbedSDK;

  const sdk = new ChartsEmbedSDK({ ... });
  const chart = sdk.createChart({ ... });

  chart.render(document.getElementById('chart'));
</script>

FAQs

I'm using Rollup, what configuration options do I need to set?

To use the Embedding SDK with Rollup, you'll need to have a rollup.config.js that looks like:

import resolve from '@rollup/plugin-node-resolve';
import cjs from '@rollup/plugin-commonjs';

export default {
  input: 'index.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [ cjs(), resolve({ browser: true, preferBuiltins: false }) ]
};

API


ChartsEmbedSDK

The default export of @mongodb-js/charts-embed-dom.

constructor(options: EmbedOptions): ChartsEmbedSDK

Creates an SDK object that can create Chart/Dashboard instances. Accepts an object that contains any default options to set for all Charts/Dashboards created using this SDK instance.

createChart(options: EmbedChartOptions): Chart

Creates an instance of a Chart that can be used to embed and control the MongoDB Chart specified by chartId.

createDashboard(options: EmbedDashboardOptions): Dashboard

Creates an instance of a Dashboard that can be used to embed and control the embedded dashboard specified by dashboardId.


EmbedChartOptions

These options configure the behaviour of a Chart when it is first embedded. After this, you can control the configuration of the Chart by calling methods on its handle.

name type description
baseUrl string The base url for your MongoDB Charts instance, it should look something like: https://charts.mongodb.com/charts-example-url-zdvkh.
chartId string The chart id for the embedded chart. This can be found in the Embed Chart dialog when viewing a chart on a Dashboard.
width string | number The width of the embedded chart. If no width is provided, it will default to stretching to the width of its container. If a value is provided without units, it will be assumed to be pixels (px).
height string | number The height of the embedded chart. If no height is provided, it will default to stretching to the height of its container. If a value is provided without units, it will be assumed to be pixels (px).
autoRefresh boolean Specifies whether the chart automatically refreshes. If omitted, charts automatically refresh. Use this option with the maxDataAge option to configure how often the chart refreshes.
maxDataAge number Specifies the maximum age of data to load from the cache when loading or refreshing the chart. If omitted, MongoDB Charts renders the chart with data from the cache if the data is less than one hour old.
background string A background color for the embedded chart e.g. 'transparent'. If no background is provided it will set a default based on the theme.
filter object A filter to apply to the embedded chart. This expects an object that contains a valid query operators. Any fields referenced in this filter are expected to be added to the allowed fields list in the 'Embed Chart' dialog for each Chart you wish to filter on.
getUserToken function A function that should return a valid JWT token to use for authenticating the render request.
theme 'light' | 'dark' The color scheme to apply to the chart. Defaults to light. If the theme is set to 'dark', you will need to ensure that your background color has appropriate contrast as by default a chart's background is transparent.
showAttribution boolean Whether to show the MongoDB attribution logo on the embedded chart. By default, this is set to true.
renderingSpec object A rendering specification to apply customizations that the embedded chart supports. See the rendering specification for details on what are the supported customizations and the format of this object.

EmbedDashboardOptions

These options configure the behaviour of a Dashboard when it is first embedded. After this, you can control the configuration of the Dashboard by calling methods on its handle.

name type description
baseUrl string The base url for your MongoDB Charts instance, it should look something like: https://charts.mongodb.com/charts-example-url-zdvkh.
dashboardId string The dashboard id for the embedded dashboard. This can be found in the Embed Dashboard dialog.
width string | number The width of the embedded dashboard. If no width is provided, it will default to stretching to the width of its container. If a value is provided without units, it will be assumed to be pixels (px).
height string | number The height of the embedded dashboard. If no height is provided, it will default to stretching to the height of its container. If a value is provided without units, it will be assumed to be pixels (px).
autoRefresh boolean Specifies whether the dashboard automatically refreshes. If omitted, dashboards automatically refresh. Use this option with the maxDataAge option to configure how often the dashboard refreshes.
maxDataAge number Specifies the maximum age of data to load from the cache when loading or refreshing the dashboard. If omitted, MongoDB Charts renders the dashboard with data from the cache if the data is less than one hour old.
background string A background color for the embedded dashboard e.g. 'transparent'. If no background is provided it will set a default based on the theme.
chartsBackground string A background color for all charts in the embedded dashboard e.g. 'transparent'.
getUserToken function A function that should return a valid JWT token to use for authenticating the render request.
theme 'light' | 'dark' The color scheme to apply to the dashboard. Defaults to light.
showAttribution boolean Whether to show the MongoDB attribution logo on the embedded dashboard. By default, this is set to true.
widthMode 'fixed' | 'scale' Width behaviour of charts in an embedded dashboard. fixed: width of charts will remain the same as the configured on dashboard; scale: width of charts will scale according to the container. Defaults to fixed.
heightMode 'fixed' | 'scale' Height behaviour of charts in an embedded dashboard. fixed: height of charts will remain the same as the configured on dashboard; scale: height of charts will scale according to the container. Defaults to fixed.
showTitleAndDesc boolean Whether to show the dashboard title and description on the embedded dashboard. By default, this is set to false .
filter object A filter to apply to all charts in the embedded dashboard. This expects an object that contains a valid query operators. Any fields referenced in this filter are expected to be added to the allowed fields list for filtering in the 'Embed Dashboard' dialog.
charts array of objects Embedding options to apply to specified embedded dashboard charts. Currently, we only support filters. An example is [ { chartId: '0b1e7577-5ad6-4be4-8b13-5b0bee7d291f', filter: { city: 'Sydney' }}] where chartId is the embedding chart id of the dashboard chart, and filter is an MQL expression for what you want to filter this chart's data by.

Chart

The Chart instance returned by ChartsEmbedSDK.createChart({ ... }).

render(container: HTMLElement): Promise<void>

Renders a chart into the specified container and should only be invoked once. It returns a Promise that will resolve once the chart is 'ready' to accept commands (like setFilter, refresh).

refresh(): Promise<void>

Triggers a refresh of the chart, if it is embedded.

setAutoRefresh(bool: boolean): Promise<void>

Enable or disable chart auto refresh. Auto refresh is enabled by default.

isAutoRefresh(): Promise<boolean>

Returns whether auto refreshing is enabled or not.

setMaxDataAge(seconds: number): Promise<void>

Sets a duration (in seconds) for how old a chart is allowed to be before it is considered expired.

getMaxDataAge(): Promise<number>

Returns the duration (in seconds) that has to pass before a chart is considered stale.

setFilter(filter: object): Promise<void>

Applies a filter to the embedded chart. This expects an object that contains valid query operators. Any fields referenced in this filter are expected to be added to the allowed list in the 'Embed Chart' dialog. An empty document {} is equivalent to no filter.

getFilter(): Promise<object>

Returns the current filter applied to the embedded chart.

setTheme(theme: 'dark' | 'light'): Promise<void>

Sets the current theme of the embedded chart. When setting the theme to 'dark', you will need to ensure that your background color has appropriate contrast as by default a chart's background is transparent.

getTheme(): Promise<string>

Returns the current theme applied to the embedded chart.

addEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>

Adds an event listener to an embedded chart. We currently support only 'click' events. The payload parameter in the event callback contains details on the chart element clicked. You can also define the chart's mark roles and/or types for which you want to receive event information in the options parameter. More information regarding how to handle click events can be found in the Charts documentation.

removeEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>

Removes an event listener that was previously added. You need to provide the same parameters that were used for subscribing to the event.

setHighlight(value: object): Promise<void>

Sets a highlight to apply to an embedded chart. The value object parameter should contain valid query operators. It is the same type of object that can be used in setFilter. However, it doesn't support some query expressions and there are some specifics about what is highlightable. You can clear an existing highlight by setting the value to an empty object {}. More information regarding charts highlighting can be found in the Charts documentation.

getHighlight(): Promise<object>

Returns the current highlight applied to an embedded chart.

getData(): Promise<object>

Returns the underlying data used to render chart. It has the following structure

{
  // an object whose key is the name of a channel, e.g. x, y, etc
  fields: { [channel]: string },
  // an array of object whose key is the name of a channel, e.g. x, y, etc
  documents: Array<{ [channel]: any }>
}

getImage(option: { encoding: 'base64' | 'binary' }): Promise<string|Blob>

Returns a PNG image of the embedded chart in the required encoding, i.e. 'base64' or 'binary'. Note that Table Chart is not supported.

setRenderingSpecOverride(value: object): Promise<void>

Sets a customization on the embedded chart. See the rendering specification for details on what is customizable and the format of this object.

getRenderingSpecOverride(): Promise<object> | undefined

Returns the customizations set on the embedded chart from calling setRenderingSpecOverride().

getChannels(): Promise<object>

Returns the chart channels for the embedded chart.

getCustomizableAxes(): Promise<object>

Returns the customizable chart axes for the embedded chart. This will return an empty object if no axes are customizable for the embedded chart.


Dashboard

The Dashboard instance returned by ChartsEmbedSDK.createDashboard({ ... }).

render(container: HTMLElement): Promise<void>

Renders a dashboard into the specified container and should only be invoked once. It returns a Promise that will resolve once the dashboard is 'ready' to accept commands (like refresh).

Note that the charts inside the embedded dashboard will render as soon as their data is fetched. Since the charts data fetch is an asynchronous process, some of the charts will render with data after the dashboard renders itself. Keep this in mind when using the dashboard charts methods.

refresh(): Promise<void>

Triggers a refresh of the dashboard.

setAutoRefresh(value: boolean): Promise<void>

Enable or disable auto refresh. Auto refresh is enabled by default.

isAutoRefresh(): Promise<boolean>

Returns whether auto refreshing is enabled or not.

setMaxDataAge(seconds: number): Promise<void>

Sets a duration (in seconds) for how old a chart on a dashboard is allowed to be before it is considered expired.

getMaxDataAge(): Promise<number>

Returns the duration (in seconds) that has to pass before a chart on a dashboard is considered stale.

setTheme(theme: 'dark' | 'light'): Promise<void>

Sets the current theme of the embedded dashboard. Defaults to 'light';

getTheme(): Promise<string>

Returns the current theme applied to the embedded dashboard.

setChartsBackground(color: string): Promise<void>

Sets a custom background color that will be applied to all charts of the embedded dashboard.

getChartsBackground(): Promise<string>

Returns the current custom background color.

setWidthMode(mode: 'fixed' | 'scale'): Promise<void>

Sets the width mode that will be applied to all charts of the embedded dashboard. Defaults to 'fixed';

getWidthMode(): Promise<'fixed' | 'scale'>

Returns the current width mode.

setHeightMode(mode: 'fixed' | 'scale'): Promise<void>

Sets the height mode that will be applied to all charts of the embedded dashboard. Defaults to 'fixed';

getHeightMode(): Promise<'fixed' | 'scale'>

Returns the current height mode.

setShowAttribution(value: boolean): Promise<void>

Enable or disable the attribution logo. Attribution is enabled by default.

isShowAttribution(): Promise<boolean>

Returns whether the attribution logo is enabled.

setFilter(filter: object): Promise<void>

Applies a filter to all charts in an embedded dashboard. This expects an object that contains valid query operators. Any fields referenced in this filter are expected to be added to the allowed list in the 'Embed Dashboard' dialog (or in the 'Embed Chart' dialog for all charts in the dashboard). An empty document {} is equivalent to no filter. Note: the embedded dashboard filter is independent from the embedded dashboard chart filter - if you have set both of them, they will both apply on the chart.

getFilter(): Promise<object>

Returns the current filter applied directly to the embedded dashboard.

getChart(chartId: string): Promise<DashboardChart>

Returns an instance DashboardChart that has the specified chart id.

getAllCharts(): Promise<DashboardChart[]>

Returns an array of DashboardChart instances of all charts on the embedded dashboard.

getImage(option: { encoding: 'base64' | 'binary' }): Promise<string|Blob>

Returns a PNG image of the embed dashboard in the required encoding, i.e. 'base64' or 'binary'.


DashboardChart

The chart instance returned by Dashboard.getChart('chartId') or Dashboard.getAllCharts().

refresh(): Promise<void>

Triggers a refresh of the chart.

addEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>

Adds an event listener to the embedded chart. We currently support only 'click' events. The payload parameter in the event callback contains details on the chart element clicked. You can also define the chart's mark roles and/or types for which you want to receive event information in the options parameter. More information regarding how to handle click events can be found in the Charts documentation.

removeEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>

Removes an event listener that was previously added. You need to provide the same parameters that were used for subscribing to the event.

setFilter(filter: object): Promise<void>

Applies a filter to the embedded dashboard chart. This expects an object that contains valid query operators. Any fields referenced in this filter are expected to be added to the allowed list in the 'Embed Chart' dialog or in the "Embed Dashboard" dialog (in which case they will be allowed for all charts in the dashboard). An empty document {} is equivalent to no filter. Note: the embedded dashboard chart filter is independent from the embedded dashboard filter - if you have set both of them, they will both apply on the chart.

getFilter(): Promise<object>

Returns the current filter applied directly to the embedded dashboard chart. Note: if you have applied a filter on the embedded dashboard, it will not be returned in this dashboard chart method. To get the dashboard filter, use the getFilter() method on the dashboard entity.

setHighlight(value: object): Promise<void>

Sets a highlight to apply to an embedded dashboard chart. The value object parameter should contain valid query operators. It is the same type of object that can be used in setFilter. However, it doesn't support some query expressions and there are some specifics about what is highlightable. You can clear an existing highlight by setting the value to an empty object {}. More information regarding charts highlighting can be found in the Charts documentation.

getHighlight(): Promise<object>

Returns the current highlight applied to an embedded dashboard chart.

getData(): Promise<object>

Returns the underlying data used to render dashboard chart. It has the following structure.

{
  // an object whose key is the name of a channel, e.g. x, y, etc
  fields: { [channel]: string },
  // an array of object whose key is the name of a channel, e.g. x, y, etc
  documents: Array<{ [channel]: any }>
}

Limitation: Unlike the getData() method for embedded charts, in the case for embedded dashboard charts, the documents might not be available directly after the dashboard render. The reason for that is the nature of the embedded dashboard, and that we render the charts inside it as soon as we fetch their data. Since the charts data fetch is an asynchronous process, the dashboard chart data might not be available for all dashboard charts directly after the dashboard render() method.


Refresh Tolerance

Refresh tolerance refers to the maximum age of the data to load from cache. It is used to determine whether an embedded chart or dashboard needs to fetch fresh data from the server or use the cached data. This value is affected by the combination of autoRefresh and maxDataAge set to the embedded entity. Below table illustrates the different scenarios.

autoRefresh maxDataAge tolerance (secs)
true undefined | null 3600
true -1 Infinity (always use cache data)
true 0 60
true >0 and <60 60
true >=60 Same value as maxDataAge
false undefined | null 3600
false -1 Infinity (always use cache data)
false >=0 Same value as maxDataAge

Realm Web Authentication

getRealmUserToken(client: StitchAppClient | RealmAppClient): string

A helper function to use the Atlas App Services authentication provider. Returns a value to pass to the getUserToken prop via a function.

Dependencies (5)

Dev Dependencies (26)

Package Sidebar

Install

npm i @mongodb-js/charts-embed-dom

Weekly Downloads

6,436

Version

3.2.1

License

Apache-2.0

Unpacked Size

3.65 MB

Total Files

36

Last publish

Collaborators

  • pulkitkalra
  • mongo-j
  • shaketbaby
  • mutukrish
  • tomhollander
  • matt_d_rat
  • srv-charts-read-only
  • srv-mdb-charts-build-bot
  • kristina.stefano
  • jarjee