JavaScript API¶
The reference of what scripts can call: window.dashboard in a dashboard, <source-api> in a page of your own, embedDashboard in a Host. The tags and their attributes are in Components.
How the pieces fit¶
BI Components are decoupled from the way queries are executed. A component only knows one thing: window.dashboard. A connector installs it, and each setup has its own.
<score-card> <bar-chart> <line-chart> <data-table> <ui-filter> custom scripts
\ | | | | /
+-------------------- window.dashboard ---------------------+
| | |
1 · Static page 2 · Your backend 3 · Sandbox
duckdb-wasm.js http-api.js iframe-bridge.js, in the frame
DuckDB-WASM in the fetch: one POST per postMessage to the Host
browser batch of queries (host-bridge.js, in your page)
npm run build makes two files from src/:
| File | Where it runs | Connector it installs |
|---|---|---|
bi-components.js |
In your page, with <source-table> or <source-view> |
duckdb-wasm.js |
In your page, with <source-api url="..."> |
http-api.js |
|
In a frame of embedDashboard, which marks its document with <meta name="bi-components" content="embedded"> |
iframe-bridge.js |
|
bi-components-host.js |
In your page, the Host of sandboxed frames | host-bridge.js: the other end of iframe-bridge.js |
In a page, <source-api> installs http-api.js and <source-table> DuckDB-WASM, each time one is added: a site that changes pages without reloading them gets the right connector on every page.
window.dashboard¶
The same members in every setup. See Custom charts and scripts for how to use them.
| Member | Description |
|---|---|
query(specOrName, { timeoutMs = 30000 }) |
Returns Promise<{ rows, meta }>. Takes a query object, or the name (string) of a named query: a <source-view> of a static page, or a query your server or Host defines ('region_profile' is short for { mode: 'named', name: 'region_profile' }). When filters / date_range are omitted, the current selection is used. |
filters.get(dimension) / filters.getAll() |
Current selection: string, string[] or undefined. |
filters.set(dimension, value) |
Sets a filter, or removes it with null. |
filters.toggle(dimension, value, { multi }) |
What a click does. Simple click: select / unselect the value. multi: true (Ctrl / Cmd + click): add / remove the value of a multi-selection. |
filters.clear() |
Removes every dimension filter. |
filters.getDateRange() / filters.setDateRange([start, end] \| null) |
The period ("YYYY-MM-DD" strings), kept apart from dimension filters. |
filters.getOptions() / filters.setOption(key, value) |
Options of the page (period_comparison_method, date_granularity, or any key of your own). |
variables |
Read-only values given by the Host, such as locale. |
theme |
{ mode: "light" \| "dark", palette: string[] }. |
subscribe(callback) |
callback({ type }) is called on every change: filters, dateRange, options, variables, theme, sourcesReady. Returns unsubscribe(). |
sync({ theme, variables, filters, dateRange, options }) |
Pushes a state from outside: how a page of your own switches to dark mode, and what a Host's setState does in a frame. |
registerSource(config) |
Static page only. Used by <source-table> / <source-view>: { name, url \| data \| sql, columns, dateColumn }. |
sql(query) |
Static page only. Runs raw SQL on the local database and returns the rows. |
refresh() |
With <source-api> only. Every component asks again. |
ready() |
Called automatically when every component has rendered once: a Host gets onReady, a page of your own the dashboard-rendered event on document. |
The page dispatches dashboard-ready on document each time a connector installs window.dashboard.
The query¶
What a component sends, and what query() takes. The presence of the table attribute decides its mode.
Named measures: no table¶
<bar-chart measure="revenue" by="region" compare="yoy">
| HTML attribute | Query field |
|---|---|
mode: "semantic" |
|
measure (charts, score cards) / measures (<data-table> only) |
metrics: string[] |
by + breakdown-by |
dimensions: string[] \| null |
attributes="store_name,city" |
attributes: string[] \| null |
granularity="day\|week\|month\|quarter\|year" |
date_granularity |
compare="yoy\|mom\|prev_period" |
period_comparison_method |
sort-by (or order_by), sort-asc, limit |
sort_by, sort_ascending, limit |
param-* |
params |
| the filters of the page, minus the component's own dimension | filters |
| the period of the page | date_range |
granularity and compare written without a value follow the option of the same meaning (date_granularity, period_comparison_method), so a <ui-filter option="date_granularity"> can drive them.
What your code answers, field by field: Answer the queries.
SQL expressions: table="..."¶
<bar-chart table="stocks" measure="avg(stock_value)" by="company" breakdown-by="sector" sort-by="avg(stock_value) desc" limit="20">
{
"mode": "table",
"table": "stocks",
"metrics": ["avg(stock_value)"],
"dimensions": ["company"],
"breakdown": "sector",
"breakdown_limit": 6,
"attributes": [],
"filters": { "country": ["US", "FR"] },
"date_range": ["2026-01-01", "2026-11-30"],
"sort_by": "avg(stock_value)",
"sort_ascending": false,
"limit": 20
}
Measures and dimensions are SQL expressions; a trailing alias (measures="sum(ca) as ca") is used as the displayed name. The SQL itself is only written by the connector (sql_compiler.js): WHERE (with IN (...) for multi-selections and the period when the table has a date-column), GROUP BY, ORDER BY, LIMIT. Result rows are keyed by the exact strings of the query (row["avg(stock_value)"]).
Optional fields: where (a condition, refused from a sandboxed frame), date_column, normalized (shares of the total instead of values).
params¶
param-* attributes travel as they are, in both modes:
<score-card measure="revenue" param-scope="like_for_like" param-with-tax>
{ "mode": "semantic", "metrics": ["revenue"], "params": { "scope": "like_for_like", "with_tax": true } }
The library carries params without interpreting them (they also keep two score cards apart when batching). A Host drops them unless it validates them, with sanitizeParams.
meta¶
Optional help for the display, in the answer { rows, meta }:
time_col: name of the time column of a time series (<line-chart measure="revenue" granularity="month">has noby).formats:{ column: "eur" | "pct" | "int" | "dec" }, used by axes, tooltips, score cards and tables. An explicitformat/formats="revenue:eur"attribute wins.comparisons:{ metric: column holding the comparison value }. Score cards show a colored variation badge, line and bar charts draw the comparison period.labels:{ column: display name }.
In a static page, meta.sql holds the SQL that was run.
<source-api>¶
Sends the queries of a page to your server: the backend setup.
POST <url> { ...body, "queries": { "q1": query, "q2": query } }
-> { "answers": { "q1": { "rows": [...], "meta": {...} }, "q2": { "error": "Unknown metrics: margin" } } }
url attribute |
Where the queries go, relative to the page. |
body attribute |
A JSON object added to every request: body='{"profile": "global_hq"}'. |
credentials attribute |
same-origin by default: a request to the same site carries its cookies. include for an API on another site, which must then allow it with CORS. |
body and headers properties |
An object, or a function of the dashboard called for each request: api.headers = () => ({ authorization: `Bearer ${getToken()}` }). A body property replaces the attribute. |
dashboard property |
The dashboard it installed. |
refresh() |
Every component asks again. Changing an attribute or a property does it too. |
- The queries a render asks within 10 ms leave together, as one request. A batch of more than 100 queries is split.
- An error of one query goes to the component that asked; a refused request (HTTP 4xx / 5xx) to every query it held, with the
detailorerrorof its body. - A new query of a component replaces its previous one, whose answer is ignored. A query times out after 30 s.
- Each
<source-api>added to the page installs a newwindow.dashboard, with a fresh selection; the components move to it, wherever the element is in the page.
embedDashboard¶
Shows a dashboard written by someone else in a sandboxed frame, and answers its queries: the sandbox setup.
import { embedDashboard, restrictFilters, validateTableSpec } from 'https://unytics.io/bi-components/dist/bi-components-host.js';
const dashboard = embedDashboard(container, options);
container is the element the iframe goes in; the iframe takes its width and height.
Options¶
| Option | |
|---|---|
resolveQuery(query) |
Required. Gets every query once validated, and answers it: { rows, meta }, or a promise of it. query.mode is 'semantic', 'table' or 'named'. Throw for what you do not accept: the message is shown in the component that asked. |
html |
The dashboard: a string of HTML. Without it, nothing is shown until load(html). |
state |
{ filters, dateRange, options, variables, theme } at start. |
components |
The address of bi-components.js, which each frame loads. By default the file next to bi-components-host.js. |
resources |
A list of addresses, stylesheets (.css) and classic scripts (.js), every dashboard gets, in this order, before the components. Anything else is refused. |
css |
Your own rules, placed after the stylesheets. |
theme |
'light' or 'dark' at start. |
lang |
The language of the document ('en'). |
title |
The title of the iframe, read by screen readers ('Dashboard'). |
sanitizeParams(params) |
Returns the params you accept, or throws. Without it, params are dropped. |
valuesMetric |
The metric to add to a query that asks for the values of a dimension (from <ui-filter>), for engines that need one. |
timeColumn |
The name of the time column of your time series ('date'), which a query may sort on. |
comparisons |
The comparison methods you accept (['yoy', 'mom', 'prev_period']). |
maxLimit |
The highest limit a query may ask (10000). |
maxPendingQueries |
Queries running at the same time (200); the others are refused. |
onReady() |
The first render of the dashboard is done. |
onStateChange(state) |
The viewer changed a filter, the period or an option. |
onRuntimeError({ message, line, stack }) |
A script of the dashboard failed. Text written by the dashboard: see the security model. |
onLog({ direction, message }) |
Every message between the frame and the Host, for debugging. |
An unknown option is refused, with the list of those that exist.
The handle¶
setState(partial) |
Pushes theme, filters, period, options or variables to the running dashboard. Nothing is reloaded. |
load(html, state) |
Shows another dashboard. Filters, period and options go back to those given at start; theme and variables are kept, or replaced by state. Answers to the previous dashboard never reach the new one. |
configure(rules) |
Changes a rule for the next queries, for instance { maxLimit: 500 } or another resolveQuery. |
state |
The current state, including what the viewer selected. |
iframe |
The element it created. |
destroy() |
Removes the iframe and stops listening. |
restrictFilters(filters, allowed)¶
Row-level security for resolveQuery: intersects what the frame asked with what the viewer may see, instead of overwriting it.
resolveQuery: (query) => callYourEngine({ ...query, filters: restrictFilters(query.filters, { store_code: ['M001', 'M002', 'M003'] }) })
- no filter asked on the dimension: the viewer's three stores;
- a click on
M001:M001only, so cross-filtering keeps working on restricted dimensions; - only values outside the viewer's scope (
M999): the query is refused with an access error; - a viewer whose allowed list is empty: refused as well. An empty list never means "no restriction".
validateTableSpec(query, tables)¶
For queries with SQL expressions: throws unless the table and every column of every expression are in tables.
validateTableSpec(query, { sales: ['date', 'country', 'revenue'] });
Messages between a frame and its Host¶
A sandboxed frame has no network. iframe-bridge.js implements window.dashboard with serialized postMessage messages only:
| Message | Direction | Payload |
|---|---|---|
BRIDGE_READY |
frame → Host | the bridge is installed, waiting for the state |
STATE_SYNC |
Host → frame | { payload: { filters, dateRange, options, variables, theme } } |
QUERY_REQ |
frame → Host | { reqId, spec } |
QUERY_RES |
Host → frame | { reqId, rows, meta } or { reqId, error } |
FILTER_SET |
frame → Host | { filters, dateRange, options } after a user interaction |
DASHBOARD_READY |
frame → Host | initial render done |
RUNTIME_ERROR |
frame → Host | { message, line, stack } from window.onerror / unhandled rejections |
- Batching: queries for named measures without dimensions (score cards) that are identical apart from their metrics, issued within 4 ms, travel as one
QUERY_REQwith all their metrics. Each caller gets back its own metric. - Timeouts and replacement: a request times out after 30 s by default; a new query of a component replaces its previous one, whose late answer is ignored.
- No flicker: theme or filter changes are pushed with
STATE_SYNC; the frame is never reloaded.
What the Host checks in each message, and how the document of the frame is written: Security model.
Another engine: your own connector¶
A connector is a small script that installs window.dashboard with a function able to answer a query. For something else than DuckDB-WASM, an HTTP API with this protocol or a Host (a warehouse proxy, a WebSocket, another protocol):
import { createDashboard, installDashboard } from 'https://unytics.io/bi-components/src/dashboard.js';
const { dashboard } = createDashboard({
query: async (spec, { timeoutMs }) => ({ rows: await askMyEngine(spec), meta: {} }),
});
installDashboard(dashboard);
createDashboard provides everything else: the filters, the period, the options, the theme and the subscriptions. The three existing connectors are the examples to read. Load your connector with the modules of the components you use, instead of bi-components.js, which would install its own:
<script type="module" src="my-connector.js"></script>
<script type="module" src="https://unytics.io/bi-components/src/components/echarts.js"></script>
<script type="module" src="https://unytics.io/bi-components/src/components/score_cards.js"></script>