@bmap-analytics/react
v0.12.0
Published
BMAP React SDK — render dashboards natively in your app. No iframe.
Maintainers
Readme
@bmap-analytics/react
Render BMAP dashboards natively inside your React app. No iframe.
npm install @bmap-analytics/reactQuick start
import { BmapProvider, Dashboard } from "@bmap-analytics/react";
export function Analytics() {
return (
<BmapProvider
baseUrl="https://analytics.acme.com"
fetchToken={(dashboardId) =>
fetch(`/api/bmap-token?dashboard=${dashboardId}`).then((r) => r.json())
}
>
<Dashboard id="019f8c…" />
</BmapProvider>
);
}fetchToken calls your backend, which mints the token with @bmap-analytics/node or
the Python SDK. That indirection is the security model — see why.
Token refresh, retry after a recoverable auth failure, loading and error states are all
handled. There is no setInterval for you to write.
Making it look like your product
Three levels, pick the one that fits.
Restyle the built-ins. Colours and geometry are props; the charts inherit your text colour:
<Dashboard id="019f8c…" colors={["#5b8def", "#f0a04b"]} rowHeight={72} gap={16} />rowHeight also takes a mode rather than a number. "proportional" (the default) scales
rows with the container's width, bounded to ±40%, so tiles keep their proportions instead of
turning into tall thin boxes on a narrow page. "content" grows a row to fit what is inside
it — for a tile holding a table you would rather see whole than scroll. "fill" divides the
container's own height between the rows the layout uses, so the dashboard fits exactly with
no inner scroll; that one needs you to give the container a height, and falls back to
proportional when there is nothing to divide.
The grid also collapses to fewer columns in a narrow container and stacks on a phone. Pass
responsive={false} only if your page guarantees the width the dashboard was designed for —
the saved layout is then rendered exactly as authored, tiles too narrow to read included.
Replace the tile. Keep the layout and data handling, supply your own chrome:
<Dashboard
id="019f8c…"
renderWidget={(widget, result) => (
<Card title={widget.name}>
{result?.error ? <Alert>{result.error}</Alert> : <WidgetChart widget={widget} result={result!} />}
</Card>
)}
/>Take the data and render it yourself. No BMAP components at all:
const { data, loading, error } = useDashboard({ dashboardId: "019f8c…" });
// data.data.widgets[i] → { columns, rows, rowCount, fromCache, error }useWidget(widgetId) does the same for a single tile.
Parameters
Broadcast to every widget on the dashboard; each query ignores names it does not declare.
<Dashboard id="019f8c…" parameters={{ product: "Widget" }} />These are presentation parameters. They cannot change which rows the viewer may see — that is fixed by the token.
Filters
A dashboard's author can put a filter bar on it — a date range, a select, a number range, a
search box. They arrive on the definition as dashboard.filters, and driving them is the
same thing as setting parameters: a filter writes the query parameter it is bound to, and
reaches only the widgets whose saved query declares that name.
Headless first, like everything else here. useDashboardFilters owns the values; FilterBar
is one way to render them:
import { Dashboard, FilterBar, useDashboard, useDashboardFilters } from "@bmap-analytics/react";
function Analytics() {
const { data } = useDashboard({ dashboardId: "019f8c…" });
const filters = useDashboardFilters(data?.dashboard.filters ?? [], { region: "EU" });
return (
<>
<FilterBar filters={data?.dashboard.filters ?? []} values={filters.values} onChange={filters.setFilter} />
<Dashboard id="019f8c…" parameters={filters.values} />
</>
);
}<Dashboard> does not render the bar itself. Where the controls sit — above the grid, in
your own page header, in a drawer — is a layout decision only your app can make, and a bar
the SDK injected would be the one piece of chrome you could not move.
const { values, setFilter, setValues, reset } = useDashboardFilters(filters, initial);initial opens the dashboard on a particular window — "this month", or whatever range the
surrounding page is already showing. reset() clears the viewer's choices rather than
restating the authored defaults: the server applies those to any request that omits them, so
echoing them back would be a round trip saying the same thing.
Relative windows are resolved by the server, not here. "Last 30 days" is sent as
{ $relative: { unit: "day", count: 30, … } } and resolved once, in the tenant's timezone,
for the whole dashboard — so twelve widgets cannot end up with twelve slightly different
ideas of "now", and a scheduled report with no browser at all resolves it the same way.
DATE_PRESETS has the usual windows ready to hand.
A select filter's options are fetched per viewer, narrowed by the same security context as the data — nobody is shown the existence of a value they could not have queried:
const { values, truncated, loading } = useFilterValues("region", { search, enabled: open });Not fetched until the control is opened: a dashboard with six selects should not run six
queries against your customer's database to paint a page nobody has touched. search is
debounced and re-queries the server rather than filtering the array, because the list is
capped — truncated means there are values that are not in it to filter.
Building your own controls? Take the hook and skip FilterBar, or keep the bar and override
one control with its renderControl prop.
A wallboard
<Dashboard id="019f8c…" refreshIntervalMs={30_000} />Errors
import { BmapError } from "@bmap-analytics/react";
<Dashboard
id="019f8c…"
renderError={(error, retry) => (
<MyError
message={error.message}
canRetry={error instanceof BmapError ? error.isRetryable : true}
onRetry={retry}
/>
)}
/>| error.code | Meaning |
|---|---|
| token_expired, session_revoked | A fresh token fixes it — the SDK already tried once |
| forbidden | Configuration: usually a missing resource grant |
| quota_exceeded | Ceiling reached; error.retryAfter has the seconds |
| not_entitled | The organization's plan does not include this |
| network, server | Transient; already retried with backoff |
Letting viewers save a widget as an image
<Dashboard> renders a save button on any widget whose author allowed it. There is nothing
to switch on in the SDK:
<Dashboard id="019f…" /> // save buttons appear where the dashboard permits themWhether a tile offers this is resolved by the server from the widget's own setting and the
dashboard's override, and arrives on widget.download. That is deliberate — it is neither
the SDK's decision nor the host's. A board whose author said "no downloads" means it wherever
it is shown, not only inside the Studio.
Charts are captured with ECharts' own renderer at the configured pixel ratio, with the background painted first — the usual destination is a slide, and a transparent capture would come out black once JPEG dropped the alpha. Tiles drawn as text (a stat or a table) have no image to save, so no button appears.
Building your own tile? The hook does the capture and tells you whether to offer it:
import { DownloadButton, useWidgetDownload, WidgetChart } from "@bmap-analytics/react";
function MyTile({ widget, result }) {
const ref = useRef<HTMLDivElement>(null);
const download = useWidgetDownload(widget.download, widget.name, ref);
return (
<div ref={ref}>
{/* Also gate on a result: capturing before the data lands saves an empty canvas,
and over a failed widget would save the error message. */}
{download.offered && result && !result.error && (
<DownloadButton onClick={download.save} label={`Save ${widget.name} as JPEG`} />
)}
<WidgetChart widget={widget} />
</div>
);
}useWidgetDownload returns { save, offered }. Pass it the element the chart is rendered
into — it finds the ECharts instance inside.
Why your backend
The token carries the viewer's security context — which rows they may see — and it is signed, so the browser cannot alter it. If your frontend could mint one, your customer could mint one too, and choose their own context.
That is why fetchToken exists rather than an apiKey prop, and why
@bmap-analytics/node throws if it detects a browser.
Your backend mints, and that is all it does. It is not on the data path: once the browser holds a token, every dashboard, widget and data request goes straight from the SDK to BMAP. Nothing needs to be proxied through a service of yours, and putting one in the middle would buy nothing — the token already says who the viewer is, and BMAP already enforces it.
Letting the viewer choose a dashboard
For a frontend-only integration, where the viewer signs in to BMAP itself rather than your
backend minting on their behalf. Pass their own BMAP token as viewerToken and the listing
hooks work:
<BmapProvider baseUrl={url} fetchToken={getToken} viewerToken={mySignedInUsersBmapToken}>
<Picker />
</BmapProvider>;
function Picker() {
const { data, loading, error, reload } = useDashboards({ embeddableOnly: true });
if (loading) return <Spinner />;
if (error) return <p>{error.message}</p>;
return data.map((d) => <button key={d.id} onClick={() => open(d.id)}>{d.name}</button>);
}useDashboards({ status?, embeddableOnly? }); // DashboardSummary[]
useWidgets({ dashboardId?, queryId?, withPlacements? }); // WidgetSummary[]Both return the same { data, loading, error, reload } shape as useDashboard.
Without viewerToken they report an error saying so, rather than an empty list — "nothing
to list with" and "nothing to list" are different answers, and an empty array would send
someone hunting for missing dashboards. That is the correct state for an integration that
mints tokens on its backend: an embed token is pinned to one dashboard and cannot enumerate
anything, by design.
Multiple dashboards on a page
Each needs its own token, because a token is pinned to one dashboard. Pass id to each
<Dashboard> and the provider requests one per id through the same fetchToken:
<BmapProvider baseUrl={url} fetchToken={getToken}>
<Dashboard id="revenue-dashboard" />
<Dashboard id="usage-dashboard" />
</BmapProvider>When the charts load
The charting engine is not in this package's bundle. It is imported dynamically the first time a widget renders, so an application that never opens its analytics never downloads it — the package itself is around 11 KB gzipped, and the charting chunk is roughly 290 KB on top.
Dashboard handles this for you: as soon as the dashboard definition arrives it fetches the
chunk for the chart types that dashboard actually uses, alongside the widget data rather than
after it. On most dashboards that covers the whole wait.
Call preloadCharts yourself when you know a dashboard is coming before you have asked for it
— on the route that will show one, or when a tab becomes active:
import { preloadCharts } from "@bmap-analytics/react";
useEffect(() => {
void preloadCharts();
}, []);Pass chart ids to register only what a page needs:
void preloadCharts(["bar", "line", "sankey"]);It is safe to call as often as you like, from anywhere: the work happens once and later calls resolve against the same promise. It never rejects — a preload that fails is not worth interrupting a page for, and the real load reports the failure when a chart is drawn.
API
| Export | |
|---|---|
| BmapProvider | Token lifecycle. Wrap your app or a subtree. |
| Dashboard | Full dashboard with layout. |
| WidgetTile, WidgetChart | A single tile, with or without chrome. |
| useDashboard, useWidget | Headless data access. |
| useDashboards, useWidgets | Listing, with viewerToken. |
| useDashboardFilters, FilterBar, useFilterValues, DATE_PRESETS | The filter bar, headless and ready-made. |
| Chart | Draws any chart in the catalogue, by id. |
| BarChart, LineChart, DonutChart, KpiTile, DataTable | Named wrappers over Chart, kept for integrations written before the catalogue. |
| useWidgetDownload, DownloadButton | Save a widget as an image, where the author allowed it. |
| preloadCharts | Fetch the charting chunk before the first chart needs it. |
| ChartTooltip, Legend, ChartDataTable, DEFAULT_THEME | The pieces a custom tile can reuse instead of reinventing. |
| useBmap | The raw client, for custom calls. |
CHARTS, chartById, chartsByFamily, explainMismatch and resolveChartType are
re-exported from @bmap-analytics/charts, so a custom renderWidget can ask the
same questions the built-in renderer does — which of the 52 charts a stored widget means, and
whether a result suits it. So are BmapError and the model types from
@bmap-analytics/core, so a consumer never adds a package just for a type.
ESM and CJS, TypeScript declarations, source maps, sideEffects: false.
React 17+ as a peer dependency; core, charts and echarts come with it.
