@circutor/charts-react
v0.11.0
Published
React wrappers for the @circutor/charts Web Components
Maintainers
Keywords
Readme
@circutor/charts-react
React components for the charts used by the Circutor Cloud team. They wrap the Web Components from @circutor/charts, so you get typed props and React-friendly usage.
Not using React?
@circutor/chartshas the same charts as Web Components, for plain HTML, a CDN or any other framework. See its readme instead of this one.
Install
npm install @circutor/charts-react echartsecharts6 is a peer dependency of@circutor/charts: the charts use your application's copy, so it isn't bundled twice when your app also uses ECharts.reactandreact-dom18 or 19 must be installed in your application.@circutor/chartsis installed automatically.
Each component imports only its own Web Component, so your bundler only includes the charts you import.
Design system (CDS)
The charts are made to look like the rest of Scout with the Croma Design System (CDS): @circutor/ui 7, brand circutor. Your app loads CDS; the charts don't include its CSS or fonts. @circutor/ui (^7) is an optional peer dependency:
npm install @circutor/uiLoad it once in your app, with Sass:
@use '@circutor/ui/bundle' with ($brand: 'circutor');or as CSS, e.g. in main.tsx:
import '@circutor/ui/css/cds-circutor-bundle.css';What the charts take from the page:
- Font. The page's font, CDS's or yours. HTML parts (the comparison chart, and the cards and legend of the consumption overview chart) inherit it as any text. ECharts parts (the ITIC chart, the cos φ chart, and the pie and bars of the consumption overview chart) are drawn on a canvas, which doesn't read CSS, so the font is read from the page each time the chart is drawn, and its faces are loaded before it draws. Bold texts (the axis names, the title of the cos φ chart) use CDS's bold family when the page has it, or a bold weight of the page's font. If a face of the font finishes loading after the chart is drawn, the chart redraws. Tooltips are part of the page (
body), so they use the page's font as any HTML. - Colors. Charts can follow CDS's color tokens (
--cds-color-*); each color also has a fixed fallback. The colors of the comparison and consumption overview charts follow them (except their palettes, which are Scout's), and so do the text and the grid of the cos φ chart; its bars and lines have their own colors. The ITIC chart's colors (curve regions and phases) are its own and don't change with CDS. - Icons. The trends of the comparison and consumption overview charts are CDS's icons (
trend-up,trend-down,minus), drawn by the chart as SVG: their shapes are taken from@circutor/uiwhen the library is built, so they show without CDS in the page and whatever CDS version it loads. The gas and water icons of the consumption overview chart are part of it too.
Without CDS, the charts look as before: they use the page's font, or Arial when the page doesn't set one, and their own colors. Nothing is left blank or broken: the icons are part of the charts.
ECharts parts read the page's styles when they draw: a change in the page's CSS (another font or brand) shows the next time the chart redraws (e.g. new data, locale or timeZone), not as soon as it happens. HTML parts follow the page's CSS at once.
ITIC chart
Voltage events (dips, swells, interruptions…) on the ITIC curve: duration against voltage, by phase.
The chart only takes data, plus the language and time zone. It decides what is shown and how: the tooltip, the translations, the axis names, the accessible name, and each phase's name, color and order.
import { IticChart } from '@circutor/charts-react';
const groups = [
{
phase: 'AN,BN,CN',
assetName: 'Cuadro general',
points: [{ duration: 230, voltage: 93.46, ts: '2024-06-26T20:23:45.220000+02:00', eventType: 'VOLTAGE_DIP' }],
},
{
phase: 'BN',
assetName: 'Cuadro general',
points: [{ duration: 20, voltage: 0.4, ts: '2025-01-26T23:04:34.840000+01:00', eventType: 'POWER_INTERRUPT', clickable: false }],
},
];
export function PowerQuality() {
return (
<IticChart
groups={groups}
locale="es"
timeZone="Europe/Madrid"
onPointClick={({ detail }) => console.log(detail.point, detail.group)}
/>
);
}| Prop | Type | Default | Description |
|---|---|---|---|
| groups | ITICChartMarks[] | – | Point groups (see Data). |
| locale | string | 'en' | Language of the texts, event types, axes, aria-label, translated phases, dates and numbers. Only the language is used (es-ES → es); anything other than ca, de, en, es, fr or pt falls back to en. |
| timeZone | string (IANA) | The browser's | Time zone of the dates in the tooltip, e.g. Europe/Madrid. An invalid value uses the browser's and logs a console.error. |
| mode | 'interactive' \| 'print' | 'interactive' | print: for PDFs, as SVG and without tooltip, onPointClick or legend toggle (see Print mode). |
| onPointClick | (event: CustomEvent<ITICPointClickDetail>) => void | – | A clickable point was clicked. event.detail holds the point and group objects you passed in groups. Never in print mode. |
| onReady | (event: CustomEvent<{ width, height }>) => void | – | The chart has finished painting, fonts included (see Print mode and data-ready). |
| aria-label | string | Translated "ITIC chart" | Accessible name. The element has role="img", since the chart is a canvas. The default follows locale; a value you set is left alone. |
The ITICChartMarks, ITICPoint and ITICPointClickDetail types are exported by this package.
The background is transparent; set it with the --itic-chart-background CSS custom property, e.g. itic-chart { --itic-chart-background: #fafafb; }.
Data
| Group field | Type | Description |
|---|---|---|
| phase | string | Phase code (AN, AB,BC,CA, ALL, NONE…). Sets the group's name, color and order (see Phases). |
| assetName | string, optional | Asset name, shown in the tooltip. |
| points | ITICPoint[] | The voltage events. |
| Point field | Type | Description |
|---|---|---|
| duration | number | Duration, in ms. |
| voltage | number | Voltage, in % of the nominal voltage. |
| ts | string | Date of the event, ISO 8601. |
| clickable | boolean, optional | false hides the pointer cursor and emits no onPointClick. Defaults to true. |
| eventType | string, optional | Event type code from the backend (see Event types), translated in the tooltip. |
| status | string, optional | Status code from the backend, shown as is. |
| min / max | number, optional | Minimum and maximum voltage, in V. |
The axes have fixed ranges: duration from 1 to 100,000 ms (logarithmic) and voltage from 0 to 200%. Points outside them aren't drawn (e.g. a duration below 1 ms or a voltage above 200%).
Tooltip
The tooltip shows these rows, in this order, in the chart's locale. Rows without a value are left out, and every value is escaped, so data can't inject HTML.
| Row (en) | Value | Left out when |
|---|---|---|
| Asset | assetName | missing or empty |
| Date | ts with milliseconds, in timeZone (e.g. Jun 26, 20:23:45.220, 26 jun, 20:23:45,220) | never; an invalid date is shown as is |
| Event | translated eventType; unknown codes as is | missing or empty |
| Duration | e.g. 1,500 ms (1500 ms in es) | never |
| Voltage | rounded to 1 decimal, e.g. 93.5% (93,5 % in es) | never |
| Status | status as is | missing or empty |
| Phase | phase name; - for NONE | never |
| Min / Max | 2 decimals, e.g. 207.12 V | missing or 0 |
Numbers use the separators of each language, also in the axis labels: in es the duration axis reads 1000, 10.000, 100.000 (Spanish doesn't group 4-digit numbers).
The tooltip is added to document.body, not inside the chart, so containers with overflow: hidden don't clip it.
Phases
| Code | Name | Color |
|---|---|---|
| AN, AB | L1 | #a67c52 |
| BN, BC | L2 | #20262C |
| CN, CA | L3 | #B9BDC0 |
| AN,BN,CN, AB,BC,CA | L1,L2,L3 | #00B388 |
| ALL | Translated: All, Todas, Totes, Alle, Toutes | #4C5CC5 |
| A, B, C | L1, L2, L3 | ECharts palette |
| AN,BN, AN,CN, BN,CN, AB,BC, AB,CA, BC,CA | L1,L2 · L1,L3 · L2,L3 | ECharts palette |
| NONE | No name | ECharts palette |
| Any other | The code as is | ECharts palette |
- Groups are sorted by name (
L1,L1,L2,L3,L2,L3), then by code, whatever order they come in, withNONEand thenALLlast. Groups with the same code keep their order. - Phase-neutral and phase-phase codes share names and colors:
ANandABin the same chart are two "L1" groups you can't tell apart, and one legend item toggles both. NONEgroups have no name, so they don't appear in the legend (their points are drawn) and their tooltip shows-as phase.- Phases without a fixed color take the next one of the ECharts palette, so the same code may get different colors in different charts.
Event types
eventType codes with a translation (in ca, de, en, es, fr and pt). Any other code is shown as is.
| Code | en | es |
|---|---|---|
| VOLTAGE_DIP | Voltage dip | Hueco de tensión |
| VOLTAGE_SWELL | Voltage swell | Aumento de tensión |
| POWER_INTERRUPT | Power interruption | Interrupción |
| VOLTAGE_TRANSIENT | Voltage transient | Transitorio de voltaje |
| VOLTAGE_VARIATION | Voltage variation | Variación de voltaje |
| OVER_VOLTAGE | Overvoltage | Sobretensión |
| SUB_VOLTAGE | Subvoltage | Subtensión |
Clickable points
Every point is clickable by default: it shows a pointer cursor and emits onPointClick. Set clickable: false on a point to turn both off, e.g. for events without waveforms.
Your own data in points and groups
Points and groups accept any extra field (e.g. waveforms). The chart doesn't read or validate them; it passes them back in onPointClick. Cast them to your own types there:
import { IticChart, type ITICChartMarks, type ITICPoint } from '@circutor/charts-react';
// Use `extends` (or `&`) so your types are assignable to the chart's
interface EventPoint extends ITICPoint {
waveforms: Waveform[];
}
interface AssetGroup extends ITICChartMarks {
points: EventPoint[];
}
<IticChart
groups={groups}
locale={locale}
timeZone={timeZone}
onPointClick={({ detail }) => openWaveforms(detail.point as EventPoint, detail.group as AssetGroup)}
/>;Size and data updates
- The chart takes the full width of its container, also as an item of a flex row, and is
400pxhigh by default. Any CSS rule onitic-chartwins over that default, e.g.itic-chart { height: 300px; }, or, to grow with a flex container:
The chart redraws automatically whenever its size changes..card { display: flex; flex-direction: column; } .card itic-chart { flex: 1; min-height: 400px; } - Passing a new
groupsarray,locale,timeZoneormoderedraws the chart; groups that are no longer present are removed.
Print mode
With mode="print" (see Print mode and data-ready) the chart is SVG, has no tooltip or pointer cursor and doesn't call onPointClick; its legend is shown, but clicking it doesn't hide a phase. It doesn't animate in either mode. The whole chart avoids being split between pages.
Invalid groups (invalid JSON, or not an array) log a console.error and draw the curve without points; data-ready is set at once.
Comparison chart
Compares a value of several items in a period, e.g. the normalized consumption (kWh/m²) of several buildings. Each row has a bar, a color dot, the name, the value with its unit, and the trend from the previous period (icon and percentage). The chart is HTML and CSS, not a canvas: its texts are real text, it takes the page's font and CDS's icons, and it doesn't use ECharts.
import { ComparisonChart, type ComparisonChartItem } from '@circutor/charts-react';
const items: ComparisonChartItem[] = [
{ name: 'Sagrada Familia', value: 77.75, trend: 34.8 },
{ name: 'Central Office', value: 48.12, trend: -1.8 },
{ name: 'Danonino', value: 34.5, trend: -1.8 },
{ name: 'Empire State', value: null },
];
export function Consumption() {
return <ComparisonChart items={items} unit="kWh/m²" locale="es" aria-label="Consumo normalizado por edificio" />;
}| Prop | Type | Default | Description |
|---|---|---|---|
| items | ComparisonChartItem[] | – | Rows, in any order: the chart sorts them with sort. |
| sort | 'value' \| 'trend' | 'value' | Field the rows are sorted by, from largest to smallest: value or trend. Any other value sorts by value. |
| unit | string | '' | Unit of the values, the same for every row (e.g. kWh/m²). Shown as is. |
| max | number | The largest value | Value that fills the bar. |
| locale | string | 'en' | Language of the texts and numbers. Only the language is used (es-ES → es); anything other than ca, de, en, es, fr or pt falls back to en. |
| mode | 'interactive' \| 'print' | 'interactive' | print: for PDFs. It looks the same (see Print mode below). |
| onReady | (event: CustomEvent<{ width, height }>) => void | – | The chart is rendered and the fonts of the page have loaded (see Print mode and data-ready). |
| aria-label | string | – | Accessible name of the list. The element has role="group" and no label of its own. |
| Item field | Type | Description |
|---|---|---|
| name | string | Name of the row (e.g. the building). Rows without it are left out, with a console.error. |
| value | number \| null, optional | Value of the period. null or missing: the row shows "No data". |
| trend | number \| null, optional | Change from the previous period, in % (34.8 → +34.8%). null or missing: not shown. |
| color | string, optional | Color of the dot and the bar (any CSS color). Without it, the default palette's. |
Items accept any extra field (e.g. id); the chart keeps them as they are. ComparisonChartItem is exported by both packages.
Order: from the largest to the smallest
value(sort="value", the default) ortrend(sort="trend"). Rows without it go last (withtrend, also rows without value, which show no trend), and ties keep their order initems.Bar:
valueover the scale (max, or the largest value of the list), from empty to full. Values of0or below leave it empty, and values abovemaxfill it. With a scale of0(every value is0) or amaxof0or below, every bar is empty.Value: at most 2 decimals, with the separators of the language (
77.75,77,75ines), thenunit.Trend: always 1 decimal, signed, in the language's format (
+34.8%,+34,8 %ines), then "vs last period", translated. Lower is better, so going up is shown as worse:|
trend| Icon | Color | |---|---|---| | Above 0 |trend-up|--comparison-chart-worse-color(amber) | | Below 0 |trend-down|--comparison-chart-better-color(green) | |0, or shown as0.0%(e.g.-0.04) |minus|--comparison-chart-neutral-color(grey) |The icon is CDS's, drawn by the chart, so it also shows without CDS in the page.
No data: a row without
valueshows its dot, its name and "No data", translated, with an empty bar, and neither unit nor trend. Without rows (noitems,[]or invalid JSON), the chart shows "No data", centred.Colors: rows without
colortake the default palette by their position initems, also rows without data, so an item keeps its color when it has no data or the order changes. They are the asset colors of Scout's web app, not CDS tokens. After 10 rows, the palette starts again:| Row | Color | Default | |---|---|---| | 1, 11… |
--comparison-chart-color-1|#2A90BC| | 2, 12… |--comparison-chart-color-2|#92B757| | 3, 13… |--comparison-chart-color-3|#1CAF80| | 4, 14… |--comparison-chart-color-4|#FCB154| | 5, 15… |--comparison-chart-color-5|#DD6A37| | 6, 16… |--comparison-chart-color-6|#C70D3B| | 7, 17… |--comparison-chart-color-7|#832A6D| | 8, 18… |--comparison-chart-color-8|#9B59B6| | 9, 19… |--comparison-chart-color-9|#E64C65| | 10, 20… |--comparison-chart-color-10|#2B5D8C|
| CSS custom property | Default | Description |
|---|---|---|
| --comparison-chart-background | transparent | Background of the component. |
| --comparison-chart-track-color | --cds-color-surface-200 (#E4E4E4) | Empty part of the bars. |
| --comparison-chart-text-color | --cds-color-surface-950 (#191a1b) | Names. |
| --comparison-chart-secondary-text-color | --cds-color-surface-600 (#5D5D5E) | Values, units and "No data". |
| --comparison-chart-worse-color | --cds-color-amber-500 (#E08C00) | Upward trend (worse). |
| --comparison-chart-better-color | --cds-color-emerald-500 (#10B981) | Downward trend (better). |
| --comparison-chart-neutral-color | --cds-color-surface-500 (#8A8A8B) | Trend of 0. |
| --comparison-chart-color-1 … -10 | See the palette above | Default colors of the rows. |
Size. The chart takes the width of its container, also as an item of a flex row, and is as high as its rows, without scrolling. In a narrow container, what doesn't fit in a row's line goes to the next one; no text is cut, and long names take several lines.
Updates. Changing items, sort, unit, max, locale or mode updates the chart. It has no tooltip, and its only event is onReady.
Print mode. The chart has nothing interactive, so with mode="print" (see Print mode and data-ready) it looks the same. The whole chart avoids being split between pages. data-ready is set once the chart is rendered and the fonts of the page have loaded; with items it can't read (invalid JSON, not an array, or no row with a name), at once. An empty list isn't invalid: it shows "No data" and waits for the fonts.
Accessibility. The rows are a list, and each row reads in order, e.g. "Sagrada Familia, 77.75 kWh/m², +34.8% vs last period". The bars and icons are hidden from assistive technologies: the text says it all. The element gets role="group" (unless you set another role) and no aria-label of its own; set one to name the list, as in the example.
Consumption overview chart
The consumption of an asset in a period: a card with the total and its change from the previous period, one card per normalized consumption, the contribution of each child (a pie and its legend) and the bars of each day or month. The cards and the legend are HTML and CSS (real text, the page's font and CDS's icons); the pie and the bars are ECharts.
Pass the data as the API returns it, plus the language and time zone. The chart does the rest: scale and units, ranking, "Others", texts and translations, colors and icons. It has a print mode for PDF reports, and a data-ready attribute that says when it has finished painting.
import { ConsumptionOverviewChart, type ConsumptionOverviewData } from '@circutor/charts-react';
export function Consumption({ data }: { data: ConsumptionOverviewData }) {
// `data` as the API returns it
return <ConsumptionOverviewChart data={data} locale="es" timeZone="Europe/Madrid" onReady={({ detail }) => console.log(detail.height)} />;
}| Prop | Type | Default | Description |
|---|---|---|---|
| data | ConsumptionOverviewData | – | The data (see Consumption data). |
| locale | string | 'en' | Language of the texts, dates and numbers. Only the language is used (es-ES → es); anything other than ca, de, en, es, fr or pt falls back to en. |
| timeZone | string (IANA) | The browser's | Time zone of the days of the data, e.g. Europe/Madrid (see Dates and time zone). An invalid value uses the browser's and logs a console.error. |
| heading | string | The commodity's | Title of the total card, instead of "Total Energy Consumption", "Gas consumption" or "Water consumption". |
| stacked | boolean | false | Stacks the bars of each day instead of putting them side by side. |
| mode | 'interactive' \| 'print' | 'interactive' | print: for PDFs (see Print mode). |
| onReady | (event: CustomEvent<{ width, height }>) => void | – | The chart has finished painting, fonts included (see Print mode and data-ready). |
| aria-label | string | The title of the total card | Accessible name (see Accessibility). |
ConsumptionOverviewData and the types it uses (ConsumptionCommodity, ConsumptionGranularity, ConsumptionSource, ConsumptionCompareWith, ConsumptionPoint, ConsumptionTotalPoint), and ConsumptionOverviewChartProps, are exported by both packages.
Consumption data
| Field | Type | Description |
|---|---|---|
| commodity | 'electricity' \| 'gas' \| 'water' | Sets the unit (energy or volume), the icon and the default title. |
| granularity | 'day' \| 'month' | The bucket the data was requested with: one point per day or per month. The chart doesn't guess it from the period. |
| from, to | string | The period. The bars go from the day (or month) of from to the one of to, or of today if the period is still going on. |
| total | { source?, points } | The total of the asset. source: 'MEASURE_DEVICE' ("Measured") or 'AGGREGATED' ("Calculated"), shown as a badge. points: ConsumptionTotalPoint[]. |
| compare | { with, weekDayEquivalent, total }, optional | Only when the comparison is on: without it, previousPoints are ignored. with: 'previousMonth' or 'previousYear'. weekDayEquivalent: compare the same day of the week (4 or 52 weeks before). total.points: the total of the previous period. |
| breakdown | array | The children of the asset, in any order: the chart ranks them. Each one: id, name, color (optional, any CSS color), points and previousPoints (optional, with compare). |
| breakdownLimit | number, optional | Children shown before grouping the rest into "Others". Defaults to 4. |
| normalized | array, optional | One card each: id, name (a preset token such as __ROOMS_NAME__, translated, or a name shown as is), points and previousPoints (optional). |
| Point field | Type | Description |
|---|---|---|
| ts | string | Day or month of the value (see Dates and time zone). |
| value | number | Consumption of that day or month in the base unit, not scaled: Wh for electricity and gas, m³ for water. |
| unmeasured | number, optional | Only in total.points: the part of value that the breakdown doesn't measure (see below). |
Points without a valid ts and value are left out, and a missing array is empty; each problem logs a console.error. Without data, with invalid JSON, or without a valid commodity, granularity, from or to, nothing is drawn, a console.error is logged and data-ready is set at once, so a PDF doesn't wait forever.
Dates and time zone
tswithout time (2026-10-11,2026-10) is a calendar day or month, taken as is, whatever the time zone. This is the format to use.tswith time and offset (2026-10-10T22:00:00Z,…+02:00) is an instant: its day is the one intimeZone(here, the 11th inEurope/Madrid).tswith time and no offset (2026-10-11T10:00) is the time of day intimeZone, not in the browser's.fromandtofollow the same rules.- Several points of a series on the same day (or month) are added up in its bar, as in the total card and the contribution.
- Points outside
from–tocount in the cards and the contribution, but have no bar.
What the chart shows
Scale. The unit comes from the largest point of
total.pointsand is the same everywhere:Wh,kWh,MWh,GWh,TWhfor energy, andm³,dam³,hm³,km³for water. Each normalized card scales with its own largest point.Total card. The title (
heading, or thecommodity's), the icon (gas and water; electricity has none), the source badge and the sum oftotal.points, with at most 1 decimal.Change from the previous period, only with
compare:current / previous × 100 − 100, with 1 decimal and "vs last period", translated. Lower is better, as in the comparison chart:| Change | Icon | Colors | |---|---|---| | Above 0 |
trend-up|--consumption-overview-chart-worse-color, icon and text (amber) | | Below 0 |trend-down|--consumption-overview-chart-better-color, icon and text; the amount in-better-text-color(green) | |0, or shown as0.0%| A line |--consumption-overview-chart-neutral-color(grey) | | No value | A line and "— vs last period" |--consumption-overview-chart-neutral-color|There is no value when either total is 0 or the previous one isn't positive. The icons are CDS's, drawn by the chart, so they also show without CDS in the page (e.g. a PDF report).
Normalized cards, in a row below: "Consumption by {name}" and the same amount and change as the total card, without icon or badge. The unit is the scaled base unit (
kWh,m³…).Contribution. The children, from the largest to the smallest sum of
points(ties keep their order). The firstbreakdownLimitare shown as they are; the rest are added up into "Others". "No measured consumption" is added when a point oftotal.pointshasunmeasuredand the children don't cover the total (the sum oftotal.pointsminus the sum of every child'spointsis above 0), with the sum ofunmeasured, even0. When the children add up to the total or more, it isn't shown, whateverunmeasuredsays. The legend shows every item, also those at 0: its value (at most 2 decimals) and its share of the total card, e.g.41.65%. The pie has one sector per item with a value above 0, and a tooltip in interactive mode.No distribution. When no child has points, the contribution and the bars aren't shown: only the cards.
Bars. One series per item of the contribution; series that are 0 or below every day, in both periods, are left out. Days without a point are a gap, not a 0. With
compare, the previous period goes next to each bar, in the same color with diagonal stripes, if it has any value above 0. Each day is paired with the same day of the previous period: 1 month or 1 year before, or 4 or 52 weeks before withweekDayEquivalent(a day that doesn't exist, such as 31 March − 1 month, goes to the last day of the month). Months are always paired with 1 month or 1 year before: a month has no day of the week. Withstacked, each period is stacked apart, with "Others" at the bottom.Y axis. Outliers don't flatten the rest: with 8 values or more in the range the zoom shows, if the largest is at least 8 times the third quartile, the axis ends at 4 times the third quartile, and the taller bars are cut. It's computed again when the zoom changes.
Interactive mode. A tooltip per day (the date with its weekday, a row per series with value and, with
compare, the previous period's date and rows), a zoom slider and a legend that toggles each series with its previous period. The tooltip is added todocument.body, like the ITIC chart's. Names are escaped.Numbers and dates use the separators of the language (
12.641,5,41,65 %ines, which doesn't group 4-digit numbers:1641,5). Dates are day, short month and year in every language (01 oct 2026,01 Oct 2026).
| Text (en) | es |
|---|---|
| Total Energy Consumption, Gas consumption, Water consumption | Consumo Total de Energía, Consumo de gas, Consumo de agua |
| vs last period | vs periodo anterior |
| Contribution by submetering | Contribución por submedición |
| Others, No measured consumption | Otros, Consumo no medido |
| Measured, Calculated | Medido, Calculado |
| Consumption by {name} | Consumo por {name} |
| Rooms, Workstations, Parking places, Building area (__ROOMS_NAME__, __WORKSTATIONS_NAME__, __PARKING_PLACES_NAME__, __BUILDING_AREA_NAME__) | Habitaciones, Puestos de trabajo, Plazas de aparcamiento, Superficie del edificio |
Colors
Children without color take the contribution palette by their position in the ranking, and "Others" takes the color of its position (the 5th, with the default breakdownLimit). The palette starts again after the 5th. "No measured consumption" is grey. The pie and the bars take each color from its dot in the legend, so a custom property, or a color from the data (even a var(--…)), is the same in the three.
| Position | Color | Default |
|---|---|---|
| 1, 6… | --consumption-overview-chart-color-1 | #00B388 |
| 2, 7… | --consumption-overview-chart-color-2 | #E08C00 |
| 3, 8… | --consumption-overview-chart-color-3 | #CA3F38 |
| 4, 9… | --consumption-overview-chart-color-4 | #2A90BC |
| 5, 10… | --consumption-overview-chart-color-5 | #832A6D |
| CSS custom property | Default | Description |
|---|---|---|
| --consumption-overview-chart-background | transparent | Background of the component. |
| --consumption-overview-chart-card-background | --cds-color-surface-100 (#F2F1F1) | Background of the cards and the contribution. |
| --consumption-overview-chart-card-border-color | transparent | Border of the cards. |
| --consumption-overview-chart-text-color | --cds-color-surface-950 | Titles, amounts and names. |
| --consumption-overview-chart-secondary-text-color | --cds-color-surface-500 | Values of the legend. |
| --consumption-overview-chart-badge-background, -badge-border-color | --cds-color-surface-50, --cds-color-surface-400 | Source badge. |
| --consumption-overview-chart-worse-color, -better-color | --cds-color-amber-500, --cds-color-emerald-500 | Icon and text of a change up (worse) or down (better). |
| --consumption-overview-chart-better-text-color | --cds-color-emerald-900 | Amount of a card whose change is better. |
| --consumption-overview-chart-neutral-color | --cds-color-surface-500 | Line and text of a change of 0 or without value. |
| --consumption-overview-chart-color-1 … -5 | See the palette above | Default colors of the contribution. |
| --consumption-overview-chart-unmeasured-color | rgb(217.3, 218.2, 219.95) | "No measured consumption". |
| --consumption-overview-chart-gas-icon-color, -water-icon-color | #CA3F38, #4C8FC5 | Icons of the total card. |
| --consumption-overview-chart-axis-text-color | --cds-color-surface-500 | Axes and legend of the bars. |
| --consumption-overview-chart-grid-line-color | --cds-color-surface-200 | Grid and axis lines of the bars. |
| --consumption-overview-chart-previous-pattern-color | rgba(255, 255, 255, 0.5) | Stripes of the previous period. |
| --consumption-overview-chart-bars-min-height | 320px | Minimum height of the bars. |
| --consumption-overview-chart-pie-height | 200px | Height of the pie. |
Each CDS color also has a fixed fallback, so a page without CDS (e.g. a report) gets the same colors. The gas and water icons are part of the chart (Phosphor's flame-fill and drop-fill, MIT), so they don't need CDS.
Size and updates
- Both modes. The chart is a column as wide and as high as its container: cards, contribution, and the bars, which take the height left over, at least
--consumption-overview-chart-bars-min-height. It is that wide also as an item of a flex row, even a centred one (justify-content: center), and follows the row when it gets narrower or wider. In a container without a height, the bars get that minimum. To fill the height of a flex container:.card { display: flex; flex-direction: column; } .card consumption-overview-chart { flex: 1; min-height: 700px; } - Print mode. Size the container in the report, e.g. the box the chart has on the page; without a height, it is as high as its content, with the bars at their minimum.
- Changing
data,locale,timeZone,heading,stacked,modeor the size repaints the chart. A newdataalso resets the zoom.
Print mode
With mode="print" (see Print mode and data-ready): no tooltip, zoom slider, legend toggle or animations, and the pie and the bars are SVG. Each block (cards, contribution, bars) avoids being split between pages, not the whole chart. data-ready is set when every part is painted.
Accessibility
The cards and the legend are real text, read in order. The element gets role="group" (unless you set another role) and the title of the total card as aria-label, which follows heading and locale. Pass your own aria-label to describe it better; the chart then leaves it alone.
Cos φ chart
The cos φ (displacement power factor, DPF) of an asset by day or by week, as bars colored by how they compare to its target cos φ, with the lines at 1 and at the target. It is drawn with ECharts, and has a print mode for PDF reports and a data-ready attribute that says when it has finished painting.
One asset per chart.
datais the cos φ of a single asset. A saved widget that had several assets isn't supported: the consumer decides what to do with it (e.g. one chart per asset, or the first one).
Pass the data as the API returns it, renaming three fields (see Cos φ data), plus the language and the time zone of the asset. The chart does the rest: the colors from the target, the lines, the ISO week numbers, the texts and translations.
import { CosPhiChart, type CosPhiChartData } from '@circutor/charts-react';
export function CosPhi({ asset, metrics }: { asset: Asset; metrics: Metric[] }) {
// The API's `{ ts, data: { DPF, type } }` as `{ ts, value, type }`, and the asset's own target
const data: CosPhiChartData = {
granularity: 'day',
name: asset.name,
target: asset.targetCosPhi,
points: metrics.map(({ ts, data }) => ({ ts, value: data.DPF, type: data.type })),
};
return <CosPhiChart data={data} locale="es" timeZone={asset.timeZone} subheading="Últimos 14 días" onReady={({ detail }) => console.log(detail.height)} />;
}| Prop | Type | Default | Description |
|---|---|---|---|
| data | CosPhiChartData | – | The data of one asset (see Cos φ data). |
| locale | string | 'en' | Language of the texts, dates and numbers. Only the language is used (es-ES → es); anything other than ca, de, en, es, fr or pt falls back to en. |
| timeZone | string (IANA) | The browser's | Time zone of the asset, e.g. Europe/Madrid (see Dates and time zone). An invalid value uses the browser's and logs a console.error. |
| heading | string | 'cos φ' | Title, in bold, at the top left. |
| subheading | string | – | Shown after the title, in parentheses and not in bold: cos φ (Last 14 days). |
| mode | 'interactive' \| 'print' | 'interactive' | print: for PDFs (see Print mode). |
| onReady | (event: CustomEvent<{ width, height }>) => void | – | The chart has finished painting, fonts included (see Print mode and data-ready). |
| aria-label | string | The visible title | Accessible name (see Accessibility). |
CosPhiChartData and the types it uses (CosPhiPoint, CosPhiGranularity, CosPhiType), and CosPhiChartProps, are exported by both packages.
Cos φ data
| Field | Type | Description |
|---|---|---|
| granularity | 'day' \| 'week' | The bucket the data was requested with: one point per day or per week. Required. |
| name | string, optional | Name of the asset, in bold at the top of the tooltip. It is escaped. |
| target | number, optional | The asset's target cos φ. It is 0.95 when it is missing, isn't a number or is 0 or less, and 1 when it is above 1 (no error). The colors and the line of the target use that value. |
| points | CosPhiPoint[] | One bar per point, in any order: the chart sorts them. [] is valid: the empty axes are drawn. |
| Point field | Type | Description |
|---|---|---|
| ts | string | Start of the bucket: the day, or the Monday of the week (see Dates and time zone). |
| value | number | The cos φ (DPF), from 0 to 1, as the backend rounds it to 2 decimals. 0 is a valid value (a bucket without energy, or a purely reactive load): it is drawn as a bar at 0, not as a gap. |
| type | 'L' \| 'C' \| 'E', optional | L inductive, C capacitive, E bucket without energy (the backend sends it with the 0). Shown after the value (0,95 L). Any other value is ignored, with no error. |
The API returns { ts, data: { DPF, type, … } } and the chart takes { ts, value, type }. The only thing to do is to rename the fields: nothing is calculated, classified or translated, so the chart isn't tied to the shape of metrics/calculate:
// TypeScript
points: metrics.map(({ ts, data }) => ({ ts, value: data.DPF, type: data.type }))# Python (a report)
[{"ts": m["ts"], "value": m["data"]["DPF"], "type": m["data"]["type"]} for m in metrics]A point without a valid ts, or with a value that isn't a number from 0 to 1 (-0.1, 1.2), is left out with a console.error. Without data, with invalid JSON, without a valid granularity or with points that isn't an array, nothing is drawn, a console.error is logged and data-ready is set at once, so a PDF doesn't wait forever.
Dates and time zone
tsis the start of the bucket: a day, or the Monday of the week. It follows the rules of the consumption overview chart:tswithout time (2026-06-01) is a calendar day, taken as is whatever the time zone; with time and offset (2026-03-22T23:00:00Z) is an instant, and its day is the one intimeZone; with time and no offset is the time of day intimeZone.- The backend returns each bucket as an instant: 00:00 of the day, or of the Monday, in the asset's time zone. Pass that zone as
timeZone. With another one, west of the asset's, the Monday falls on the Sunday and the ISO week number is one less. For example2026-03-22T23:00:00Zis Monday 23 March at 00:00 inEurope/Madrid: week 13 withtimeZone="Europe/Madrid", but Sunday 22 and week 12 withAmerica/Mexico_City. - The bucket is the day of the
tsas is, also by week, because it already is the Monday. - Points of the same day are drawn as separate bars, in the order they came.
What the chart shows
Bars. One per point, on a category axis in chronological order. The color depends on the value and the target (the first that applies):
| Condition | Color | Custom property | |---|---|---| |
valueis 0 |#4C5CC5(blue) |--cos-phi-chart-zero-color| |value< target |#CA3F38(red) |--cos-phi-chart-below-target-color| |value≤ target + 0.01 |#FFAB20(orange) |--cos-phi-chart-near-target-color| | the rest |#B9BDC0(grey) |--cos-phi-chart-above-target-color|They are compared in whole hundredths (
Math.round(value * 100)), so there is no floating point error: with the target 0.93, a 0.94 is orange. The rounding is only for the comparison: the values, the tooltip and the line show the numbers as they come. A bar at 0 has no height and isn't seen, but it keeps its color: it is the border of its tooltip.Lines. A line at 1 (
--cos-phi-chart-ideal-line-color,#00B38B, always) and one at the target (--cos-phi-chart-target-line-color,#CA3F38, not without points). With a target of 1 they coincide. They have no label, tooltip or interaction.Axes. The Y axis goes from 0 to 1 with a mark every 0.25, and its numbers follow
locale. The X axis hasDD/MMlabels by day, in every language, or the ISO 8601 week number oftsby week (Monday 29 Dec 2025 is week 1), and its name centered below: "Days" or "Weeks", translated. Ticks line up with the labels, and there is a vertical grid line. The pointer is a line.Values over the bars. The value with 2 decimals in the language and the letter of its type:
0,95 L,0,00 E. They are never cut at the top: the space above the plot leaves room for a bar of1,00, also with a title and in print mode. The ones that overlap are hidden, and all of them are hidden when the component is less than 500 px wide (the width of the element, not of the window), and shown again when it grows to 500 px. It is computed again when it resizes, in print mode too.Title.
heading(cos φby default) in bold, followed by(subheading)in normal weight, at the top left.Tooltip (interactive mode), per bar: the
namein bold (if it comes), the date of the bucket (03 nov 2026) and a row withcos φ:in bold and the value (0,95 L) to the right. Its border takes the color of the bar. It is added todocument.body, like the ones of the other charts, and the values are escaped. Hovering over the value of a bar at 0 also opens it.No legend and no zoom, in any mode.
Numbers and dates use the separators of the language (
0,95ines,0.95inen). Only the title and the X axis name are translated:cos φand the lettersL,C,Earen't.
| Text (en) | es | ca | de | fr | pt |
|---|---|---|---|---|---|
| Days | Días | Dies | Tage | Jours | Dias |
| Weeks | Semanas | Setmanes | Wochen | Semaines | Semanas |
Colors
The bars and the lines have their own colors, with the ones of the table above. The text and the grid follow CDS, with a fixed fallback for a page without it (a report):
| CSS custom property | Default | Description |
|---|---|---|
| --cos-phi-chart-background | transparent | Background of the component. Scout's is #FAFAFB. |
| --cos-phi-chart-zero-color, -below-target-color, -near-target-color, -above-target-color | #4C5CC5, #CA3F38, #FFAB20, #B9BDC0 | Bars, see "What the chart shows". |
| --cos-phi-chart-ideal-line-color, -target-line-color | #00B38B, #CA3F38 | Line at 1 and line at the target. |
| --cos-phi-chart-axis-text-color | --cds-color-surface-500 | Title, axes and values over the bars. |
| --cos-phi-chart-grid-line-color | --cds-color-surface-200 | Lines of the grid and the axes. |
| --cos-phi-chart-min-height | 316px | Minimum height of the component. |
ECharts paints on a canvas and reads the colors when it draws: after changing a custom property, the chart shows it the next time it repaints (new data, locale, timeZone…).
Size and updates
- Both modes. The chart is as wide and as high as its container, with a minimum height of
316px(--cos-phi-chart-min-height). It is that wide also as an item of a flex row, even a centred one (justify-content: center). In a container without a height, it stays at that minimum. To fill the height of a flex container, the minimum keeps it from being 0 px:.card { display: flex; flex-direction: column; } .card cos-phi-chart { flex: 1; } - Print mode. Size the container in the report, e.g. the box the chart has on the page; without a height, it is 316 px high.
- Changing
data,locale,timeZone,heading,subheading,modeor the size repaints the chart.
Print mode
With mode="print" (see Print mode and data-ready): no tooltip, pointer or animations, and the chart is SVG. The values over the bars stay, and still hide below 500 px of width. The whole chart avoids being split between pages (break-inside: avoid). data-ready is set when it has painted, and removed and set again if the width crosses 500 px.
Accessibility
The element gets role="group" (unless you set another role) and its visible title (heading, plus (subheading)) as aria-label, which follows both. Set your own aria-label to describe it better, e.g. with the asset and the period; the chart then leaves it alone.
Cos φ summary
The cos φ (displacement power factor, DPF) of one week as a bar: an icon (inductive or capacitive), "cos φ · Week 20", the value, and a fill of value × 100 % colored by how the value compares to the asset's target cos φ. It is the bar a report shows above the weekly chart of Cos φ chart, and uses the same data (a weekly point of the API, the same target, the same ISO week) and the same rules. It is HTML and CSS, without ECharts, and has a print mode for PDF reports and a data-ready attribute that says when it has finished painting.
No
heading. Unlike the other charts, the text of the bar is always the library's, in the language oflocale. A message such as the report's long "no data" text, with a support email, is the consumer's: show it instead of the component.
Pass the point as the API returns it, renaming three fields (see Cos φ summary data), plus the language and the time zone of the asset. The component does the rest: the colors from the target, the ISO week number, the texts and translations.
import { CosPhiSummary, type CosPhiSummaryData } from '@circutor/charts-react';
export function CosPhiWeek({ asset, week }: { asset: Asset; week: Metric }) {
// The API's `{ ts, data: { DPF, type } }` as `{ ts, value, type }`, and the asset's own target
const data: CosPhiSummaryData = {
point: { ts: week.ts, value: week.data.DPF, type: week.data.type },
target: asset.targetCosPhi,
};
return <CosPhiSummary data={data} locale="es" timeZone={asset.timeZone} onReady={({ detail }) => console.log(detail.height)} />;
}| Prop | Type | Default | Description |
|---|---|---|---|
| data | CosPhiSummaryData | – | The week of one asset (see Cos φ summary data). |
| locale | string | 'en' | Language of the texts and numbers. Only the language is used (es-ES → es); anything other than ca, de, en, es, fr or pt falls back to en. |
| timeZone | string (IANA) | The browser's | Time zone of the asset, e.g. Europe/Madrid (see Week and time zone). An invalid value uses the browser's and logs a console.error. |
| mode | 'interactive' \| 'print' | 'interactive' | print: for PDFs (see Print mode and data-ready). |
| onReady | (event: CustomEvent<{ width, height }>) => void | – | The component has finished painting, fonts included (see Print mode and data-ready). |
| aria-label | string | The text of the bar | Accessible name (see Summary accessibility). |
CosPhiSummaryData and CosPhiSummaryProps are exported by both packages, with CosPhiPoint and CosPhiType, the same as Cos φ chart uses.
Cos φ summary data
| Field | Type | Description |
|---|---|---|
| point | CosPhiPoint, optional | The week. Without it, or with type: 'E', the component says there is no data (see "What the summary shows"). |
| target | number, optional | The asset's target cos φ. It is 0.95 when it is missing, isn't a number or is 0 or less, and 1 when it is above 1 (no error). The colors use that value. |
| Point field | Type | Description |
|---|---|---|
| ts | string | The Monday of the week (see Week and time zone). |
| value | number | The cos φ (DPF), from 0 to 1, as the backend rounds it to 2 decimals. 0 is a valid value (a purely reactive load): with type L or C it is an empty bar, not "no data". |
| type | 'L' \| 'C' \| 'E', optional | L inductive, C capacitive (they set the icon), E week without energy (no data). Any other value is ignored, with no error: there is no icon. |
The API returns { ts, data: { DPF, type, … } } and the component takes { ts, value, type }. It is the same point as Cos φ chart takes, and the only thing to do is to rename the fields. Nothing is calculated, classified or translated, so the component isn't tied to the shape of metrics/calculate:
// TypeScript
point: { ts: week.ts, value: week.data.DPF, type: week.data.type }# Python (a report)
{"ts": week["ts"], "value": week["data"]["DPF"], "type": week["data"]["type"]}A point with a ts that isn't a date, or a value that isn't a number from 0 to 1 (-0.1, 1.2), counts as missing, with a console.error: it shows "No data". Without data, with invalid JSON or with something that isn't an object, nothing is drawn, a console.error is logged and data-ready is set at once, so a PDF doesn't wait forever.
Week and time zone
tsis the Monday of the week, with the same rules as Cos φ chart: without time (2026-05-11) it is a calendar day, taken as is whatever the time zone; with time and offset (2026-05-10T22:00:00Z) it is an instant, and its day is the one intimeZone; with time and no offset it is the time of day intimeZone.- The week number is the ISO 8601 one of that day (Monday 29 Dec 2025 is week 1; Monday 28 Dec 2026, week 53).
- Pass the time zone of the asset. The backend returns the Monday as an instant, 00:00 in the asset's zone. With another one, west of it, the Monday falls on the Sunday and the week is one less:
2026-05-10T22:00:00Zis Monday 11 May inEurope/Madrid(week 20), and Sunday 10 May (week 19) inAmerica/Mexico_Cityor in UTC.
What the summary shows
The bar. As wide as its container, with rounded corners. Its background is the "pale" color of the state, and a fill of
value × 100 %of the width, in the "main" one.The content, over the bar: on the left an avatar with the icon and
cos φ · Week 20, and on the right the value with 2 decimals in the language (0,94, without the letter of its type). In a container too narrow for both, the value goes to the next line, at the end.The icon.
inductiveforLandcapacitiveforC, white, on an avatar in the "strong" color of the state. They are CDS's icons, drawn inline: the page doesn't need CDS. Without a recognized type there is no icon.The state, from the value and the target, compared in whole hundredths (
Math.round(value * 100)), as Cos φ chart does:| Condition | State | Fill | Rest of the bar | Avatar | |---|---|---|---|---| |
value< target | Below target | CDSfeedback-error-main(red-500) |feedback-error-pale|feedback-error-strong| |value≤ target + 0.01 | Near target | CDSfeedback-alert-main(amber-500) |feedback-alert-pale|feedback-alert-strong| | the rest | Above target | CDSfeedback-success-main(emerald-500) |feedback-success-pale|feedback-success-strong|With the target 0.95, a 0.955 is "near". "Above target" is green here and grey in the chart, on purpose: the bar is a status indicator (green is good), and in the chart grey doesn't distract from the bars that matter. Each component keeps its color, and both can be changed with their custom properties. A 0 with
LorCis below the target: an empty bar, in its color and with its icon.No data. With
type: 'E', withoutpoint, or with apointthat was left out as invalid, the component shows "No data" (Sin datos,Sense dades,Keine Daten,Aucune donnée,Sem dados) instead of the bar, centred, without icon or value. It is the term of Comparison chart.Numbers and texts follow
locale. "cos φ" isn't translated. The text of the bar is a template per language, so each one orders the sentence:| Text (
en) |es|ca|de|fr|pt| |---|---|---|---|---|---| | cos φ · Week 20 | cos φ · Semana 20 | cos φ · Setmana 20 | cos φ · Woche 20 | cos φ · Semaine 20 | cos φ · Semana 20 | | No data | Sin datos | Sense dades | Keine Daten | Aucune donnée | Sem dados |
Summary colors
Each state has three colors, from CDS with a fixed fallback for a page without it (a report), and a custom property each:
| CSS custom property | Default | Description |
|---|---|---|
| --cos-phi-summary-below-target-color | --cds-color-feedback-error-main | Fill below the target. |
| --cos-phi-summary-below-target-background | --cds-color-feedback-error-pale | Rest of the bar below the target. |
| --cos-phi-summary-below-target-avatar-color | --cds-color-feedback-error-strong | Avatar of the icon below the target. |
| --cos-phi-summary-near-target-color, -background, -avatar-color | --cds-color-feedback-alert-main, -pale, -strong | The same, near the target. |
| --cos-phi-summary-above-target-color, -background, -avatar-color | --cds-color-feedback-success-main, -pale, -strong | The same, above the target. |
With CDS 7, Scout's feedback-* aliases aren't defined, so the primitives are used (red, amber and emerald); with CDS 5, which the report loads, feedback-* are its own. Contrast. The text and the value are dark (text-default) and large text for WCAG (24 px, regular), so AA is 3:1; over the fill and over the rest of the bar they have 3.57–6.87 against 3 with CDS 7, and 3.11–5.76 with CDS 5, the lowest being the red fill. The white icon has 11–14 against its avatar. If you change a color, keep 3:1 between it and the dark text (and the white icon).
Summary size
- Both modes. The component is as wide as its container (
width: 100%; min-width: 0), also as an item of a flex row, even a centred one, and as high as its content. It has no minimum height. - Changing
data,locale,timeZoneormoderenders it again.
Summary print mode
With mode="print" (see Print mode and data-ready) the component looks the same, as it has nothing interactive. It has print-color-adjust: exact, so the background and the fill are printed in a PDF even without print_background, and avoids being split between pages. data-ready is set once it is rendered and the fonts of the page have loaded; with data it can't read (invalid JSON, or something that isn't an object), at once. "No data" isn't invalid: it waits for the fonts.
Summary accessibility
- With a bar, the element gets
role="meter"witharia-valuemin="0",aria-valuemax="1"andaria-valuenow,aria-valuetextwith the value and the state (0,94, Below target, translated), and the text of the bar asaria-label. - With no data,
role="img"(a meter needsaria-valuenow), without anyaria-value*, and asaria-labelthe text of the bar followed by "No data" in the language (cos φ · Semana 20: Sin datos) when there is a week (type: 'E'), orcos φ: Sin datoswhen there isn't (nopoint, or one that was left out). - The role follows the data, but only the one the component set. If you set your own
roleoraria-label, they are kept. Thearia-value*are only set while the role ismeter.
Print mode and data-ready
Every chart can be printed, e.g. in a PDF report that Chromium generates from an HTML page, with the same props:
| Prop | Type | Default | Description |
|---|---|---|---|
| mode | 'interactive' \| 'print' | 'interactive' | print: without what only works on screen (tooltips, zoom, legend toggles, clicks), and with the ECharts parts as SVG, so their text is vector in the PDF. Each chart's section says what changes. Changing it repaints the chart. |
| onReady | (event: CustomEvent<{ width, height }>) => void | – | The chart has finished painting, fonts included, at the same moment data-ready is set. detail is the size of the element, in px, as getBoundingClientRect() gives it (with decimals, e.g. 617.59375). Called again after each repaint. |
- No chart is split between pages: the ITIC, comparison, cos φ and cos φ summary charts as a whole, the consumption overview chart block by block (cards, contribution, bars).
- Wait for
data-ready, not for the page load. A chart paints after it renders and after its fonts load, so a PDF printed onloadcan catch it half drawn. The element gets thedata-readyattribute when it is completely painted, and loses it at once when something makes it repaint (a prop, its size, a font that loads).onReadyis called at the same moment, but a PDF generator only sees the page: use the attribute.- It isn't set while the element is 0 px wide or high, with a
console.warn: better a PDF that fails with a cause than one with a hole. It is set as soon as the element gets a size. - With data the chart can't read (e.g. invalid JSON), it is set at once, whatever the size and the fonts, so a PDF doesn't wait forever. The chart logs a
console.error.
- It isn't set while the element is 0 px wide or high, with a
- Mark each chart of the report with
data-charts, an empty attribute that the chart itself doesn't read. With it, the generator waits for every chart of the page without knowing their tags. As it is in the HTML from the start, it works however the charts are loaded (charts.esm.jsor each chart's file). A chart without it isn't waited for.
Open the page at the printable width of the paper. ECharts draws at the width its container has when it paints, and isn't told when Chromium lays the page out again for the paper. With Playwright's default viewport (1280 px) the bars would be cut on an A4 page; with a narrower one, they'd leave a gap. The width in px, at 96 dpi, is (paper width − left margin − right margin) in mm / 25.4 × 96, rounded down:
| Paper | Margins | Viewport width |
|---|---|---|
| A4 portrait (210 mm) | 1 cm | 718 |
| A4 landscape (297 mm) | 1 cm | 1046 |
| Letter portrait (8.5 in) | 1 cm | 740 |
For an HTML report (e.g. a Jinja template), see the readme of @circutor/charts, with data-charts on each chart. The generator waits the same way:
page = browser.new_page(viewport={"width": 718, "height": 1000})
page.goto(report_url)
# Every chart marked with data-charts, whatever its tag
page.wait_for_function("[...document.querySelectorAll('[data-charts]')].every(chart => chart.hasAttribute('data-ready'))")
page.pdf(path="report.pdf", format="A4", print_background=True, margin={"top": "1cm", "right": "1cm", "bottom": "1cm", "left": "1cm"})Next.js (App Router)
- The wrappers are client components (
'use client'). A Server Component can render them with serializable props (the data, strings such aslocaleormode,aria-label), butonPointClickandonReadyare functions: pass them from your own'use client'component. - Server-side rendering works without
next/dynamicorssr: false: importing the wrappers doesn't touch the DOM, the server renders an empty element (e.g.<itic-chart>) and the chart draws in the browser after hydration, without hydration warnings.
Testing with Vitest and jsdom
jsdom has no canvas, so ECharts can't draw there and logs getContext() errors. Mock the wrappers in a setup file (setupFiles in your Vitest config), so every test gets a plain element instead.
vi.mock replaces the whole package, so mock every chart you use:
// vitest.setup.tsx
import { vi } from 'vitest';
import type { ComparisonChartItem, ITICChartMarks, ITICPointClickDetail } from '@circutor/charts-react';
vi.mock('@circutor/charts-react', () => ({
// A plain element: check the props it gets (see below). It draws nothing and never calls `onReady`.
ConsumptionOverviewChart: vi.fn(({ 'aria-label': ariaLabel }: { 'aria-label'?: string }) => (
<div data-testid="consumption-overview-chart" aria-label={ariaLabel} />
)),
CosPhiChart: vi.fn(({ 'aria-label': ariaLabel }: { 'aria-label'?: string }) => (
<div data-testid="cos-phi-chart" aria-label={ariaLabel} />
)),
CosPhiSummary: vi.fn(({ 'aria-label': ariaLabel }: { 'aria-label'?: string }) => (
<div data-testid="cos-phi-summary" aria-label={ariaLabel} />
)),
// One list item per row, in the order of `items`, with its name, value and unit. `sort`, `max`, `locale` and `mode` are ignored.
// It never calls `onReady`, as the other mocks.
ComparisonChart: ({ items = [], unit = '', 'aria-label': ariaLabel }: {
items?: ComparisonChartItem[];
unit?: string;
sort?: 'value' | 'trend';
max?: number;
locale?: string;
mode?: 'interactive' | 'print';
'aria-label'?: string;
}) => (
<ul aria-label={ariaLabel} data-testid="comparison-chart">
{items.map((item, index) => (
<li key={index}>{item.value == null ? `${item.name} No data` : `${item.name} ${item.value} ${unit}`.trim()}</li>
))}
</ul>
),
// One button per point, so tests can find points and click them. `locale`, `timeZone` and `mode` are ignored.
IticChart: ({ groups = [], onPointClick, 'aria-label': ariaLabel = 'ITIC chart' }: {
groups?: ITICChartMarks[];
locale?: string;
timeZone?: string;
mode?: 'interactive' | 'print';
onPointClick?: (event: CustomEvent<ITICPointClickDetail>) => void;
'aria-label'?: string;
}) => (
<div role="img" aria-label={ariaLabel} data-testid="itic-chart">
{groups.flatMap(group =>
group.points.map((point, index) => (
<button
key={`${group.phase}-${index}`}
disabled={point.clickable === false}
onClick={() => onPointClick?.(new CustomEvent('pointClick', { detail: { point, group } }))}
>
{group.phase} {point.ts}
</button>
)),
)}
</div>
),
}));Then fireEvent.click(screen.getByText('AN 2024-06-26T20:23:45.220000+02:00')) calls your onPointClick with the original point.
ConsumptionOverviewChart is a vi.fn, so a test checks the data your component builds:
import { ConsumptionOverviewChart } from '@circutor/charts-react';
render(<ConsumptionWidget assetId="a1" />);
expect(screen.getByTestId('consumption-overview-chart')).toBeInTheDocument();
expect(vi.mocked(ConsumptionOverviewChart).mock.lastCall?.[0]).toMatchObject({ data: { commodity: 'gas', granularity: 'day' }, locale: 'es' });CosPhiChart is a vi.fn too, so a test checks the data and the time zone your component passes:
import { CosPhiChart } from '@circutor/charts-react';
render(<CosPhiWidget assetId="a1" />);
expect(screen.getByTestId('cos-phi-chart')).toBeInTheDocument();
expect(vi.mocked(CosPhiChart).mock.lastCall?.[0]).toMatchObject({ data: { granularity: 'week', target: 0.95 }, timeZone: 'Europe/Madrid' });CosPhiSummary is a vi.fn too: the same, with the point of the week and the target in data:
import { CosPhiSummary } from '@circutor/charts-react';
render(<CosPhiWeek assetId="a1" />);
expect(screen.getByTestId('cos-phi-summary')).toBeInTheDocument();
expect(vi.mocked(CosPhiSummary).mock.lastCall?.[0]).toMatchObject({ data: { point: { value: 0.94, type: 'L' }, target: 0.95 }, timeZone: 'Europe/Madrid' });React calls a component with two arguments: the props and a second one, undefined in React 19 and {} in React 18. Read the props from mock.lastCall[0], as above, or pass that second argument to toHaveBeenCalledWith(props, undefined) (React 19). Call vi.mocked(ConsumptionOverviewChart).mockClear() between tests (or set clearMocks: true in your Vitest config) so each test only sees its own calls.
