Skip to content

Charts ​

ApexCharts by default, Chart.js and ECharts as alternatives. All themed from tokens, all lazy, all with an accessible data fallback.


Basic usage ​

A chart is an empty element with two attributes: data-av-chart as the marker, and data-av-chart-options carrying one JSON object. There is no separate attribute per setting.

html
<div data-av-chart
     data-av-chart-options='{
       "type": "area", "height": 260, "moneyAxis": true,
       "categories": ["Mar","Apr","May","Jun","Jul","Aug"],
       "series": [{ "name": "Revenue", "data": [18200, 21400, 20100, 24800, 27300, 31200] }]
     }'
     role="img"
     aria-label="Area chart of monthly revenue rising from 18,200 euros in March to 31,200 in
                 August, with a dip to 20,100 in May."></div>

The vendor is lazy-loaded when the element scrolls into view, so a chart below the fold costs nothing until it is needed. A page with no [data-av-chart] never fetches ApexCharts at all, and tests/pages.mjs asserts both directions of that.

The chart type lives in the JSON. A chart does not fetch its own data. Rendering a server response is your application's job — build the options object and set the attribute, or call the vendor directly through the instance handed to you by av:chart:ready.

The options object ​

KeyDefaultEffect
type'area'Any ApexCharts type
height300Pixels
series[]Standard ApexCharts series
categories[]x-axis categories
labels(absent)Donut/pie labels — absent, never undefined; see below
colorsderivedLiteral colours, or semantic role names resolved against the preset
stackedfalse
horizontalfalseBar orientation
mixedfalseEach series carries its own type; the chart-level type becomes line
funnelfalseRenders as a tapered bar
sparklinefalseApex's own sparkline mode
moneyAxisfalseRuns the value axis through Intl, matching currency formatting elsewhere on the page
dataLabelsfalseOff by default: labels on every point make a chart unreadable. Turn them on for ≤ 8 points
legendderived

labels must be absent, not undefined. Apex reads .length off it while laying out a bar chart and throws. It is spread in conditionally for that reason, and the same trap applies to every optional formatter: formatter: undefined replaces Apex's internal default rather than falling through to it. Area and donut happen to tolerate the undefined, which is why this only surfaced when the first bar chart landed.

The only chart rule in the stylesheet is .av-chart-frame, which makes the SVG fill its box. Height is the height key in the options.


Theming ​

Charts read the live computed custom properties, so they match every preset — including one a customer adds — with no per-preset configuration. Re-theming is an updateOptions call rather than a re-render, subscribed once at module level:

js
if (!chartsThemeBound) {
  chartsThemeBound = true;
  AdminVora.on('av:theme:change', () => {
    const p = palette();
    instances.forEach((chart, el) => {
      const cfg = JSON.parse(el.dataset.avChartOptions || '{}');
      chart.updateOptions(buildOptions(cfg, p), false, false);
    });
  });
}

The flag is not defensive tidiness: a re-scan after a client-side navigation would otherwise stack a second subscriber and re-render every chart twice on the next theme change.

Every token is OKLCH, and ApexCharts cannot read one ​

This is the finding worth carrying to any future vendor. A library that does colour maths rather than handing a string to SVG fill usually parses with a hex regex, and silently fails on oklch(). ApexCharts does. The fix is to convert at the vendor boundary:

js
hexCtx.fillStyle = '#000000';     // sentinel
hexCtx.fillStyle = value;         // the browser parses oklch() per CSS Color 4
return hexCtx.fillStyle;          // …and hands back a hex string

Painting to a 1×1 canvas and reading fillStyle back round-trips the colour through the browser's own parser, which is the only implementation guaranteed to agree with what the page renders.

Do not port the token generator instead. Its OKLCH maths clamps out-of-gamut values rather than gamut-mapping them, so it can and does disagree with the browser — tests/contrast.mjs measures from getComputedStyle for the same reason.

Two details in that conversion that are easy to leave out:

  • An unparseable colour silently becomes black on a canvas. Setting a sentinel first and checking the getter actually changed is what tells you the value was understood, rather than painting a series black and calling it a theme.
  • transparent and #… pass straight through, and a waterfall needs an invisible base.

colors may name a semantic role rather than a literal, so a deliberately coloured chart still follows the preset and the colour mode.

Charts hold three pieces of module state ​

Worth knowing before touching this module, because two of them exist to fix bugs that are invisible until they are not:

  1. An instances Map, so a re-scan finds the chart it already made instead of building a second.
  2. A one-subscriber flag, above.
  3. A MutationObserver that destroys a chart the moment its element leaves the DOM. An orphaned Apex resize observer writes NaN into SVG geometry, which the browser reports as a console error per attribute. The observer is bound only once a chart exists — a page without one should not pay for a document-wide observer — and mount() re-checks el.isConnected after awaiting the lazy import, because a router can remove the element while the vendor is still downloading.

Accessibility ​

Charts are the least accessible thing in most admin panels. AdminVora enforces three mitigations.

1. Accessible name and role ​

js
el.setAttribute('role', 'img');
el.setAttribute('aria-label', options.title || 'Chart');

2. A data table equivalent ​

The runtime does not generate one: a <div data-av-chart> holds only the SVG.

The obligation is real even though the machinery is not, so build it in your own markup: put the same numbers in a <table> beside the chart, with a <caption>. A screen-reader user is not the only beneficiary — anyone who wants the exact figure rather than a shape reads it too.

The runtime does provide one seam for this, though it is only half built: data-av-chart-fallback on an ancestor of the chart element is removed once the chart renders. The intent is a server-rendered table that disappears when the SVG arrives — but no stylesheet rule reads the attribute, so nothing is hidden today. If you want that behaviour, add the rule; the runtime half already works.

3. Never colour alone ​

Past five series the runtime adds alternating dash patterns automatically. Marker shapes are not added; set them on the instance from av:chart:ready if you need them.

The rule still stands and is the reason to bother: a reader with deuteranopia loses roughly the distinction the palette is relying on. Pass explicit colors and shapes when a chart carries more than about five series, or split it.


Responsive ​

responsive is not one of the keys the module builds, so pass it through as part of your own options and Apex will honour it — the object is handed to new ApexCharts() after the module's defaults are merged in.

There is no ResizeObserver. ApexCharts listens to window resize only, which misses a sidebar collapse, a drawer opening and a layout switch. A chart in a container that changes width without the window changing will not re-lay-out until the next window resize.

That is a real gap with a known shape. If you add one, note what the module already learned: the observer must be torn down with the chart, and mount() re-checks el.isConnected after the lazy import because a router can remove the element mid-download.


Options and events ​

The options are the fourteen keys in the table above. There is no separate attribute per option and no configuration object.

EventDetail
av:chart:ready{ el, chart } — fired after render() resolves

Teardown happens through AdminVora.destroy(root), which calls the vendor's destroy() and releases the data-av-init claim — and, for charts specifically, through the MutationObserver described above.


Chart selection guide ​

QuestionChart
How has this changed over time?Line, area
How do these categories compare?Bar (labels are long), column (labels are short)
What is the composition?Stacked bar, or a progress list — pies are hard to read
Composition with ≤ 5 parts?Donut
Progress toward a target?Radial, gauge
Where does the density lie across two dimensions?Heatmap
Where do users drop off?Funnel
How do items compare across several attributes?Radar (≤ 6 axes)
Just a trend, inline?Sparkline

Note — a progress list beats a pie chart in almost every case: exact values are readable, it works at any width, and it needs no data-table fallback.


Checklist ​

  • [ ] role="img" and aria-label on the container
  • [ ] A data table equivalent exists (visually hidden or toggleable)
  • [ ] More than 5 series → dash patterns and marker shapes added
  • [ ] Charts re-theme on av:theme:change
  • [ ] Colours read from --av-chart-* custom properties, never hard-coded
  • [ ] ResizeObserver handles container resize, not only window resize
  • [ ] Animations disabled under prefers-reduced-motion
  • [ ] Real-time feeds are throttled
  • [ ] chart.destroy() called on unmount
  • [ ] y-axis uses opposite: true in RTL

Read next: Data Grids.

Documentation for @creativeigniter/adminvora