UNPKG

19.9 kBMarkdownView Raw
1<h1 align="center">MongoDB Charts Embedding SDK</h1>
2
3<div align="center">
4
5Programmatically **embed** and **control** MongoDB Charts in your application.
6
7[![npm](https://img.shields.io/npm/v/@mongodb-js/charts-embed-dom.svg)](https://www.npmjs.com/package/@mongodb-js/charts-embed-dom/)
8[![npm](https://img.shields.io/npm/l/@mongodb-js/charts-embed-dom.svg)](https://www.npmjs.com/package/@mongodb-js/charts-embed-dom/)
9
10<div style="max-width:600px;width:100%">
11
12![demo of embedding](https://user-images.githubusercontent.com/19422770/79284750-efe86800-7efe-11ea-9ed0-9813e1a0b6d6.gif)
13[Explore this example yourself!](https://codesandbox.io/s/github/mongodb-js/charts-embed-sdk/tree/master/examples/unauthenticated)
14
15</div>
16
17</div>
18
19## Example Usage
20
21```js
22import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
23
24const sdk = new ChartsEmbedSDK({
25 baseUrl: 'https://charts.mongodb.com/charts-charts-fixture-tenant-zdvkh',
26});
27
28// embed a chart
29const chart = sdk.createChart({
30 chartId: '48043c78-f1d9-42ab-a2e1-f2d3c088f864',
31});
32
33// render the chart into a container
34chart
35 .render(document.getElementById('chart'))
36 .catch(() => window.alert('Chart failed to initialise'));
37
38// refresh the chart whenever #refreshButton is clicked
39document
40 .getElementById('refreshButton')
41 .addEventListener('click', () => chart.refresh());
42
43// embed a dashboard
44const dashboard = sdk.createDashboard({
45 dashboardId: '61d02578-6148-4c87-9cad-1fbaef50a0d3',
46});
47
48// render the chart into a container
49dashboard
50 .render(document.getElementById('dashboard'))
51 .catch(() => window.alert('Dashboard failed to initialise'));
52```
53
54## Getting Started
55
56### Installation
57
58[![module formats: umd, cjs, and esm](https://img.shields.io/badge/module%20formats-umd%2c%20cjs%2c%20esm-green.svg?style=flat)](https://unpkg.com/@mongodb-js/charts-embed-dom/dist/)
59
601. Install the `@mongodb-js/charts-embed-dom` package
61
62```bash
63# yarn
64yarn add @mongodb-js/charts-embed-dom
65
66# npm
67npm install @mongodb-js/charts-embed-dom --save
68```
69
702. Use the package
71
72```js
73import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
74```
75
763. Profit 📈
77
78### Distribution Bundle
79
80A [universal module definition](https://github.com/umdjs/umd) bundle is also published on npm under the /dist folder for consumption.
81
82You can use the UMD to run `@mongodb-js/charts-embed-sdk` directly in the browser.
83
84```html
85<!-- library -->
86<script src="https://unpkg.com/@mongodb-js/charts-embed-dom"></script>
87
88<script>
89 const ChartsEmbedSDK = window.ChartsEmbedSDK;
90
91 const sdk = new ChartsEmbedSDK({ ... });
92 const chart = sdk.createChart({ ... });
93
94 chart.render(document.getElementById('chart'));
95</script>
96```
97
98## FAQs
99
100### I'm using Rollup, what configuration options do I need to set?
101
102To use the Embedding SDK with Rollup, you'll need to have a `rollup.config.js` that looks like:
103
104```
105import resolve from '@rollup/plugin-node-resolve';
106import cjs from '@rollup/plugin-commonjs';
107
108export default {
109 input: 'index.js',
110 output: {
111 file: 'bundle.js',
112 format: 'cjs'
113 },
114 plugins: [ cjs(), resolve({ browser: true, preferBuiltins: false }) ]
115};
116```
117
118## API
119
120### ChartsEmbedSDK
121
122The default export of `@mongodb-js/charts-embed-dom`.
123
124#### `constructor(options: EmbedOptions): ChartsEmbedSDK`
125
126Creates 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.
127
128#### `createChart(options: EmbedChartOptions): Chart`
129
130Creates an instance of a Chart that can be used to embed and control the MongoDB Chart specified by `chartId`.
131
132#### `createDashboard(options: EmbedDashboardOptions): Dashboard`
133
134Creates an instance of a Dashboard that can be used to embed and control the embedded dashboard specified by `dashboardId`.
135
136### EmbedChartOptions
137
138These 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.
139
140| name | type | description |
141| --------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
142| baseUrl | string | The base url for your MongoDB Charts instance, it should look something like: `https://charts.mongodb.com/charts-example-url-zdvkh`. |
143| 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. |
144| 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). |
145| 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). |
146| 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. |
147| 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. |
148| background | string | A [background color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) for the embedded chart e.g. 'transparent'. If no background is provided it will set a default based on the theme. |
149| filter | object | A filter to apply to the embedded chart. This expects an object that contains a valid [query operators](https://docs.mongodb.com/manual/reference/operator/query/#query-selectors). Any fields referenced in this filter are expected to be added to the allowed list in the 'Embed Chart' dialog for each Chart you wish to filter on. |
150| getUserToken | function | A function that should return a valid JWT token to use for authenticating the render request. |
151| 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. |
152| showAttribution | boolean | Whether to show the MongoDB attribution logo on the embedded chart. By default, this is set to `true`. |
153
154### EmbedDashboardOptions
155
156These 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.
157
158| name | type | description |
159| ---------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
160| baseUrl | string | The base url for your MongoDB Charts instance, it should look something like: `https://charts.mongodb.com/charts-example-url-zdvkh`. |
161| dashboardId | string | The dashboard id for the embedded dashboard. This can be found in the `Embed Dashboard` dialog. |
162| 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). |
163| 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). |
164| 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. |
165| 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. |
166| background | string | A [background color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) for the embedded dashboard e.g. 'transparent'. If no background is provided it will set a default based on the theme. |
167| chartsBackground | string | A [background color](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) for all charts in the embedded dashboard e.g. 'transparent'. |
168| getUserToken | function | A function that should return a valid JWT token to use for authenticating the render request. |
169| theme | 'light' \| 'dark' | The color scheme to apply to the dashboard. Defaults to `light`. |
170| showAttribution | boolean | Whether to show the MongoDB attribution logo on the embedded dashboard. By default, this is set to `true`. |
171| 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`. |
172| 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`. |
173
174### Chart
175
176The Chart instance returned by `ChartsEmbedSDK.createChart({ ... })`.
177
178#### `render(container: HTMLElement): Promise<void>`
179
180Renders 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`).
181
182#### `refresh(): Promise<void>`
183
184Triggers a refresh of the chart, if it is embedded.
185
186#### `setAutoRefresh(bool: boolean): Promise<void>`
187
188Enable or disable chart auto refresh. Auto refresh is enabled by default.
189
190#### `isAutoRefresh(): Promise<boolean>`
191
192Returns whether auto refreshing is enabled or not.
193
194#### `setMaxDataAge(seconds: number): Promise<void>`
195
196Sets a duration (in seconds) for how old a chart is allowed to be before it is considered expired.
197
198#### `getMaxDataAge(): Promise<number>`
199
200Returns the duration (in seconds) that has to pass before a chart is considered stale.
201
202#### `setFilter(filter: object): Promise<void>`
203
204Applies a filter to the embedded chart. This expects an object that contains valid [query operators](https://docs.mongodb.com/manual/reference/operator/query/#query-selectors). Any fields referenced in this filter are expected to be added to the allowed list in the 'Embed Chart' dialog. An empty document `{}` is equivilent to no filter.
205
206#### `getFilter(): Promise<object>`
207
208Returns the current filter applied to the embedded chart.
209
210#### `setTheme(theme: 'dark' | 'light'): Promise<void>`
211
212Sets 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.
213
214#### `getTheme(): Promise<string>`
215
216Returns the current theme applied to the embedded chart.
217
218#### `addEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>`
219
220Adds 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](https://docs.mongodb.com/charts/saas/handle-click-events/).
221
222#### `removeEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>`
223
224Removes an event listener that was previously added. You need to provide the same parameters that were used for subscribing to the event.
225
226#### `setHighlight(value: object): Promise<void>`
227
228Sets a highlight to apply to an embedded chart. The `value` object parameter should contain valid [query operators](https://docs.mongodb.com/manual/reference/operator/query/#query-selectors). It is the same type of object that can be used in `setFilter`. 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](https://docs.mongodb.com/charts/saas/handle-click-events/).
229
230#### `getHighlight(): Promise<object>`
231
232Returns the current highlight applied to an embedded chart.
233
234#### `getData(): Promise<object>`
235
236Returns the underlying data used to render chart. It has following structure
237
238```
239{
240 // an object whose key is the name of a channel, e.g. x, y, etc
241 fields: { [channel]: string },
242 // an array of object whose key is the name of a channel, e.g. x, y, etc
243 documents: Array<{ [channel]: any }>
244}
245```
246
247### Dashboard
248
249The Dashboard instance returned by `ChartsEmbedSDK.createDashboard({ ... })`.
250
251#### `render(container: HTMLElement): Promise<void>`
252
253Renders a dashboard 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 `refresh`).
254
255#### `refresh(): Promise<void>`
256
257Triggers a refresh of the dashboard.
258
259#### `setAutoRefresh(bool: boolean): Promise<void>`
260
261Enable or disable auto refresh. Auto refresh is enabled by default.
262
263#### `isAutoRefresh(): Promise<boolean>`
264
265Returns whether auto refreshing is enabled or not.
266
267#### `setMaxDataAge(seconds: number): Promise<void>`
268
269Sets a duration (in seconds) for how old a chart on a dashboard is allowed to be before it is considered expired.
270
271#### `getMaxDataAge(): Promise<number>`
272
273Returns the duration (in seconds) that has to pass before a chart on a dashboard is considered stale.
274
275#### `setTheme(theme: 'dark' | 'light'): Promise<void>`
276
277Sets the current theme of the embedded dashboard. Defaults to `'light'`;
278
279#### `getTheme(): Promise<string>`
280
281Returns the current theme applied to the embedded dashboard.
282
283#### `setChartsBackground(color: string): Promise<void>`
284
285Sets a custom background color that will be applied to all charts of the embedded dashboard.
286
287#### `getChartsBackground(): Promise<string>`
288
289Returns the current custom background color.
290
291#### `setWidthMode(mode: 'fixed' | 'scale'): Promise<void>`
292
293Sets the width mode that will be applied to all charts of the embedded dashboard. Defaults to `'fixed'`;
294
295#### `getWidthMode(): Promise<'fixed' | 'scale'>`
296
297Returns the current width mode.
298
299#### `setHeightMode(mode: 'fixed' | 'scale'): Promise<void>`
300
301Sets the height mode that will be applied to all charts of the embedded dashboard. Defaults to `'fixed'`;
302
303#### `getHeightMode(): Promise<'fixed' | 'scale'>`
304
305Returns the current height mode.
306
307#### `getChart(chartId: string): Promise<DashboardChart>`
308
309Returns an instance `DashboardChart` that has the specified chart id.
310
311#### `getAllCharts(): Promise<DashboardChart[]>`
312
313Returns an array of `DashboardChart` instances of all charts on the embedded dashboard.
314
315### DashboardChart
316
317The chart instance returned by `Dashboard.getChart('chartId')` or `Dashboard.getAllCharts()`.
318
319#### `refresh(): Promise<void>`
320
321Triggers a refresh of the chart.
322
323#### `addEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>`
324
325Adds 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](https://docs.mongodb.com/charts/saas/handle-click-events/).
326
327#### `removeEventListener(event: string, eventHandler: (payload: object) => void, options: object): Promise<void>`
328
329Removes an event listener that was previously added. You need to provide the same parameters that were used for subscribing to the event.
330
331### getRealmUserToken(client: StitchClient): string
332
333A helper function to use the Realm authentication provider.
334Returns a value to pass to the `getUserToken` prop via a function.