blockcharts alpha

Embedding /

As an ES module

The same kits come as ES modules. Import BC, give it data, and draw into any element. This is the way into a bundler or a framework component.

import BC from a kit

The default export is the runtime, BC. BC.data adds a dataset by name; BC.chart(element, spec) draws and returns a handle. (Browsers load modules only over http or https, so open this page from a server, not from a file.)

HTML

<div id="chart"></div>

<script type="module">
  import BC from '/release/kits/basic.mjs';

  BC.data('sales', [{"region":"North","total":42000},{"region":"South","total":58000},{"region":"East","total":31000},{"region":"West","total":66000}]);
  const chart = BC.chart(document.getElementById('chart'), {
    "data": "sales",
    "size": [720, 280],
    "scales": { "x": { "type": "band" }, "y": { "type": "linear", "zero": true } },
    "guides": [
      { "type": "grid", "scale": "y" },
      { "type": "axis", "scale": "x" },
      {
        "type": "axis",
        "scale": "y",
        "format": { "style": "currency", "currency": "USD", "maximumFractionDigits": 0 }
      }
    ],
    "marks": [
      { "type": "rect", "x": "region", "y": "total", "radius": 3 },
      {
        "type": "text",
        "x": "region",
        "y": "total",
        "text": "total",
        "format": "compact",
        "baseline": "auto",
        "dy": -5
      }
    ],
    "interaction": [
      {
        "type": "tooltip",
        "formats": {
          "total": { "style": "currency", "currency": "USD", "maximumFractionDigits": 0 }
        }
      }
    ]
  });
  console.log(chart.diagnostics); // [] when the spec is fine
</script>

In a component

A component draws in its mount hook and cleans up in its unmount hook. destroy() removes the listeners and the elements the chart made; update(spec) redraws with a new spec and keeps the zoom. For React, Vue, Svelte and Angular that component is written already: the wrappers.

JavaScript

import BC from 'blockcharts/kits/basic.mjs';

export function mountChart(element, rows, spec) {
  BC.data('rows', rows);            // last call for a name wins
  const chart = BC.chart(element, { ...spec, data: 'rows' });
  return {
    update: (next) => chart.update({ ...next, data: 'rows' }),
    destroy: () => chart.destroy(),
  };
}