diff --git a/docs/assets/screenshots/chart-points-dark.png b/docs/assets/screenshots/chart-points-dark.png index 2f23b7649..385708274 100644 Binary files a/docs/assets/screenshots/chart-points-dark.png and b/docs/assets/screenshots/chart-points-dark.png differ diff --git a/docs/assets/screenshots/chart-points-light.png b/docs/assets/screenshots/chart-points-light.png index 9f773a441..408282def 100644 Binary files a/docs/assets/screenshots/chart-points-light.png and b/docs/assets/screenshots/chart-points-light.png differ diff --git a/docs/assets/screenshots/chart-treemap-dark.png b/docs/assets/screenshots/chart-treemap-dark.png index 0e00da838..75bdb0d74 100644 Binary files a/docs/assets/screenshots/chart-treemap-dark.png and b/docs/assets/screenshots/chart-treemap-dark.png differ diff --git a/docs/assets/screenshots/chart-treemap-light.png b/docs/assets/screenshots/chart-treemap-light.png index d890d965d..f14666fce 100644 Binary files a/docs/assets/screenshots/chart-treemap-light.png and b/docs/assets/screenshots/chart-treemap-light.png differ diff --git a/docs/concepts/charts.md b/docs/concepts/charts.md index 2ba751def..03a15111d 100644 --- a/docs/concepts/charts.md +++ b/docs/concepts/charts.md @@ -163,7 +163,8 @@ document.querySelector("pivot-report").colorMap = { Failed: "#e3000f", Success: - A label writes a sample of its line's dash in the line's colour, then the value as the value axis does. `decorateOption` puts the labels right of the plot and keeps them a line apart. With `pixelOf`, the real height of a value after a first draw, they sit at their lines. Below 480 px - it writes the names only and leaves out a label far from its line. + the names stay where all fit in 30 % of the width, else the values (a trend its name); a label + far from its line is left out. - A trend over the categories' order, when a category has no date, is one straight segment. Two functions decide which chart draws which line. The chart, the menu and the report's SVG use @@ -212,13 +213,14 @@ A series' lines take its colour. The lines of no series, a target and a stack's `referenceLineChecks`): per series, or of a stack's total. - The first of equal values gets the point. A series whose values are all the same gets none. - `toEChartsOption` draws them as a silent ECharts `markPoint` on the series: a dot in the series' - colour (a stack's in `--pk-chart-reference`), a label with ▲ or ▼ in that colour and the value in - the text colour. A palette colour such as yellow is too light for text, so the value keeps the - text colour. + colour (a stack's in `--pk-chart-reference`), and a label with ▲ or ▼ and the value in the muted + text colour (`--pk-muted`). A palette colour such as yellow is too light for text, so the dot alone takes it. - `decorateOption` keeps the labels inside the plot: the value axis reaches past them (`dataMin`, `dataMax`). A label that would take the axis across zero sits beside its dot. -- Labels that would cover each other move beside their dots, or are left out. With `pixelOf` it - uses the real heights after a first draw. +- Labels that would cover each other or another bar of a group move beside their dots, then above + the group's highest bar, else are left out; the chart's highest and lowest go first there. With + `pixelOf` it uses the real heights. Bar places assume the default `barGap` and `barCategoryGap`; + a host's `barGap`, `barCategoryGap` or `barWidth` can put a label on a bar or leave it out. - With more than 8 series, only the chart's highest and lowest value keep a label. Every dot stays. - The labels and dots get an outline in `--pk-surface`, so they read over a line. diff --git a/docs/reference/core.md b/docs/reference/core.md index d43ef32e9..93fe0b1d7 100644 --- a/docs/reference/core.md +++ b/docs/reference/core.md @@ -464,7 +464,7 @@ area with `stackPercent`. | `tooltipFormatter` | Builds the tooltip's formatter. Leave it out for a chart without a tooltip, such as an SVG. | | `readColor` | `(color) => color \| null`: a heatmap colour as ECharts can mix it. ECharts reads hex, `rgb()`, `hsl()` and some names only, and another form, such as `oklch()`, turns the cells black. An end with `null` takes `DEFAULT_THEME.colorScale`'s colour. | | `zoom`, `zoomAt`, `timeline`, `touch` | The zoom slider of a chart on a screen. See below. | -| `pixelOf` | `(value) => px`: a value's height in the drawn chart, such as ECharts' `convertToPixel` after a first draw. The labels of the reference lines then sit at their lines. | +| `pixelOf`, `tileOf` | After a first draw. `pixelOf`: `(value) => px`, a value's height in the drawn chart, such as ECharts' `convertToPixel`: the labels of the reference lines then sit at their lines. `tileOf`: `(index, name) => { width, height } \| null`, the tile of a treemap's item `index` named `name`, such as `drawnTiles(chart)` gives: each label then stands in its tile's middle, cut to fit. `drawnTiles` gives `null` for an item it cannot match by name, such as in a tree with children. | It adds the theme's colours from the tokens, and: @@ -480,11 +480,11 @@ It adds the theme's colours from the tokens, and: - A legend moved below a narrow chart. - The category axis laid out for the chart's size (`categoryLabelLayout`: straight, slanted or every n-th, `chart.axisLabels`). The option's `axisEvery` says when every n-th label is written. -- Room on the right for the values at the end of horizontal bars, and fewer value ticks where a - narrow axis needs them. -- A heatmap's row names and cell numbers where its cells have room. -- A treemap's labels in `--pk-text` or `--pk-surface`, whichever has the higher contrast on the tile - (`labelColorOn(fill, candidates)`). Below 4.5:1, the label gets an outline in the other one. +- Room on the right for the values at the end of horizontal bars, fewer value ticks on a narrow axis. +- A heatmap's row names and numbers where its cells have room. Each number takes the one of + `--pk-text` and `--pk-surface` with the higher contrast on its cell if it reaches 4.5:1, else + `#000000` or `#ffffff` (`labelColorOn`). A treemap's labels on a plate, cut to their tiles with + `tileOf`, as [Charts › Treemap](../use/charts.md#treemap) describes. pivotkit-react adds its DOM tooltip through `tooltipFormatter`. Its `readColor` turns any colour the browser reads into `#rrggbb`. pivotkit-report's keeps the colours ECharts reads. Any other one @@ -537,8 +537,8 @@ The view's display settings are part of the option: - The hidden legend entries of `chart.hidden` as `legend.selected`. Without a legend, the option has one that is not shown. - The reference lines (`chart.referenceLines`) as silent `markLine`s, with the value axis's - `dataMin` and `dataMax` reaching them. The high and low points as silent `markPoint`s, their - labels kept inside the plot and apart by `decorateOption`. + `dataMin` and `dataMax` reaching them. The high and low points as silent `markPoint`s, their labels + kept inside the plot and apart by `decorateOption` ([limits](../concepts/charts.md#high-and-low-points)). - Fixed colours (`chart.colors`, `colorMap`) as `itemStyle.color` of a series or a slice, and the line's and the fill's colour of a line or an area. `tooltip.shareFormatter` writes a share in the locale's way. diff --git a/docs/reference/theming.md b/docs/reference/theming.md index 28f67db75..b8e0e21ea 100644 --- a/docs/reference/theming.md +++ b/docs/reference/theming.md @@ -219,6 +219,10 @@ The chart reads these tokens in the current theme: | The heatmap | `--pk-heat-low`/`--pk-heat-high` | | The title's size and weight | `--pk-chart-title-size`, `--pk-weight-strong` | | Its other text: the axes, the legend, the labels on bars, slices and cells, the heatmap's scale | `--pk-chart-text-size` | +| The text on a treemap's tiles, on a plate ([treemap](../use/charts.md#treemap)) | `--pk-text` on `--pk-surface` | +| The numbers on a heatmap's cells: of the two, the one with the higher contrast on the cell if it reaches 4.5:1, else black or white | `--pk-text`, `--pk-surface` | +| The labels of high and low points, with an outline around the letters | `--pk-muted`, outlined in `--pk-surface` | +| The labels of reference lines | `--pk-muted` | | The corners of bars and pie slices | `--pk-radius-chart` | | The corners of the tooltip | `--pk-radius-card` | | The tooltip's total line and the series under the pointer | `--pk-border`, `--pk-weight-strong` | @@ -227,6 +231,12 @@ The chart reads these tokens in the current theme: | The axis line | `--pk-chart-axis`, else `--pk-border` | | The grid | `--pk-grid`, else `--pk-border` | +Black (`#000000`) and white (`#ffffff`) are fixed values, not tokens. The contrast of `--pk-text` +and of `--pk-muted` on `--pk-surface` is the theme's: the chart does not change them. Without a +`--pk-surface` the chart can draw, a treemap's text has no plate and takes a heatmap's ink. That +is a missing `--pk-surface`, or in pivotkit-report on its own a form ECharts does not read, such as +`oklch()` or `color-mix()`. A missing `--pk-surface` also leaves the points' labels without an outline. + The heatmap's colours work in any form the browser reads, `oklch()` too. The chart mixes the colour of each cell from them. It takes them as plain sRGB colours: a colour's alpha is dropped, and a colour outside sRGB, such as a P3 one, is clipped to its nearest sRGB colour. The HTML report and the SVG of the Export menu get them as the screen draws diff --git a/docs/use/charts.md b/docs/use/charts.md index 59b309f3c..9f4d4b3a5 100644 --- a/docs/use/charts.md +++ b/docs/use/charts.md @@ -81,10 +81,14 @@ report: the report itself, field list included, is at least 1,024 pixels wide. ![A treemap of 20 countries by population, each tile named with its value](../assets/screenshots/chart-treemap-light.png#only-light) ![A treemap of 20 countries by population, each tile named with its value](../assets/screenshots/chart-treemap-dark.png#only-dark) -- Each tile shows its name and value. A small tile cuts the text with "…". The tooltip shows both. +- Each tile shows its name and value in its middle, on a plate in the background's colour. The + plate looks the same on every tile, whatever the tile's colour. +- A name wider than its tile ends in "…" after at least 4 characters; a value that does not fit is + left out. A tile with less room, or lower than a line, shows no text. Point at or tap a tile for both. - A row with a total of 0 or less gets no tile. - The colours only tell the tiles apart. They do not stand for a value. -- The text on a tile is light or dark, whichever reads better on its colour. +- Without a background colour the chart can draw, the text has no plate. It then takes the text or + background colour, else black or white, that reads on its tile ([Theming](../reference/theming.md#chart-colours)). - It has no legend. **Chart settings › Series** hides a tile or sets its colour. - With a field on Columns, a tile adds up every column, as a pie does. - A click on a tile opens no rows. @@ -311,8 +315,9 @@ target you set. High and low points mark the highest and the lowest value of eac - Each line has a label right of the plot, at the line's height. It starts with a short sample of the line's dash in the line's colour, then the name and the value, written short as on the axis, such as "Target 500K". A label of a line close to another moves just below it. -- On a chart narrower than 480 px, such as on a phone, the labels name the lines only. A label - that cannot sit near its line is left out there; the tooltip still names the line. +- On a chart narrower than 480 px, such as on a phone, the names stay only where all labels fit in + 30 % of the width. Else a label writes the value (a trend its name) after its dash in the series' + colour, as in the legend. A label that cannot sit near its line is left out; the tooltip names it. - The value axis reaches every line. A target higher than every bar still shows. - The tooltip lists the lines at the category with their whole values: a trend with its value there. - The chart image, the HTML report and the chart as SVG draw the lines too. @@ -325,15 +330,16 @@ target you set. High and low points mark the highest and the lowest value of eac ![A line for each year of monthly temperatures, each year's highest and lowest month marked with a dot and a label with ▲ or ▼ and its value](../assets/screenshots/chart-points-light.png#only-light) ![A line for each year of monthly temperatures, each year's highest and lowest month marked with a dot and a label with ▲ or ▼ and its value](../assets/screenshots/chart-points-dark.png#only-dark) -- The dot has the series' colour. Its label starts with ▲ for the highest value or ▼ for the - lowest, in the same colour, then the value as the table writes it. +- The dot has the series' colour. Its label, in the muted text colour (`--pk-muted`), starts with + ▲ for the highest value or ▼ for the lowest, then the value as the table writes it. - On a line, the highest label sits above its dot and the lowest below it. - On bars and areas, both labels sit above the dot. On a bar, that is past the bar's end. - A label never stretches the axis across zero. Near zero, it sits beside its dot. - Labels have an outline in the background's colour, so they read over a line. - A stack marks the highest and lowest total, in the neutral colour of a target. -- Two labels that would cover each other move beside their dots. A label that still has no room - is left out. Its dot stays, and the tooltip names the value. +- Labels that would cover each other or another bar of a group move beside their dots or above + the group. In dense grouped bars the chart's highest and lowest label come first, and some + others are left out; the tooltip has the value. - With more than 8 series, every dot stays, but only the chart's highest and lowest value keep a label. - Where two categories share the highest value, the first one gets the dot. A series whose values @@ -399,8 +405,8 @@ Point at a bar, a segment of stacked bars or a point of a line to see a tooltip. - A series without a value at the category is left out. - A long series name ends in "…". When more series are there than fit, the last line says how many more there are, and whether the total includes them. -- On a phone, tap a bar, a point or a heatmap cell to see its tooltip. Tap it again to open - [its menu](#filter-from-the-chart). +- On a phone, tap a bar, a point, a heatmap cell or a treemap tile to see its tooltip. Tap a bar, a + point or a cell again to open [its menu](#filter-from-the-chart). - A pie's tooltip shows the value's name, the slice and its value. With a field on Columns, a slice adds up every column. - A heatmap's tooltip shows the value's name, the cell's row and column and its value. diff --git a/packages/pivotkit-core/CHANGELOG.md b/packages/pivotkit-core/CHANGELOG.md index 071e6b809..37c3cfbee 100644 --- a/packages/pivotkit-core/CHANGELOG.md +++ b/packages/pivotkit-core/CHANGELOG.md @@ -12,6 +12,36 @@ All notable changes to `pivotkit-core` are documented in this file. The format i A bundle that splits by file keeps them out of a page's first load until an export needs them ([#772](https://github.com/eizedev/pivotkit/issues/772)). The public API is unchanged. - The README says that a minor release of 0.x can break things, with links to Versioning and Upgrading. +- `labelColorOn(fill, candidates)` can return `#000000` or `#ffffff`, not one of the candidates, where + none reaches 4.5:1 on the fill ([#914](https://github.com/eizedev/pivotkit/issues/914)). + +### Added + +- `decorateOption` takes `tileOf(index, name)`, a treemap's tiles after a first draw, and + `drawnTiles(chart)` reads them from an ECharts instance. A treemap's labels then stand in their + tiles' middle, cut to fit. + +### Fixed + +- Text on coloured fills reads at 4.5:1 or more in both themes + ([#914](https://github.com/eizedev/pivotkit/issues/914)): + - A treemap writes its labels in `--pk-text` on a plate in `--pk-surface`, the same on every tile. + With `tileOf`, a name wider than its tile ends in "…" and a value that does not fit is left out; + a cut name keeps at least 4 characters. A tile with less room, or lower than a line, has no label, + so no plate stands without words. + Without a `--pk-surface` the chart can draw, no label has a plate. + - A heatmap's numbers take `--pk-text` or `--pk-surface`, else black or white, whichever reaches + 4.5:1 on the cell. `labelColorOn` gives black or white where neither candidate reaches it. +- High and low points ([#913](https://github.com/eizedev/pivotkit/issues/913)): + - The ▲ and ▼ take the muted text colour (`--pk-muted`), as the value does. A light series colour made them hard to read. + - In grouped bars a label no longer crosses another bar of its group. It moves beside its dot or + above the group's highest bar. In dense grouped bars the chart's highest and lowest are placed + first and some other labels are left out; the tooltip has the value. +- Reference lines ([#913](https://github.com/eizedev/pivotkit/issues/913)): + - On a chart narrower than 480 px, the labels keep the lines' names where all fit in 30 % of the + width. Else each writes the value instead of the name; a trend keeps its name. + - The sample before an average's label takes the series' colour from `colorMap` and + `chart.colors`, as the line does. ## [0.10.0] - 2026-11-24 diff --git a/packages/pivotkit-core/src/chart-colors.js b/packages/pivotkit-core/src/chart-colors.js index 33debc29c..fbbcbb8b7 100644 --- a/packages/pivotkit-core/src/chart-colors.js +++ b/packages/pivotkit-core/src/chart-colors.js @@ -3,6 +3,7 @@ * over the host's colorMap. Names match without regard to case; a name in neither keeps the palette's * colour. Only a drawn chart needs this module. */ +import { EXTREME_INKS } from "./defaults.js"; /** * A colour a host may name: hex of 3, 4, 6 or 8 digits, rgb(), rgba(), hsl(), hsla() or a CSS colour @@ -88,9 +89,17 @@ export function contrastOf(a, b) { return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05); } +/** The contrast text needs on its background (WCAG 2.2 AA, normal text). */ +export const TEXT_CONTRAST = 4.5; + /** - * The text colour of `candidates` (the theme's tokens) with the highest WCAG contrast on `fill`: the - * label on a treemap's tile. A colour it cannot read (not hex or rgb()) gives the first candidate. + * The colour of text on a coloured area (#914): of `candidates` (the theme's text and background + * colours, one dark and one light), the one with the highest WCAG contrast on `fill`. Where none + * reaches TEXT_CONTRAST (a mid blue between the theme's two), white or black: the one on the best ink's + * side where it reaches TEXT_CONTRAST, else the other. One of them always reaches 4.58:1 on an opaque + * colour. A fill it cannot read (not hex or rgb()) gives + * the first candidate. Used for a heatmap's cell numbers; decorateOption puts a treemap's labels on a + * background of their own instead (treemapLabels in chart-style.js). * @param {string} fill * @param {string[]} candidates */ @@ -99,5 +108,13 @@ export function labelColorOn(fill, candidates) { if (!read.length) { return candidates[0]; } - return read.reduce((best, x) => (/** @type {number} */ (x.ratio) > /** @type {number} */ (best.ratio) ? x : best)).c; + const best = read.reduce((a, x) => (/** @type {number} */ (x.ratio) > /** @type {number} */ (a.ratio) ? x : a)); + if (/** @type {number} */ (best.ratio) >= TEXT_CONTRAST) { + return best.c; + } + // the extreme on the best ink's side first (a light ink white), so the ink changes side only where it must + const [black, white] = EXTREME_INKS; + const light = /** @type {number} */ (contrastOf(best.c, black)) > /** @type {number} */ (contrastOf(best.c, white)); + const [near, far] = light ? [white, black] : [black, white]; + return /** @type {number} */ (contrastOf(fill, near)) >= TEXT_CONTRAST ? near : far; } diff --git a/packages/pivotkit-core/src/chart-fit.js b/packages/pivotkit-core/src/chart-fit.js index 1aa3d42f7..85096085e 100644 --- a/packages/pivotkit-core/src/chart-fit.js +++ b/packages/pivotkit-core/src/chart-fit.js @@ -290,6 +290,125 @@ const VALUE_LABEL_ROOM = 48; /** More series than this: each dot stays, but only the chart's highest and lowest value keep a label. */ export const POINT_LABEL_SERIES = 8; +/** ECharts' gap between the bars of one category, a share of a bar's width (its barGap default). */ +const BAR_GAP = 0.3; +/** ECharts' gap between two categories' bars, a share of the category's band (its barCategoryGap default). */ +const BAR_CATEGORY_GAP = 0.2; + +/** + * Where ECharts draws each series' bars within a category's band of `band` px, as its bar layout does + * with its default barGap and barCategoryGap (BAR_GAP, BAR_CATEGORY_GAP) and the series' barMaxWidth: a + * host's barGap, barCategoryGap or barWidth (chartOptions) moves the bars, and the point labels placed + * here may then cross a bar or be left out. The layout is estimated, not read from the drawn bars: + * per series index, the offset of the bar's left edge from the band's middle and its width; null for a + * series that is no bar, or hidden in the legend. Stacked bars share one column. + * @param {any[]} series the decorated series (barMaxWidth set by decorateOption) + * @param {number} band + * @param {{ selected?: Record }} [legend] the option's (selected false: hidden) + * @returns {({ offset: number, width: number } | null)[]} + */ +function barSlots(series, band, legend) { + /** @type {Map} each column with its series */ + const columns = new Map(); + series.forEach((s, i) => { + if (s.type !== "bar" || legend?.selected?.[s.name] === false) return; + const key = s.stack ? `stack:${s.stack}` : `own:${i}`; + columns.set(key, [...(columns.get(key) ?? []), i]); + }); + const n = columns.size; + const auto = n ? Math.max(0, (band * (1 - BAR_CATEGORY_GAP)) / (n + (n - 1) * BAR_GAP)) : 0; + /** @type {({ offset: number, width: number } | null)[]} */ + const slots = series.map(() => null); + const widths = [...columns.values()].map((members) => { + const max = Math.min(...members.map((i) => (typeof series[i].barMaxWidth === "number" ? series[i].barMaxWidth : Infinity))); + return Math.min(auto, max); + }); + const total = widths.reduce((sum, w) => sum + w * (1 + BAR_GAP), 0) - (widths.length ? widths[widths.length - 1] * BAR_GAP : 0); + let offset = -total / 2; + [...columns.values()].forEach((members, k) => { + for (const i of members) slots[i] = { offset, width: widths[k] }; + offset += widths[k] * (1 + BAR_GAP); + }); + return slots; +} + +/** + * The order pointLabels places its labels in, as indexes into `items`. In grouped bars, where labels + * are left out most, the chart's highest and lowest (`kept`) come first, so they keep theirs; elsewhere + * the series' order, which moves labels apart rather than leaving them out. + * @param {unknown[]} items + * @param {boolean} grouped + * @param {unknown[]} kept + * @returns {number[]} + */ +function placingOrder(items, grouped, kept) { + const order = items.map((_, k) => k); + const rank = (/** @type {number} */ k) => Number(kept.includes(items[k])); + return grouped ? order.sort((a, b) => rank(b) - rank(a)) : order; +} + +/** + * The boxes of grouped bars (side by side, not stacked) in a chart's estimated pixels, by series and + * category: the obstacles of the high and low points' labels. None for one column of bars. + * @param {any[]} series + * @param {({ offset: number, width: number } | null)[]} slots barSlots' + * @param {number} band + * @param {(value: number) => number} yOf + * @returns {{ si: number, index: number, x0: number, x1: number, y0: number, y1: number }[]} + */ +function groupedBars(series, slots, band, yOf) { + const offsets = new Set(slots.filter(Boolean).map((slot) => /** @type {any} */ (slot).offset)); + if (offsets.size < 2) return []; + return series.flatMap((s, si) => { + const slot = slots[si]; + if (!slot || s.stack) return []; + return (s.data ?? []).flatMap((/** @type {any} */ d, /** @type {number} */ index) => { + const v = typeof d === "number" ? d : typeof d?.value === "number" ? d.value : null; + if (v === null) return []; + const x0 = (index + 0.5) * band + slot.offset; + const [a, b] = [yOf(Math.max(v, 0)), yOf(Math.min(v, 0))]; + return [{ si, index, x0, x1: x0 + slot.width, y0: Math.min(a, b), y1: Math.max(a, b) }]; + }); + }); +} + +/** + * Whether a point's label box, its outline with it, crosses a bar other than its point's own (groupedBars). + * @param {{ si: number, index: number, x0: number, x1: number, y0: number, y1: number }[]} bars + * @param {{ si: number, index: number }} point + * @param {{ x0: number, x1: number, y0: number, y1: number }} box + */ +function acrossBar(bars, point, box) { + return bars.some((r) => (r.si !== point.si || r.index !== point.index) && r.x0 < box.x1 && box.x0 < r.x1 && r.y0 < box.y1 && box.y0 < r.y1); +} + +/** + * How far (px, up: negative) a label over its dot (`box`) moves to stand over the highest bar of its + * category's group (groupedBars), POINT_HALO above it; 0 when it stands there already or no group is. + * @param {{ index: number, y0: number }[]} bars + * @param {number} index the point's category + * @param {{ y1: number }} box + */ +function overGroup(bars, index, box) { + const tops = bars.filter((r) => r.index === index).map((r) => r.y0); + return tops.length ? Math.min(0, Math.min(...tops) - POINT_HALO - box.y1) : 0; +} + +/** + * How far (px) a label's box at `pos` moves into the plot. Beside a dot near the plot's top or bottom + * edge: up or down. Above or below a dot at the plot's first or last category: sideways. Over its + * group ("raised"): up by `lift`, and sideways as above. + * @param {string} pos + * @param {{ x0: number, x1: number, y0: number, y1: number }} box + * @param {{ width: number, top: number, bottom: number, lift: number }} plot + */ +function intoPlot(pos, box, { width, top, bottom, lift }) { + const beside = pos === "right" || pos === "left"; + const dy = pos === "raised" ? lift : beside ? Math.min(0, bottom - box.y1) || Math.max(0, top - box.y0) : 0; + const dx = beside ? 0 : Math.max(0, -box.x0) || Math.min(0, width - box.x1); + return { dx, dy }; +} + /** * The labels of the high and low points (pivotkit-core's markPoint): kept inside the plot and apart. * - The value axis reaches past each label at the plot's ends: `dataMin` and `dataMax` in values, from @@ -297,17 +416,20 @@ export const POINT_LABEL_SERIES = 8; * label that would take the axis across zero, past every value, goes beside its dot instead. * - With more than POINT_LABEL_SERIES series, only the chart's highest and lowest value keep a label; * every dot stays. - * - Two labels that would cover each other, or another point's dot, move: the later one beside its dot - * (right, then left), else it is left out. The dot stays; the tooltip and the text alternative name - * the value. `pixelOf` gives each value's real height after a first draw; without it the heights - * are estimated on the same plot. + * - Two labels that would cover each other, another point's dot or another bar (grouped bars, #913), + * move: the later one beside its dot (right, then left), then over the highest bar of its group, + * else it is left out: in dense grouped bars some labels are left out. There the chart's highest and + * lowest value are placed first, so they keep theirs. The dot stays; the tooltip and the text + * alternative name the value. Each point sits over its own bar (barSlots). + * `pixelOf` gives each value's real height after a first draw; without it the heights are + * estimated on the same plot. * Horizontal bars: each bar has a band of its own, so only the axis's reach is set. * @param {any[]} series the decorated series - * @param {{ width: number, height: number, grid: any, fontSize: number, horizontal: boolean, axis: any, pixelOf?: (value: number) => number }} chart - * axis: the value axis, with the reach the reference lines gave it + * @param {{ width: number, height: number, grid: any, fontSize: number, horizontal: boolean, axis: any, pixelOf?: (value: number) => number, legend?: { selected?: Record } }} chart + * axis: the value axis, with the reach the reference lines gave it; legend: the option's (its selected: false hides a series) * @returns {{ series: any[], dataMin?: number, dataMax?: number } | null} null without points */ -export function pointLabels(series, { width, height, grid, fontSize, horizontal, axis, pixelOf }) { +export function pointLabels(series, { width, height, grid, fontSize, horizontal, axis, pixelOf, legend }) { /** @type {{ si: number, di: number, d: any, value: number, index: number, text: string }[]} */ const items = []; series.forEach((s, si) => @@ -344,12 +466,13 @@ export function pointLabels(series, { width, height, grid, fontSize, horizontal, let dataMin = typeof axis?.dataMin === "number" ? axis.dataMin : undefined; /** @type {Map} */ const moves = new Map(); + // the chart's highest and lowest value + const highest = items.reduce((a, b) => (b.d.name === "max" && (!a || b.value > a.value) ? b : a), /** @type {typeof items[number] | null} */ (null)); + const lowest = items.reduce((a, b) => (b.d.name === "min" && (!a || b.value < a.value) ? b : a), /** @type {typeof items[number] | null} */ (null)); // many series: the labels would cover the lines; only the chart's highest and lowest keep theirs if (series.filter((s) => s.type === "line" || s.type === "bar").length > POINT_LABEL_SERIES) { - const top = items.reduce((a, b) => (b.d.name === "max" && (!a || b.value > a.value) ? b : a), /** @type {typeof items[number] | null} */ (null)); - const bottom = items.reduce((a, b) => (b.d.name === "min" && (!a || b.value < a.value) ? b : a), /** @type {typeof items[number] | null} */ (null)); for (const i of items) { - if (i !== top && i !== bottom) moves.set(i.d, { show: false }); + if (i !== highest && i !== lowest) moves.set(i.d, { show: false }); } } for (const i of items) { @@ -379,13 +502,17 @@ export function pointLabels(series, { width, height, grid, fontSize, horizontal, const yOf = (/** @type {number} */ v) => (pixelOf ? pixelOf(v) : ((extent[1] - v) / (extent[1] - extent[0] || 1)) * plot); /** @typedef {{ x0: number, x1: number, y0: number, y1: number }} Box */ const overlap = (/** @type {Box} */ a, /** @type {Box} */ b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1; + // a point stands over the middle of its bar: grouped bars stand side by side in the band + const slots = barSlots(series, band, legend); + const xOf = (/** @type {number} */ si, /** @type {number} */ index) => (index + 0.5) * band + (slots[si] ? /** @type {any} */ (slots[si]).offset + /** @type {any} */ (slots[si]).width / 2 : 0); + const bars = groupedBars(series, slots, band, yOf); const dots = items.map((i) => { - const x = (i.index + 0.5) * band; + const x = xOf(i.si, i.index); const y = yOf(i.value); return { x0: x - POINT_DOT, x1: x + POINT_DOT, y0: y - POINT_DOT, y1: y + POINT_DOT }; }); const boxOf = (/** @type {typeof items[number]} */ i, /** @type {string} */ pos) => { - const x = (i.index + 0.5) * band; + const x = xOf(i.si, i.index); const y = yOf(i.value); // the outline adds to the text's box on every side const tall = line + 2 * POINT_HALO; @@ -401,21 +528,27 @@ export function pointLabels(series, { width, height, grid, fontSize, horizontal, const plotBottom = yOf(extent[0]); /** @type {Box[]} */ const placed = []; - items.forEach((i, k) => { + placingOrder(items, bars.length > 0, [highest, lowest]).forEach((k) => { + const i = items[k]; if (moves.get(i.d)?.show === false) return; const own = moves.get(i.d)?.position ?? i.d.label?.position ?? "top"; // over no other label and no other dot; beside its dot, within the plot's width (a label above // or below a dot stays within its category's band, the plot's margin takes the rest) - const free = (/** @type {Box} */ b, /** @type {string} */ p) => (p === "top" || p === "bottom" || (b.x0 >= 0 && b.x1 <= band * categories)) && !placed.some((o) => overlap(o, b)) && !dots.some((d, j) => j !== k && overlap(d, b)); - const pos = [...new Set([own, "right", "left"])].find((p) => free(boxOf(i, p), p)); + const free = (/** @type {Box} */ b, /** @type {string} */ p) => (p === "top" || p === "bottom" || (b.x0 >= 0 && b.x1 <= band * categories)) && !placed.some((o) => overlap(o, b)) && !dots.some((d, j) => j !== k && overlap(d, b)) && !acrossBar(bars, i, b); + // over the highest bar of its group: a label over its dot, within the plot + const lift = own === "top" ? overGroup(bars, i.index, boxOf(i, "top")) : 0; + const raised = (/** @type {Box} */ b) => ({ ...b, y0: b.y0 + lift, y1: b.y1 + lift }); + const boxAt = (/** @type {string} */ p) => (p === "raised" ? raised(boxOf(i, "top")) : boxOf(i, p)); + const candidates = [...new Set([own, "right", "left"]), ...(lift ? ["raised"] : [])]; + const pos = candidates.find((p) => (p !== "raised" || boxAt(p).y0 >= plotTop) && free(boxAt(p), p === "raised" ? "top" : p)); if (pos) { - const box = boxOf(i, pos); - // beside a dot near the plot's top or bottom edge: moved up or down into the plot - const dy = pos === "right" || pos === "left" ? Math.min(0, plotBottom - box.y1) || Math.max(0, plotTop - box.y0) : 0; - // above or below a dot at the plot's first or last category: moved sideways into the plot - const dx = pos === "top" || pos === "bottom" ? Math.max(0, -box.x0) || Math.min(0, band * categories - box.x1) : 0; - placed.push({ x0: box.x0 + dx, x1: box.x1 + dx, y0: box.y0 + dy, y1: box.y1 + dy }); - if (pos !== (i.d.label?.position ?? "top") || dy || dx) moves.set(i.d, { position: pos, ...(dy || dx ? { offset: [dx, dy] } : {}) }); + const box = boxAt(pos); + const { dx, dy } = intoPlot(pos, box, { width: band * categories, top: plotTop, bottom: plotBottom, lift }); + // the raised box has its lift already + const shift = pos === "raised" ? 0 : dy; + placed.push({ x0: box.x0 + dx, x1: box.x1 + dx, y0: box.y0 + shift, y1: box.y1 + shift }); + const at = pos === "raised" ? "top" : pos; + if (at !== (i.d.label?.position ?? "top") || dy || dx) moves.set(i.d, { position: at, ...(dy || dx ? { offset: [dx, dy] } : {}) }); } else { moves.set(i.d, { show: false }); } diff --git a/packages/pivotkit-core/src/chart-measure.js b/packages/pivotkit-core/src/chart-measure.js index bcf757e66..68eee80a6 100644 --- a/packages/pivotkit-core/src/chart-measure.js +++ b/packages/pivotkit-core/src/chart-measure.js @@ -133,3 +133,20 @@ export const LINE_SAMPLES = Object.freeze({ dashed: "– –", dotted: "···", * @param {string} words */ export const lineLabelText = (type, words) => `{s|${Object.hasOwn(LINE_SAMPLES, type) ? LINE_SAMPLES[/** @type {keyof typeof LINE_SAMPLES} */ (type)] : ""}} ${String(words).replace(/[{}|]/g, "")}`; + +/* + * A treemap's labels on plates (treemapLabels in chart-style.js). Exported for the browser tests, which + * derive from them the smallest tile that must show a label. + */ +/** ECharts' padding of a treemap's label inside its tile, left and right, px (its default `label.padding`). */ +export const TILE_LABEL_PADDING = 5; +/** The room a treemap's lines keep above and below them in their tile, px. */ +export const TILE_EDGE = 1; +/** A plate's room left and right of its words, px. */ +export const PLATE_SIDE = 2; +/** The fewest characters a tile writes of a name cut short; with fewer it writes no label. Four, so a cut name is not a stub ("Ind…" beside "India"). */ +export const TILE_MIN_CHARS = 4; +/** The end of a text cut short: one character, so a narrow tile keeps more of the name. */ +export const ELLIPSIS = "\u2026"; +/** The height of a plate's line at `fontSize`, px. */ +export const plateLine = (/** @type {number} */ fontSize) => Math.round(fontSize * 1.5); diff --git a/packages/pivotkit-core/src/chart-style.js b/packages/pivotkit-core/src/chart-style.js index 37c5d8ea4..f2bfc6f7e 100644 --- a/packages/pivotkit-core/src/chart-style.js +++ b/packages/pivotkit-core/src/chart-style.js @@ -7,26 +7,173 @@ * reason: a bundle that loads the chart from here keeps the option's code out of its first load. */ -import { DEFAULT_THEME, HEATMAP_GRID_BOTTOM, pxOf } from "./defaults.js"; +import { DEFAULT_THEME, EXTREME_INKS, HEATMAP_GRID_BOTTOM, pxOf } from "./defaults.js"; import { BOTTOM_LEGEND_ROOM, CATEGORY_LABEL_WIDTH, RIGHT_LEGEND_MIN_WIDTH, categoryLabelLayout, categoryLabelWidth, columnLabelLayout, groupLabelsFit, heatmapCellLabels, pieLabelRoom, ringLabelsFit, rowLabelInterval } from "./chart-layout.js"; import { POINT_HALO, barExtent, otherSlices, pieLabelFit, pieLabelTexts, pointLabels, valueAxisSplit, valueLabelRoom } from "./chart-fit.js"; -import { AXIS_LABEL_MARGIN, LINE_SAMPLES, categorySlot, groupLabelLine, groupLabelOffset, heatmapFrame, lineLabelText, textWidth } from "./chart-measure.js"; +import { AXIS_LABEL_MARGIN, ELLIPSIS, LINE_SAMPLES, PLATE_SIDE, TILE_EDGE, TILE_LABEL_PADDING, TILE_MIN_CHARS, categorySlot, groupLabelLine, groupLabelOffset, heatmapFrame, lineLabelText, plateLine, textWidth } from "./chart-measure.js"; import { ZOOM_SLIDER, longestNames, zoomRange, zoomSlider, zoomWindow } from "./chart-zoom.js"; -import { contrastOf, labelColorOn } from "./chart-colors.js"; +import { labelColorOn } from "./chart-colors.js"; export * from "./chart-layout.js"; export { toEChartsOption } from "./chart.js"; export { extremePoints, referenceLineChecks, referenceLines } from "./chart-lines.js"; export { labelColorOn }; +/** + * A treemap's tiles as a first draw laid them out, for decorateOption's `tileOf`: by an item's place in + * the series' data and its name, its tile's size, or null. `chart` is the ECharts instance. ECharts + * (checked with 6.1.0) keeps the tree in its list depth first, the root first: a flat treemap's item i + * at i + 1. An item's name that is not at that place (a tree with children) gives null. + * @param {any} chart + * @returns {((index: number, name: string) => { width: number, height: number } | null) | undefined} + */ +export function drawnTiles(chart) { + const series = chart.getModel?.()?.getSeriesByIndex(0); + if (series?.subType !== "treemap") return undefined; + const data = series.getData(); + return (index, name) => { + if (index + 1 >= data.count() || data.getName(index + 1) !== name) return null; + const tile = data.getItemLayout(index + 1); + return typeof tile?.height === "number" ? { width: tile.width, height: tile.height } : null; + }; +} + /** Room (px) beside a combo's plot: the margins and the numbers of its two value axes, estimated. */ const COMBO_AXES_ROOM = 136; -/** The contrast text needs on its background (WCAG 2.2 AA, normal text). */ -const TEXT_CONTRAST = 4.5; /** A copy of an object without the given keys. */ const without = (obj, keys) => Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k))); +/* + * Text on a coloured area (#913, #914): it reads against a colour the chart knows. + * - A heatmap's cell has one colour of an ordered scale: its number takes labelColorOn's ink for it + * (the theme's text or background colour, else black or white), at least 4.5:1. Along the scale the + * ink changes once, from dark on light cells to light on dark ones. + * - A treemap's tiles take any colours of a palette, a host's among them: each label sits on a plate in + * the background colour (--pk-surface), in the text colour (--pk-text). Every label looks the same, + * whatever the tile's colour and in both themes; an ink chosen per tile would flip between dark and + * light from tile to tile. + * - A high or low point's label crosses the plot and the bars: an outline in the background colour + * around its letters (POINT_HALO), the same backing as a plate. + */ + +/** + * Rich text of ECharts: `text` in the style `key`, line by line. A "}" ends a style's text in ECharts' + * markup, so it stands between two runs of the style, in the label's own style. + * @param {string} key + * @param {unknown} text + */ +const styled = (key, text) => + String(text) + .split("\n") + .map((line) => line.split("}").map((part) => (part ? `{${key}|${part}}` : "")).join("}")) + .join("\n"); + +/** + * The ink of `inks` that reads on `fill` (labelColorOn), black or white when none does; `inks[0]` for a + * fill it cannot read. + * @param {unknown} fill + * @param {string[]} inks + * @param {((color: string) => string | null) | undefined} readColor + */ +function inkOn(fill, inks, readColor) { + const read = typeof fill === "string" ? (readColor ? (readColor(fill) ?? fill) : fill) : null; + return read ? labelColorOn(read, inks) : inks[0]; +} + +/** + * `text` as it fits `width` px at `fontSize` (textWidth): whole, else cut with ELLIPSIS after at least + * TILE_MIN_CHARS characters; null when that does not fit. + * @param {string} text + * @param {number} width + * @param {number} fontSize + */ +function fitText(text, width, fontSize) { + if (textWidth(text, fontSize) <= width) return text; + const chars = [...text]; + for (let n = chars.length - 1; n >= TILE_MIN_CHARS; n--) { + const cut = `${chars.slice(0, n).join("").trimEnd()}${ELLIPSIS}`; + if (textWidth(cut, fontSize) <= width) return cut; + } + return null; +} + +/** + * A treemap's labels (see above): on plates in the background colour, the text in the text colour, the + * plates' corners as the tiles', alike on every tile. ECharts gives a tile's label a box of the tile's + * size and lays rich text out from the box's top. With `tileOf` (the tiles of a first draw) each label + * writes what fits its tile, in the tile's middle: the name cut short with ELLIPSIS (fitText), the + * lines after it whole or not at all (a number cut short would mislead), as many lines as plates fit + * the tile's height. A tile without room for TILE_MIN_CHARS characters or one line writes no label: the + * tooltip has it. Without `tileOf` the labels stand on plates at the top, ECharts cutting them. Without + * a background colour it can draw (--pk-surface missing, or `readColor` cannot read it), no plates: + * each label in the ink that reads on its tile (inkedLabel). + * @param {any} s the treemap's series + * @param {{ text?: string, surface?: string, radius: number, fontSize: number, readColor?: (color: string) => string | null, tileOf?: (index: number, name: string) => { width: number, height: number } | null }} theme + * @returns {{ label: any, data?: any[] }} + */ +function treemapLabels(s, { text, surface, radius, fontSize, readColor, tileOf }) { + const label = s.label; + const plate = surface && readColor ? readColor(surface) : surface; + const inks = /** @type {string[]} */ ([text, plate].filter((c) => typeof c === "string" && c !== "")); + if (typeof label?.formatter !== "function" || !plate) { + return { label: inkedLabel(label, inks, readColor) }; + } + const format = label.formatter; + // no --pk-text: ECharts' own text colour + const ink = text || undefined; + const line = plateLine(fontSize); + const out = { + label: { + ...label, + color: ink, + formatter: (/** @type {any} */ p) => styled("plate", format(p)), + rich: { plate: { fontSize, lineHeight: line, color: ink, backgroundColor: plate, borderRadius: radius, padding: [Math.max(1, (line - fontSize * 1.2) / 2), PLATE_SIDE] } } + } + }; + if (!tileOf || !Array.isArray(s.data)) return out; + const pad = TILE_LABEL_PADDING; + return { + ...out, + data: s.data.map((/** @type {any} */ d, /** @type {number} */ i) => { + const tile = tileOf(i, d.name); + if (!tile) return d; + const width = tile.width - 2 * pad - 2 * PLATE_SIDE; + // above and below the lines only TILE_EDGE: a tile a line tall keeps its label (the sides keep `pad`) + const height = tile.height - 2 * TILE_EDGE; + const [first, ...rest] = String(format(d)).split("\n"); + const name = fitText(first, width, fontSize); + const shown = name === null ? [] : [name, ...rest.filter((t) => textWidth(t, fontSize) <= width)].slice(0, Math.floor(height / line)); + if (!shown.length) return { ...d, label: { ...d.label, show: false } }; + const top = (tile.height - shown.length * line) / 2; + const words = styled("plate", shown.join("\n")); + return { ...d, label: { ...d.label, padding: [top, pad, 0, pad], formatter: () => words } }; + }) + }; +} + +/** + * A heatmap's numbers in the ink that reads on their cell (labelColorOn on the colour ECharts drew it + * in): one rich style per ink, so the cells keep their data as they are. + * @param {any} label the series' label + * @param {string[]} inks the theme's text and background colours + * @param {((color: string) => string | null) | undefined} readColor + */ +function inkedLabel(label, inks, readColor) { + if (!inks.length || typeof label?.formatter !== "function") { + return { ...label, color: inks[0] }; + } + const format = label.formatter; + const all = [...inks, ...EXTREME_INKS]; + const keyOf = (/** @type {unknown} */ fill) => `ink${all.indexOf(inkOn(fill, inks, readColor))}`; + return { + ...label, + color: inks[0], + formatter: (/** @type {any} */ p) => styled(keyOf(p.color), format(p)), + rich: Object.fromEntries(all.map((c, i) => [`ink${i}`, { color: c }])) + }; +} + /** * A heatmap's colours as ECharts can mix them. ECharts works out each cell's colour from the scale's * ends itself, and its parser reads hex, rgb(), hsl() and some names only: any other colour (oklch(), @@ -40,15 +187,49 @@ function heatmapColors(colors, readColor) { return colors.map((c, i) => readColor(String(c)) ?? fallback[i === 0 ? 0 : fallback.length - 1]); } -/** A chart narrower than this writes a reference line's name alone, without its value. */ +/** A chart narrower than this writes the reference lines' names before their values only where they fit (briefWords). */ const LINE_VALUE_MIN_WIDTH = 480; +/** On a narrow chart, the share of its width a reference line's label may take with its name. */ +const LINE_WORDS_SHARE = 0.3; /** Room (px) between the plot and a reference line's label right of it. */ const LINE_LABEL_GAP = 6; -/** A reference line's markLine item with its label writing the line's name alone, after its sample. */ -const namesOnly = (/** @type {any} */ d) => { +/** The words of a reference line's label, without its sample: its name and value (a trend's name). */ +const wordsOf = (/** @type {any} */ item) => String(item.label.formatter()).replace(/^\{s\|[^}]*\} /, ""); + +/** + * The words of reference lines' labels on a chart `width` px wide (narrower than LINE_VALUE_MIN_WIDTH), + * by line: each its name and value where every label with its sample takes at most LINE_WORDS_SHARE of + * the width, else each its value alone (`brief`; a trend its name). All or none, so the labels read + * alike. Without the names the samples' dashes tell the kinds. + * @param {any[]} items the lines' markLine items (their first point for a trend) + * @param {number} width + * @param {number} fontSize + * @returns {Map} + */ +function briefWords(items, width, fontSize) { + const sampleOf = (/** @type {any} */ item) => LINE_SAMPLES[/** @type {keyof typeof LINE_SAMPLES} */ (item.lineStyle?.type)] ?? ""; + const named = items.every((item) => textWidth(`${sampleOf(item)} ${wordsOf(item)}`, fontSize) <= width * LINE_WORDS_SHARE); + return new Map(items.map((item) => [item, named ? wordsOf(item) : String(item.brief ?? item.name ?? "")])); +} + +/** + * The reference lines of upright lines (horizontal bars) on a narrow chart: each label with the words + * briefWords gives, its line's name where every label fits, else the value. + * @param {any[]} series + * @param {number} width + * @param {number} fontSize + */ +function uprightWords(series, width, fontSize) { + const head = (/** @type {any} */ d) => (Array.isArray(d) ? d[0] : d); + const brief = briefWords(series.flatMap((s) => (s.markLine?.data ?? []).map(head)), width, fontSize); + return series.map((s) => (s.markLine ? { ...s, markLine: { ...s.markLine, data: s.markLine.data.map((/** @type {any} */ d) => withWords(d, /** @type {string} */ (brief.get(head(d))))) } } : s)); +} + +/** A reference line's markLine item with its label writing `words` after its sample. */ +const withWords = (/** @type {any} */ d, /** @type {string} */ words) => { const head = Array.isArray(d) ? d[0] : d; - const label = { ...head.label, formatter: () => lineLabelText(head.lineStyle?.type, head.name ?? "") }; + const label = { ...head.label, formatter: () => lineLabelText(head.lineStyle?.type, words) }; return Array.isArray(d) ? [{ ...head, label }, d[1]] : { ...head, label }; }; @@ -59,7 +240,8 @@ const namesOnly = (/** @type {any} */ d) => { * after a first draw): the labels then sit at their lines. Without it the heights are estimated on a * scale at most as fine as ECharts' (it never stretches the values over less than half the axis, nor * the plot over less than about half the chart), so the labels end at least as far apart as - * estimated. A chart narrower than LINE_VALUE_MIN_WIDTH writes the names alone, and leaves out a + * estimated. A chart narrower than LINE_VALUE_MIN_WIDTH writes the lines' names only where they fit + * (briefWords), and leaves out a * label that would sit more than one and a half lines from its line; the tooltip has every value. A * trend on bars ends at the middle of the last bar: its label moves right by half a bar's band. * @param {any[]} series the decorated series @@ -82,7 +264,9 @@ function lineLabels(series, { width, height, grid, fontSize, pixelOf }) { } const narrow = width < LINE_VALUE_MIN_WIDTH; // the widest label: its sample, a space and its words - const textOf = (/** @type {any} */ item) => `${LINE_SAMPLES[/** @type {keyof typeof LINE_SAMPLES} */ (item.lineStyle?.type)] ?? ""} ${narrow ? String(item.name ?? "") : String(item.label.formatter()).replace(/^\{s\|[^}]*\} /, "")}`; + /** @type {Map} the words of each label on a narrow chart */ + const brief = narrow ? briefWords(labels.map((l) => l.item), width, fontSize) : new Map(); + const textOf = (/** @type {any} */ item) => `${LINE_SAMPLES[/** @type {keyof typeof LINE_SAMPLES} */ (item.lineStyle?.type)] ?? ""} ${brief.get(item) ?? wordsOf(item)}`; const widest = Math.max(...labels.map((l) => textWidth(textOf(l.item), fontSize))); // without the real heights: the values' span (the data, a stack's tops, 0 and the lines) on a coarse scale const numbers = series.flatMap((s) => (s.data ?? []).filter((/** @type {unknown} */ v) => typeof v === "number")); @@ -120,7 +304,7 @@ function lineLabels(series, { width, height, grid, fontSize, pixelOf }) { const far = narrow && dy > line * 1.5; const label = { ...head.label, offset: [l.trend ? band : 0, dy], ...(far ? { show: false } : {}) }; const item = Array.isArray(d) ? [{ ...head, label }, d[1]] : { ...head, label }; - return narrow ? namesOnly(item) : item; + return narrow ? withWords(item, /** @type {string} */ (brief.get(head))) : item; }) } } @@ -138,7 +322,7 @@ function lineLabels(series, { width, height, grid, fontSize, pixelOf }) { * @param {{ height?: number, width?: number, categoryNames?: string[], axisLabels?: string, * tooltipFormatter?: (context: { valueFormatter?: (v: unknown) => string, shareFormatter?: (v: number) => string, xNames?: string[], yNames?: string[], categoryNames?: string[] }) => unknown, * readColor?: (color: string) => string | null, zoom?: string, zoomAt?: { start: number, end: number }, timeline?: boolean, touch?: boolean, - * pixelOf?: (value: number) => number }} [size] + * pixelOf?: (value: number) => number, tileOf?: (index: number, name: string) => { width: number, height: number } | null }} [size] * height and width: the chart's size in px (the room around a pie, a heatmap's column names, the * category axis); categoryNames: the categories' whole names (the tooltip's title when the axis * writes them shorter); axisLabels: the view's chart.axisLabels; tooltipFormatter: builds the @@ -148,10 +332,11 @@ function lineLabels(series, { width, height, grid, fontSize, pixelOf }) { * the slider's window from before; timeline: the categories run along a time line (the first window * shows the latest); touch: a finger points (the slider takes --pk-target-touch); pixelOf: a value's * height in the drawn chart (ECharts' convertToPixel after a first draw), so the labels of the - * reference lines sit at their lines (lineLabels) + * reference lines sit at their lines (lineLabels); tileOf: a treemap's tile in the drawn chart by + * its item (drawnTiles), so each label stands in its tile's middle (treemapLabels) * @returns {any} the option; `axisEvery` (not ECharts') is n when the category axis writes every n-th label */ -export function decorateOption(option, style, { height = 480, width = 800, categoryNames, axisLabels, tooltipFormatter, readColor, zoom, zoomAt, timeline = false, touch = false, pixelOf } = {}) { +export function decorateOption(option, style, { height = 480, width = 800, categoryNames, axisLabels, tooltipFormatter, readColor, zoom, zoomAt, timeline = false, touch = false, pixelOf, tileOf } = {}) { const extra = { categoryNames, axisLabels }; const first = (a) => (Array.isArray(a) ? a[0] : a); const v = (name) => style.getPropertyValue(name).trim(); @@ -230,29 +415,19 @@ export function decorateOption(option, style, { height = 480, width = 800, categ return { ...s, top, bottom, ...fit, labelLine: fit.labelLine ?? line, itemStyle: { ...s.itemStyle, borderColor: surface, borderWidth: 2, borderRadius: r }, label: { ...label, color: label?.position === "inside" ? undefined : v("--pk-text") || undefined } }; } if (s.type === "treemap") { - // each tile's label in the token that reads best on it, --pk-text or --pk-surface (one is - // dark, one light in every theme); the tiles parted by the background's colour - const inks = [v("--pk-text"), surface].filter((c) => typeof c === "string" && c !== ""); - const label = (/** @type {string | undefined} */ fill) => { - const read = fill && readColor ? (readColor(fill) ?? fill) : fill; - const color = read && inks.length ? labelColorOn(read, inks) : inks[0]; - // a tile on which neither reaches the contrast text needs (a mid blue): the label gets an - // outline in the other token, so it reads against that - const ratio = read && color ? contrastOf(read, color) : null; - const other = inks.find((c) => c !== color); - return { color, ...(ratio !== null && ratio < TEXT_CONTRAST && other ? { textBorderColor: other, textBorderWidth: 2 } : {}) }; - }; + // each label on a plate (treemapLabels); the tiles parted by the background's colour return { ...s, itemStyle: { ...s.itemStyle, borderColor: surface, borderRadius: cell }, - data: (s.data ?? []).map((/** @type {any} */ d) => ({ ...d, label: { ...d.label, ...label(d.itemStyle?.color) } })) + ...treemapLabels(s, { text: v("--pk-text"), surface, radius: cell, fontSize, readColor, tileOf }) }; } if (s.type === "heatmap") { // numbers only in cells large enough for them (heatmapCellLabels); the tooltip has every one const texts = typeof s.label?.formatter === "function" ? s.data.map((/** @type {any} */ d) => s.label.formatter({ value: d })) : []; const fits = heatmapCellLabels(option.xAxis?.data?.length ?? 1, option.yAxis?.data?.length ?? 1, width, height, texts, fontSize, cellFrame); - return { ...s, itemStyle: { borderColor: surface, borderWidth: 2, borderRadius: cell }, label: { ...s.label, show: Boolean(s.label?.show) && fits, color: v("--pk-text") || undefined } }; + const inks = [v("--pk-text"), surface].filter((c) => typeof c === "string" && c !== ""); + return { ...s, itemStyle: { borderColor: surface, borderWidth: 2, borderRadius: cell }, label: { ...inkedLabel(s.label, inks, readColor), show: Boolean(s.label?.show) && fits } }; } return s; }); @@ -262,8 +437,8 @@ export function decorateOption(option, style, { height = 480, width = 800, categ if (grid) grid.right += valueLabelRoom(series, fontSize); // the labels of lying reference lines: right of the plot, kept apart, with room const lines = grid && first(option.yAxis)?.type === "value" ? lineLabels(series, { width, height, grid, fontSize, pixelOf }) : null; - // upright lines (horizontal bars) have a row each above the plot; a narrow chart writes their names alone - if (grid && !lines && width < LINE_VALUE_MIN_WIDTH) series = series.map((s) => (s.markLine ? { ...s, markLine: { ...s.markLine, data: s.markLine.data.map(namesOnly) } } : s)); + // upright lines (horizontal bars) have a row each above the plot; a narrow chart writes their names where they fit + if (grid && !lines && width < LINE_VALUE_MIN_WIDTH) series = uprightWords(series, width, fontSize); if (lines) { grid.right += lines.room; series = lines.series; @@ -271,7 +446,7 @@ export function decorateOption(option, style, { height = 480, width = 800, categ // the labels of the high and low points: inside the plot (the value axis reaches past them) and apart const horizontalBars = first(option.yAxis)?.type === "category"; const valueKey = horizontalBars ? "xAxis" : "yAxis"; - const points = grid ? pointLabels(series, { width, height, grid, fontSize, horizontal: horizontalBars, axis: first(option[valueKey]), pixelOf }) : null; + const points = grid ? pointLabels(series, { width, height, grid, fontSize, horizontal: horizontalBars, axis: first(option[valueKey]), pixelOf, legend: option.legend }) : null; /** @type {Record} */ const reach = {}; if (points) { diff --git a/packages/pivotkit-core/src/chart.js b/packages/pivotkit-core/src/chart.js index b340da76b..d3f0651f7 100644 --- a/packages/pivotkit-core/src/chart.js +++ b/packages/pivotkit-core/src/chart.js @@ -347,7 +347,7 @@ export function toEChartsOption(result, options) { const showValues = labels !== "auto" && labels !== "off"; const position = type === "line" ? "top" : stacked ? "inside" : chart.horizontal && !combo ? "right" : "top"; const valueLabel = showValues ? { label: { show: true, position, color: theme.textColor, formatter: (p) => (typeof p.value === "number" ? (percent ? shareFormatter(p.value) : fmt(p.value)) : "") } } : {}; - const marks = markLines(referenceLines(result, { chart, series: s, words: options.labels?.referenceLines, locale: options.locale }), s, { horizontal: Boolean(chart.horizontal), theme, short: (v) => compact(v), hidden: Array.isArray(chart.hidden) ? chart.hidden : [] }); + const marks = markLines(referenceLines(result, { chart, series: s, words: options.labels?.referenceLines, locale: options.locale }), s, { horizontal: Boolean(chart.horizontal), theme, colorOf, short: (v) => compact(v), hidden: Array.isArray(chart.hidden) ? chart.hidden : [] }); const points = markPoints(extremePoints(result, { chart, series: s, locale: options.locale }), s, { type, horizontal: Boolean(chart.horizontal), theme, colorOf, raised: showValues && !stacked, hidden: Array.isArray(chart.hidden) ? chart.hidden : [] }); // the value axis reaches every line: a target past the tallest bar is drawn, not cut off. // dataMin and dataMax are ECharts' own (ECharts 6, scaleRawExtentInfo: they widen the data's @@ -410,15 +410,16 @@ const LABEL_GAP = 6; * drawn above every mark, in the theme's reference colour. Silent: a line is no element to point at; the * tooltip names its value. A trend is drawn from category to category, at its value at each: over * real time with a gap it bends where the axis leaves the gap out. A label writes the name and the - * value as the value axis does (`short`); each item's `name` is the line's name alone, for a chart too - * narrow for the value. `extent`: the lowest and highest value of the lines, for the value axis; + * value as the value axis does (`short`); each item's `brief` is what a chart too narrow for both + * writes: the value, a trend's name. `extent`: the lowest and highest value of the lines, for the value axis; * `room`: the height (px) the labels of upright lines take above the plot. * @param {import("./chart-lines.js").ReferenceLine[]} lines * @param {ReturnType} s - * @param {{ horizontal: boolean, theme: ChartTheme, short: (v: number) => string, hidden: string[] }} how - * hidden: the series the legend hides (chart.hidden); ECharts hides a series' markLine with it + * @param {{ horizontal: boolean, theme: ChartTheme, colorOf: (name: string, i: number) => string | null, short: (v: number) => string, hidden: string[] }} how + * colorOf: a series' fixed colour (chart.colors, colorMap); hidden: the series the legend hides + * (chart.hidden); ECharts hides a series' markLine with it */ -function markLines(lines, s, { horizontal, theme, short, hidden }) { +function markLines(lines, s, { horizontal, theme, colorOf, short, hidden }) { /** @type {any[][]} */ const bySeries = s.series.map(() => []); // the lines of no series go on the last series shown; with none shown, nowhere @@ -437,12 +438,17 @@ function markLines(lines, s, { horizontal, theme, short, hidden }) { // line starts at the top), the first row nearest to it; lying ones right of the plot const where = horizontal ? { position: "start", distance: [0, LABEL_GAP + rows * (fontSize + LABEL_GAP)] } : { position: "end", distance: LABEL_GAP }; rows += 1; - // the line's colour: its series' (the palette's, as ECharts picks it), else the reference colour + // the line's colour: its series' (a fixed one, else the palette's, as ECharts picks it), else the + // reference colour const colors = theme.colors ?? []; - const color = own ? colors[/** @type {number} */ (line.series) % Math.max(1, colors.length)] : (theme.referenceColor ?? theme.textColor); + const place = /** @type {number} */ (line.series); + const color = own ? (colorOf(own.name, place) ?? colors[place % Math.max(1, colors.length)]) : (theme.referenceColor ?? theme.textColor); const type = LINE_TYPES[line.kind]; const style = { name: line.name, + // what a chart too narrow for the whole label writes (decorateOption): the value, which tells + // one series' average from another's (the sample says the kind and the series); a trend's name + brief: line.kind === "trend" ? line.name : short(/** @type {number} */ (line.value)), lineStyle: { type, width: 1.5, ...(own ? {} : { color }) }, // the words in the text colour, after a sample of the line's dash in its colour label: { formatter: () => lineLabelText(type, text), rich: { s: { ...(color ? { color } : {}), fontSize } }, ...where, color: theme.textColor, fontSize } @@ -477,9 +483,9 @@ export const POINT_GLYPHS = Object.freeze({ max: "\u25B2", min: "\u25BC" }); /** * The high and low points as ECharts markPoint data, by the series that draws them: a series' own on * it; a stack's total's on the last series shown, in the theme's reference colour. Each is a dot in its - * series' colour (chart.colors, colorMap, else the palette's) and a label: the glyph (▲, ▼) in that - * colour, the value in the text colour, which reads on every background (a palette colour such as - * yellow does not, as text). A line's highest label goes above its dot, its lowest below; a bar's past + * series' colour (chart.colors, colorMap, else the palette's) and a label in the text colour: the + * glyph (▲, ▼) and the value. A series' colour may be a light grey or yellow, which does not read as + * text (#913); the dot says which series it is. A line's highest label goes above its dot, its lowest below; a bar's past * its end, where nothing else is drawn, above any value label there (`raised`). decorateOption keeps * the labels inside the plot and apart. * @param {import("./chart-lines.js").ExtremePoint[]} points @@ -514,7 +520,7 @@ function markPoints(points, s, { type, horizontal, theme, colorOf, raised, hidde position, distance: raised && !below ? fontSize + 10 : 6, formatter: () => `{s|${POINT_GLYPHS[p.kind]}} ${label}`, - rich: { s: { ...(color ? { color } : {}), fontSize } }, + rich: { s: { fontSize } }, color: theme.textColor, fontSize } diff --git a/packages/pivotkit-core/src/defaults.js b/packages/pivotkit-core/src/defaults.js index 9b2398099..8feb83fa0 100644 --- a/packages/pivotkit-core/src/defaults.js +++ b/packages/pivotkit-core/src/defaults.js @@ -29,6 +29,12 @@ export const DEFAULT_THEME = Object.freeze({ donutRadius: Object.freeze(["42%", "70%"]) }); +/** + * Black and white: the inks text on a coloured fill falls back to where neither of the theme's reaches + * 4.5:1 on it (labelColorOn). No theme sets them: one of the two always reaches 4.58:1 on an opaque colour. + */ +export const EXTREME_INKS = Object.freeze(/** @type {const} */ (["#000000", "#ffffff"])); + /** * The colour scales a report builder picks in the value menu (Highlight › Colour scale), low to high, * as a view's `conditional.colors`. The theme's own scale (light to dark in its accent) has no colours. diff --git a/packages/pivotkit-core/test/api.test.js b/packages/pivotkit-core/test/api.test.js index 3b6df7eca..51645daa3 100644 --- a/packages/pivotkit-core/test/api.test.js +++ b/packages/pivotkit-core/test/api.test.js @@ -22,7 +22,7 @@ test("the package exports its documented entry points and nothing else", () => { ]); assert.deepEqual(Object.keys(exporters).sort(), ["dataToCsv", "dataToCsvBytes", "dataToCsvParts", "dataToJson", "isDataAsOf", "rowsToCsv", "rowsToCsvBytes", "rowsToXlsx", "scaleColor", "toCsv", "toCsvBytes", "toJson", "toTsv", "toXlsx"]); assert.deepEqual(Object.keys(charts).sort(), [ - "BOTTOM_LEGEND_ROOM", "CATEGORY_LABEL_WIDTH", "GROUP_LABEL_ROOM", "RIGHT_LEGEND_MIN_WIDTH", "SLANTED_LABEL_WIDTH", "categoryLabelLayout", "categoryLabelWidth", "columnLabelLayout", "decorateOption", "extremePoints", "groupLabelsFit", "heatmapCellLabels", "labelColorOn", "pieLabelRoom", "referenceLineChecks", "referenceLines", "ringLabelsFit", "rowLabelInterval", "toEChartsOption" + "BOTTOM_LEGEND_ROOM", "CATEGORY_LABEL_WIDTH", "GROUP_LABEL_ROOM", "RIGHT_LEGEND_MIN_WIDTH", "SLANTED_LABEL_WIDTH", "categoryLabelLayout", "categoryLabelWidth", "columnLabelLayout", "decorateOption", "drawnTiles", "extremePoints", "groupLabelsFit", "heatmapCellLabels", "labelColorOn", "pieLabelRoom", "referenceLineChecks", "referenceLines", "ringLabelsFit", "rowLabelInterval", "toEChartsOption" ]); assert.deepEqual(Object.keys(links).sort(), ["LINK_ISSUE_CODES", "LINK_LIMITS", "decodeViewLink", "encodeViewLink", "linkFragment", "linkParam", "readViewLink", "withLinkFragment"]); assert.deepEqual(Object.keys(templates).sort(), ["TEMPLATES_EXTENSION", "TEMPLATE_LIMITS", "parseTemplates", "templatesFromSchema"]); diff --git a/packages/pivotkit-core/test/chart/extremes.test.js b/packages/pivotkit-core/test/chart/extremes.test.js index 90e3dd210..00f2ba46d 100644 --- a/packages/pivotkit-core/test/chart/extremes.test.js +++ b/packages/pivotkit-core/test/chart/extremes.test.js @@ -119,17 +119,18 @@ test("the ECharts option: a silent markPoint per series, a dot in its colour, assert.deepEqual(a.markPoint.data.map((d) => text(d.label)), ["▲ 40", "▼ 10"]); assert.deepEqual(a.markPoint.data.map((d) => d.label.position), ["top", "bottom"]); assert.deepEqual(b.markPoint.data.map((d) => text(d.label)), ["▲ 7", "▼ 3"]); - // the dot and the glyph in the series' colour; the number in the text colour, which reads on - // every background (a palette colour such as yellow does not, as text) + // the dot in the series' colour; the glyph and the number in the text colour, which reads on every + // background (a series' colour such as a light grey or yellow does not, as text: #913) assert.equal(a.markPoint.data[0].itemStyle.color, "#111111"); assert.equal(b.markPoint.data[0].itemStyle.color, "#222222"); - assert.equal(b.markPoint.data[0].label.rich.s.color, "#222222"); + assert.equal(b.markPoint.data[0].label.rich.s.color, undefined, "the glyph takes the label's colour"); assert.equal(a.markPoint.data[0].label.color, "#333333"); assert.equal(a.markPoint.data[0].label.fontSize, 15); - // a fixed colour (chart.colors) wins over the palette, for the dot and the glyph + // a fixed colour (chart.colors) wins over the palette for the dot; the label keeps the text colour const fixed = toEChartsOption(pivot({ chart: { type: "line", colors: [{ name: "B", color: "#abcdef" }], referenceLines: ON } }), { theme }); assert.equal(fixed.series[1].markPoint.data[0].itemStyle.color, "#abcdef"); - assert.equal(fixed.series[1].markPoint.data[0].label.rich.s.color, "#abcdef"); + assert.equal(fixed.series[1].markPoint.data[0].label.rich.s.color, undefined); + assert.equal(fixed.series[1].markPoint.data[0].label.color, "#333333"); // nothing switched on: no markPoint assert.equal(toEChartsOption(pivot({ chart: { type: "line" } })).series[0].markPoint, undefined); }); @@ -203,6 +204,75 @@ test("decorateOption: two labels at one category that would cover each other mov assert.deepEqual(lows(far).map((d) => d.label.position), ["bottom", "bottom"]); }); +test("decorateOption: grouped bars (#913): a point's label stands over its own bar and never across a taller neighbour", () => { + const style = { getPropertyValue: () => "" }; + // three teams side by side per month; A's high (50,000) between a taller B (100,000) and nothing + const rows = encode([ + { Month: "m1", Team: "A", N: 50_000 }, + { Month: "m1", Team: "B", N: 100_000 }, + { Month: "m1", Team: "C", N: 10_000 }, + { Month: "m2", Team: "A", N: 20_000 }, + { Month: "m2", Team: "B", N: 30_000 }, + { Month: "m2", Team: "C", N: 40_000 } + ]); + const r = computePivot(rows, { rows: ["Month"], cols: ["Team"], values: [{ field: "N", agg: "sum" }], sort: [], formatting: { locale: "en-US" }, chart: { type: "bar", referenceLines: ON } }); + const highOf = (option, i) => option.series[i].markPoint.data.find((d) => d.name === "max"); + const out = decorateOption(toEChartsOption(r), style, { width: 360, height: 300 }); + // above A's bar the label would run across B's taller bar, beside it too: left out, the dot stays + assert.equal(highOf(out, 0).label.show, false, JSON.stringify(highOf(out, 0).label)); + // B's high is the tallest bar: its label stays above it + assert.notEqual(highOf(out, 1).label.show, false); + // one column of bars (stacked) has no neighbours to avoid + const stacked = decorateOption(toEChartsOption(computePivot(rows, { rows: ["Month"], cols: ["Team"], values: [{ field: "N", agg: "sum" }], sort: [], chart: { type: "bar", stacked: true, referenceLines: ON } })), style, { width: 360, height: 300 }); + assert.ok(stacked.series.some((s) => (s.markPoint?.data ?? []).some((d) => d.label.show !== false))); +}); + +test("decorateOption: grouped bars (#913): a label with no room over its bar or beside its dot stands over its group's highest bar", () => { + const style = { getPropertyValue: () => "" }; + // A's high (50,000) next to a taller B (90,000) in m1; B's own high is in m2, so m1's group has room above + const rows = encode([ + { Month: "m1", Team: "A", N: 50_000 }, + { Month: "m1", Team: "B", N: 90_000 }, + { Month: "m1", Team: "C", N: 10_000 }, + { Month: "m2", Team: "A", N: 20_000 }, + { Month: "m2", Team: "B", N: 100_000 }, + { Month: "m2", Team: "C", N: 40_000 } + ]); + const r = computePivot(rows, { rows: ["Month"], cols: ["Team"], values: [{ field: "N", agg: "sum" }], sort: [], formatting: { locale: "en-US" }, chart: { type: "bar", referenceLines: ON } }); + // the real heights: 100,000 at 50 px, 0 at 250 px + const pixelOf = (v) => 250 - v * 0.002; + const out = decorateOption(toEChartsOption(r), style, { width: 360, height: 300, pixelOf }); + const label = out.series[0].markPoint.data.find((d) => d.name === "max").label; + assert.notEqual(label.show, false, JSON.stringify(label)); + assert.equal(label.position, "top"); + // moved up from A's top (150 px): the label's foot (its distance above the 5 px dot) above B's top (70 px) + assert.ok(150 - 5 - label.distance + label.offset[1] <= pixelOf(90_000), JSON.stringify(label)); +}); + +test("decorateOption: dense grouped bars (#913): the chart's highest and lowest label are placed first, before the other series' labels take their room", () => { + const style = { getPropertyValue: () => "" }; + // three series over six months; the chart's lowest (13) and highest (100) are B's, the second series + const values = { A: [40, 89, 84, 34, 91, 65], B: [31, 60, 13, 100, 73, 57], C: [51, 68, 22, 22, 99, 78] }; + const rows = encode(Object.entries(values).flatMap(([Team, list]) => list.map((N, i) => ({ Month: `m${i + 1}`, Team, N })))); + const r = computePivot(rows, { rows: ["Month"], cols: ["Team"], values: [{ field: "N", agg: "sum" }], sort: [], formatting: { locale: "en-US" }, chart: { type: "bar", referenceLines: ON } }); + const out = decorateOption(toEChartsOption(r), style, { width: 360, height: 300 }); + const shown = out.series.flatMap((s) => (s.markPoint?.data ?? []).filter((d) => d.label.show !== false).map((d) => text(d.label))); + assert.ok(shown.includes("▲ 100") && shown.includes("▼ 13"), shown.join(", ")); + // lossy: not every label has room + assert.ok(shown.length < 6, shown.join(", ")); +}); + +test("decorateOption: lines keep the series' order, so close lows move apart instead of a label left out", () => { + const style = { getPropertyValue: () => "" }; + // three years of monthly temperatures: the lows of January and February close together + const values = { 2023: [4.1, 2.8, 5.5, 7.7, 14, 19.4, 20.1, 19.6, 18.9, 12.1, 5.5, 3.6], 2024: [1.2, 6.6, 7.6, 10.9, 16.9, 18, 20.4, 21.4, 17.5, 11.5, 5.4, 3.8], 2025: [2.3, 0.6, 6.2, 12, 13.9, 19.7, 19.6, 18.9, 15.7, 10.3, 5.2, 3.1] }; + const rows = encode(Object.entries(values).flatMap(([Year, list]) => list.map((T, i) => ({ Month: `m${String(i + 1).padStart(2, "0")}`, Year, T })))); + const r = computePivot(rows, { rows: ["Month"], cols: ["Year"], values: [{ field: "T", agg: "sum", format: "number:1" }], sort: [], formatting: { locale: "en-US" }, chart: { type: "line", referenceLines: ON } }); + const out = decorateOption(toEChartsOption(r), style, { width: 1080, height: 420 }); + const shown = out.series.flatMap((s) => (s.markPoint?.data ?? []).filter((d) => d.label.show !== false).map((d) => text(d.label))); + assert.deepEqual(shown.sort(), ["▲ 20.1", "▲ 21.4", "▲ 19.7", "▼ 0.6", "▼ 1.2", "▼ 2.8"].sort()); +}); + test("decorateOption: a label reads over a line it crosses, outlined in the background's colour", () => { const style = { getPropertyValue: (name) => (name === "--pk-surface" ? "#101418" : "") }; const out = decorateOption(toEChartsOption(pivot({ chart: { type: "line", referenceLines: ON } })), style, { width: 800, height: 480 }); diff --git a/packages/pivotkit-core/test/chart/fill-labels.test.js b/packages/pivotkit-core/test/chart/fill-labels.test.js new file mode 100644 index 000000000..7214dd65a --- /dev/null +++ b/packages/pivotkit-core/test/chart/fill-labels.test.js @@ -0,0 +1,182 @@ +// Text on coloured fills (#913, #914), in both themes: a treemap's labels on plates, a heatmap's +// numbers in the ink that reads on their cell, the labels of high and low points and reference lines in +// the text colour. Every label reaches 4.5:1 on what is under it (tests/fill-contrast.js). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chartThemeFrom, computePivot, encode, toEChartsOption } from "pivotkit-core"; +import { decorateOption, drawnTiles, labelColorOn } from "pivotkit-core/chart"; +import { THEME_TOKENS, contrastOnFill, fillContrasts, unreadable } from "../../../../tests/fill-contrast.js"; +import { MONTH, MONTHLY, REVENUE } from "./fixtures.js"; + +/** Eight regions, one tile each: every colour of the palette. */ +const REGIONS = encode(["Central", "West", "North", "South", "East", "Alps", "Coast", "Islands"].map((Region, i) => ({ Region, Revenue: 4000 - i * 380 }))); +/** A host's palette with a light grey and a near black next to the theme's colours. */ +const HOST = { Central: "#d9d9d9", West: "#1f1f1f", North: "#9ecbff" }; +const PALETTE = (/** @type {Readonly>} */ tokens) => Array.from({ length: 8 }, (_, i) => tokens[`--pk-chart-${i + 1}`]); + +/** The option a report draws in a theme: the core's option and the report's marks, from the tokens. */ +const drawn = (/** @type {any} */ r, /** @type {any} */ style, /** @type {object} */ options = {}, width = 800) => decorateOption(toEChartsOption(r, { theme: chartThemeFrom(style), ...options }), style, { width, height: 480 }); + +test("labelColorOn: the theme's ink that reads best; where neither reaches 4.5:1, black or white", () => { + const dark = "#1a1d23"; + const light = "#ffffff"; + assert.equal(labelColorOn("#eda100", [dark, light]), dark, "dark text on yellow"); + assert.equal(labelColorOn("#6250d6", [dark, light]), light, "light text on violet"); + assert.equal(labelColorOn("rgb(237, 161, 0)", [dark, light]), dark); + // a mid blue: dark text 3.8:1, white 4.4:1; black reaches 4.8:1 + assert.equal(labelColorOn("#2a78d6", [dark, light]), "#000000"); + // a colour it cannot read: the first token + assert.equal(labelColorOn("oklch(0.5 0.1 200)", [dark, light]), dark); + // every colour of both themes' palettes, and the host's, takes an ink that reaches 4.5:1 + const measured = fillContrasts((_, tokens) => { + const inks = [tokens["--pk-text"], tokens["--pk-surface"]]; + return [...PALETTE(tokens), ...Object.values(HOST)].map((fill) => ({ name: fill, ink: labelColorOn(fill, inks), fill })); + }); + assert.deepEqual(unreadable(measured), []); +}); + +test("treemap, both themes: every label on a plate in the background colour, the same on every tile; 4.5:1 on it", () => { + const r = computePivot(REGIONS, { rows: ["Region"], values: [{ field: "Revenue", agg: "sum" }], chart: { type: "treemap" }, formatting: { locale: "en-US" } }); + for (const colorMap of [undefined, HOST]) { + const measured = fillContrasts((style) => { + const [s] = drawn(r, style, colorMap ? { colorMap } : {}).series; + // one look: no tile has a label colour or an outline of its own + assert.deepEqual(s.data.filter((/** @type {any} */ d) => d.label), []); + assert.equal(s.label.textBorderWidth, undefined); + const plate = s.label.rich.plate; + assert.equal(s.label.formatter({ name: "North", value: 3240 }), "{plate|North}\n{plate|3,240}"); + return [{ name: `plate${colorMap ? " (host colours)" : ""}`, ink: plate.color, fill: plate.backgroundColor }]; + }); + assert.deepEqual(unreadable(measured), []); + assert.deepEqual(measured.map((m) => [m.theme, m.ink, m.fill]), [ + ["light", THEME_TOKENS.light["--pk-text"], THEME_TOKENS.light["--pk-surface"]], + ["dark", THEME_TOKENS.dark["--pk-text"], THEME_TOKENS.dark["--pk-surface"]] + ]); + } + // a "}" in a name would end the plate's text in ECharts' markup: it stands between two runs of it + const [s] = drawn(r, { getPropertyValue: (/** @type {string} */ n) => THEME_TOKENS.light[n] ?? "" }).series; + assert.equal(s.label.formatter({ name: "A}B", value: 1 }), "{plate|A}}{plate|B}\n{plate|1}"); +}); + +test("treemap with the tiles of a first draw (tileOf): each label on a plate in its tile's middle, cut to the tile with an ellipsis; none where fewer than 4 characters fit", () => { + const r = computePivot(REGIONS, { rows: ["Region"], values: [{ field: "Revenue", agg: "sum" }], chart: { type: "treemap" }, formatting: { locale: "en-US" } }); + const style = { getPropertyValue: (/** @type {string} */ n) => THEME_TOKENS.light[n] ?? "" }; + /** @type {Record} */ + const tiles = { + Central: { width: 300, height: 200 }, + // 30 px wide: not even "Wes…" fits + West: { width: 30, height: 60 }, + // 20 px tall: no line fits; 23 px: one does, with a pixel above and below + North: { width: 300, height: 20 }, + South: { width: 300, height: 23 }, + // 56 px wide and 40 px tall: "Isla…" fits, the value "1,340" too, but a line only + Islands: { width: 56, height: 40 }, + // 50 px wide: "Coa…" would fit, but a name cut to 3 characters is a stub: no label + Coast: { width: 50, height: 60 } + }; + /** @type {Array<[number, string]>} */ + const asked = []; + const tileOf = (/** @type {number} */ i, /** @type {string} */ name) => (asked.push([i, name]), tiles[name] ?? null); + const [s] = decorateOption(toEChartsOption(r, { theme: chartThemeFrom(style) }), style, { width: 800, height: 480, tileOf }).series; + const byName = Object.fromEntries(s.data.map((/** @type {any} */ d) => [d.name, d])); + // asked by item and name, so a tile is never another item's + assert.deepEqual(asked, s.data.map((/** @type {any} */ d, /** @type {number} */ i) => [i, d.name])); + const line = s.label.rich.plate.lineHeight; + // two lines of `line` px in the middle of the tile's 200 px, on the series' plate + assert.deepEqual(byName.Central.label.padding, [(200 - 2 * line) / 2, 5, 0, 5]); + assert.equal(byName.Central.label.formatter(), "{plate|Central}\n{plate|4,000}"); + assert.equal(byName.Central.label.rich, undefined, "on the series' plate"); + // cut with an ellipsis, on the plate; the value, with no line left, left out whole, not cut + assert.equal(byName.Islands.label.formatter(), "{plate|Isla…}"); + assert.deepEqual(byName.Islands.label.padding, [(40 - line) / 2, 5, 0, 5]); + // no empty plate where nothing fits: the tooltip has the value + assert.equal(byName.West.label.show, false); + assert.equal(byName.Coast.label.show, false); + assert.equal(byName.North.label.show, false); + assert.equal(byName.South.label.formatter(), "{plate|South}"); + // a tile not drawn yet: the series' label + assert.equal(byName.East.label, undefined); +}); + +test("drawnTiles: a treemap's tiles by item and name, its root left out; nothing for another chart", () => { + const data = { count: () => 2, getName: (/** @type {number} */ i) => ["", "A"][i], getItemLayout: () => ({ width: 300, height: 200 }) }; + const chart = (/** @type {string} */ subType) => ({ getModel: () => ({ getSeriesByIndex: () => ({ subType, getData: () => data }) }) }); + const tileOf = /** @type {(i: number, name: string) => unknown} */ (drawnTiles(chart("treemap"))); + // the root at 0, the first item at 1 + assert.deepEqual(tileOf(0, "A"), { width: 300, height: 200 }); + // another name at that place, or past the end: unknown + assert.equal(tileOf(0, "B"), null); + assert.equal(tileOf(1, "A"), null); + assert.equal(drawnTiles(chart("bar")), undefined); + assert.equal(drawnTiles({}), undefined); +}); + +test("treemap without a background colour it can draw: no plates, each label in the ink that reads on its tile", () => { + const r = computePivot(REGIONS, { rows: ["Region"], values: [{ field: "Revenue", agg: "sum" }], chart: { type: "treemap" }, formatting: { locale: "en-US" } }); + const missing = { getPropertyValue: (/** @type {string} */ n) => (n === "--pk-surface" ? "" : (THEME_TOKENS.light[n] ?? "")) }; + const unreadableSurface = { getPropertyValue: (/** @type {string} */ n) => (n === "--pk-surface" ? "oklch(0.98 0 0)" : (THEME_TOKENS.light[n] ?? "")) }; + const readColor = (/** @type {string} */ c) => (c.startsWith("#") ? c : null); + for (const style of [missing, unreadableSurface]) { + const [s] = decorateOption(toEChartsOption(r, { theme: chartThemeFrom(missing) }), style, { width: 800, height: 480, readColor }).series; + assert.equal(s.label.rich.plate, undefined, style.getPropertyValue("--pk-surface")); + const out = s.label.formatter({ name: "North", value: 3240, color: "#1f1f1f" }); + const key = /^\{(\w+)\|/.exec(out)?.[1] ?? ""; + assert.ok(/** @type {number} */ (contrastOnFill(s.label.rich[key].color, "#1f1f1f")) >= 4.5, out); + } +}); + +/** A colour `t` of the way from `a` to `b` (#rrggbb), mixed as ECharts mixes a visual map's colours: per channel. */ +const mix = (/** @type {string} */ a, /** @type {string} */ b, /** @type {number} */ t) => { + const ch = (/** @type {string} */ c, /** @type {number} */ i) => parseInt(c.slice(1 + 2 * i, 3 + 2 * i), 16); + return `rgba(${[0, 1, 2].map((i) => Math.round(ch(a, i) + (ch(b, i) - ch(a, i)) * t)).join(",")},1)`; +}; + +test("heatmap, both themes: each number in the ink that reads on its cell, 4.5:1; the ink turns from dark to light once along the scale", () => { + const r = computePivot(encode(REVENUE), { rows: ["Region"], cols: ["Category"], values: [{ field: "Revenue", agg: "sum" }], chart: { type: "heatmap" }, formatting: { locale: "en-US" } }); + const inks = /** @type {Record} */ ({}); + const measured = fillContrasts((style, tokens, theme) => { + const out = drawn(r, style); + const [s] = out.series; + const [low, high] = out.visualMap.inRange.color; + // the cell's colour ECharts hands the formatter (p.color), from the low end to the high one + return Array.from({ length: 11 }, (_, i) => { + const fill = mix(low, high, i / 10); + const key = /^\{(\w+)\|/.exec(s.label.formatter({ value: [0, 0, 12], color: fill }))?.[1] ?? ""; + const ink = s.label.rich[key]?.color; + (inks[theme] ??= []).push(ink); + return { name: `cell ${i}`, ink, fill }; + }); + }); + assert.deepEqual(unreadable(measured), []); + // dark or light: closer to black or to white + const side = (/** @type {string} */ ink) => (/** @type {number} */ (contrastOnFill(ink, "#000000")) > /** @type {number} */ (contrastOnFill(ink, "#ffffff")) ? "light" : "dark"); + for (const [theme, list] of Object.entries(inks)) { + const changes = list.filter((ink, i) => i > 0 && side(ink) !== side(list[i - 1])).length; + assert.ok(changes <= 1, `${theme}: ${list.join(" ")}`); + } +}); + +test("high and low points and reference lines, both themes: the glyph, the value and the words in the text colour, 4.5:1 on the background", () => { + const rows = encode(MONTHLY); + const r = computePivot(rows, { derived: [MONTH], rows: ["Month"], cols: ["Product"], values: [{ field: "Revenue", agg: "sum" }], formatting: { locale: "en-US" }, chart: { type: "bar", referenceLines: { average: true, trend: false, target: null, extremes: true } } }); + // a host's light grey and pale blue series: their dots keep the colour, the labels do not take it + const colorMap = { A: "#d0d4da", B: "#9ecbff" }; + const measured = fillContrasts((style) => { + const out = drawn(r, style, { colorMap }); + const surface = style.getPropertyValue("--pk-surface"); + return out.series.flatMap((/** @type {any} */ s) => [ + ...(s.markPoint?.data ?? []).flatMap((/** @type {any} */ d) => [ + { name: `${s.name} ${d.name} value`, ink: d.label.color, fill: surface }, + { name: `${s.name} ${d.name} glyph`, ink: d.label.rich.s.color ?? d.label.color, fill: surface }, + // the outline around the letters is the background's colour too + { name: `${s.name} ${d.name} outline`, ink: d.label.color, fill: d.label.textBorderColor } + ]), + ...(s.markLine?.data ?? []).map((/** @type {any} */ d) => ({ name: `${s.name} ${d.name}`, ink: d.label.color, fill: surface })) + ]); + }); + assert.ok(measured.length >= 12, String(measured.length)); + assert.deepEqual(unreadable(measured), []); + // the measure itself: an unreadable colour is named, not passed + assert.equal(contrastOnFill("var(--pk-nothing)", "#ffffff", {}), null); + assert.deepEqual(unreadable([{ theme: "light", name: "x", ink: "oklch(0.5 0.1 200)", fill: "#ffffff", ratio: null }]), ["light x: oklch(0.5 0.1 200) on #ffffff = unreadable"]); +}); diff --git a/packages/pivotkit-core/test/chart/reference-lines.test.js b/packages/pivotkit-core/test/chart/reference-lines.test.js index 60f2bee2f..e983d03ea 100644 --- a/packages/pivotkit-core/test/chart/reference-lines.test.js +++ b/packages/pivotkit-core/test/chart/reference-lines.test.js @@ -282,7 +282,7 @@ test("the labels write the value as the axis does, short", () => { assert.equal(referenceLines(r).at(-1).format(1234567), "€1,234,567.00"); }); -test("decorateOption: the labels of lying lines right of the plot, kept apart, with room; a narrow chart writes the names only", () => { +test("decorateOption: the labels of lying lines right of the plot, kept apart, with room; a narrow chart writes the names only where every label fits (#913)", () => { const style = { getPropertyValue: () => "" }; // A's average 25 and a target of 26: two labels at nearly the same height const r = pivot({ chart: { type: "line", referenceLines: { average: true, trend: true, target: 26 } } }); @@ -297,10 +297,14 @@ test("decorateOption: the labels of lying lines right of the plot, kept apart, w const target = shown.find((d) => words(d.label) === "Target 26"); assert.equal(target.label.offset[1], 0); assert.ok(average.label.offset[1] > 10, JSON.stringify(average.label.offset)); - // narrow: the names alone + // narrow: the values alone, which tell one series' average from another's; a trend has its name const narrow = decorateOption(toEChartsOption(r), style, { width: 360, height: 480 }); const names = narrow.series.flatMap((x) => x.markLine?.data ?? []).map((d) => (Array.isArray(d) ? d[0] : d)).filter((d) => d.label.show !== false).map((d) => words(d.label)); - assert.deepEqual(names.sort(), ["Average", "Average", "Target", "Trend", "Trend"]); + assert.deepEqual(names.sort(), ["25", "26", "5", "Trend", "Trend"]); + // narrow, but each label with its name within 30 % of the chart's width: every label names its line + const roomy = decorateOption(toEChartsOption(r), style, { width: 440, height: 480 }); + const named = roomy.series.flatMap((x) => x.markLine?.data ?? []).map((d) => (Array.isArray(d) ? d[0] : d)).filter((d) => d.label.show !== false).map((d) => words(d.label)); + assert.deepEqual(named.sort(), ["Average 25", "Average 5", "Target 26", "Trend", "Trend"]); }); test("each label carries its line's cue: a sample of its dash in the line's colour", () => { @@ -317,6 +321,9 @@ test("each label carries its line's cue: a sample of its dash in the line's colo const target = b.markLine.data.at(-1).label; assert.equal(target.formatter(), "{s|——} Target 80"); assert.equal(target.rich.s.color, "#999999"); + // a fixed colour of a series (chart.colors, a host's colorMap) is its line's and its sample's (#913) + const fixed = toEChartsOption(pivot({ chart: { type: "line", colors: [{ name: "B", color: "#abcdef" }], referenceLines: { average: true, trend: false, target: null } } }), { theme: { colors: ["#111111", "#222222"] }, colorMap: { A: "#fedcba" } }); + assert.deepEqual(fixed.series.map((x) => x.markLine.data[0].label.rich.s.color), ["#fedcba", "#abcdef"]); // a name from the labels cannot break the markup const odd = toEChartsOption(r, { labels: { referenceLines: { average: "Mean {x|y}", trend: "Trend", target: "Target" } } }); assert.equal(odd.series[0].markLine.data[0].label.formatter(), "{s|– –} Mean xy 25"); @@ -347,7 +354,7 @@ test("decorateOption with the lines' real places (pixelOf): labels at their line const same = pivot({ cols: [], values: [{ field: "Revenue", agg: "sum" }, { field: "Revenue", agg: "max" }], chart: { type: "line", referenceLines: { average: true, trend: false, target: 30 } } }); const flat = (v) => (v > 20 ? 200 : 300); const narrow = labelsOf(decorateOption(toEChartsOption(same), style, { width: 360, height: 480, pixelOf: flat })); - assert.deepEqual(narrow.map((l) => [l.words, l.show]), [["Average", true], ["Average", true], ["Target", false]]); + assert.deepEqual(narrow.map((l) => [l.words, l.show]), [["30", true], ["25", true], ["30", false]]); }); test("the lines of no series ride on the last series shown: the legend hides a series' markLine with it", () => { diff --git a/packages/pivotkit-core/test/chart/types.test.js b/packages/pivotkit-core/test/chart/types.test.js index 307a0400e..6b7df4504 100644 --- a/packages/pivotkit-core/test/chart/types.test.js +++ b/packages/pivotkit-core/test/chart/types.test.js @@ -3,7 +3,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { CATALOG, computePivot, encode, normalize, referenceLineRules, toEChartsOption } from "pivotkit-core"; -import { decorateOption, labelColorOn } from "pivotkit-core/chart"; +import { decorateOption } from "pivotkit-core/chart"; /** Revenue in thousands and units in a few dozen per month: two values of very different sizes. */ const ROWS = [ @@ -116,37 +116,6 @@ test("treemap: one tile per category, its area its total, each tile in its colou ); }); -test("labelColorOn: the label of a tile in the token colour that reads best on it", () => { - const dark = "#1a1d23"; - const light = "#ffffff"; - assert.equal(labelColorOn("#eda100", [dark, light]), dark, "dark text on yellow"); - assert.equal(labelColorOn("#2a78d6", [dark, light]), light, "light text on blue"); - assert.equal(labelColorOn("#008300", [dark, light]), light); - assert.equal(labelColorOn("rgb(237, 161, 0)", [dark, light]), dark); - // a colour it cannot read: the first token - assert.equal(labelColorOn("oklch(0.5 0.1 200)", [dark, light]), dark); -}); - -test("decorateOption: treemap labels take --pk-text or --pk-surface, whichever reads better on each tile", () => { - const tokens = { "--pk-text": "#1a1d23", "--pk-surface": "#ffffff" }; - const style = { getPropertyValue: (n) => tokens[n] ?? "" }; - const r = computePivot(data, { rows: ["Region"], values: [TWO[0]], chart: { type: "treemap", colors: [{ name: "North", color: "#eda100" }, { name: "South", color: "#2a78d6" }] } }); - const out = decorateOption(toEChartsOption(r, { theme: THEME }), style, { width: 390, height: 300 }); - assert.deepEqual( - out.series[0].data.map((d) => [d.name, d.label.color]), - [ - ["North", "#1a1d23"], - ["South", "#ffffff"] - ] - ); - // tiles are parted by the background's colour - assert.equal(out.series[0].itemStyle.borderColor, "#ffffff"); - // on yellow the dark text reads (7.8:1): no outline; on a mid blue neither reaches 4.5:1, so the - // white label gets a dark outline it reads against - assert.equal(out.series[0].data[0].label.textBorderColor, undefined); - assert.deepEqual([out.series[0].data[1].label.textBorderColor, out.series[0].data[1].label.textBorderWidth], ["#1a1d23", 2]); -}); - test("decorateOption: a combo's axis names each fit in half the chart; a phone leaves them to the legend", () => { const option = toEChartsOption(pivot({ type: "combo" }), { theme: THEME }); const phone = decorateOption(option, { getPropertyValue: () => "" }, { width: 358, height: 300 }); diff --git a/packages/pivotkit-element/CHANGELOG.md b/packages/pivotkit-element/CHANGELOG.md index 52d568248..13ad20eff 100644 --- a/packages/pivotkit-element/CHANGELOG.md +++ b/packages/pivotkit-element/CHANGELOG.md @@ -17,6 +17,10 @@ All notable changes to `pivotkit-element` are documented in this file. The forma - pivotkit-core's Excel number formats load with the export: the export group grows by 0.8 KiB to 13.2 KiB ([#772](https://github.com/eizedev/pivotkit/issues/772)). - The README says that a minor release of 0.x can break things, with links to Versioning and Upgrading. +- The chart's load group grows by 1.6 KiB to 261.8 KiB gzip with pivotkit-core's fix of text on + coloured fills and of high and low points beside grouped bars, its budget to 262.0 KiB + ([#913](https://github.com/eizedev/pivotkit/issues/913), [#914](https://github.com/eizedev/pivotkit/issues/914)). + The first load stays the same. ### Fixed diff --git a/packages/pivotkit-element/build.js b/packages/pivotkit-element/build.js index 80eb90fe2..0de0e48c8 100644 --- a/packages/pivotkit-element/build.js +++ b/packages/pivotkit-element/build.js @@ -207,7 +207,7 @@ async function licenses(metafile) { * can make the first load larger. * `--size` fails above it. */ -export const SIZE_BUDGET_KIB = { initial: 182.5, chart: 260.7, export: 13.7, link: 7.5, menus: 59.6, texts: 8.5, unused: 6.5, import: 23.2, report: 26.8, template: 3, lang: 6.2, tips: 1.8 }; +export const SIZE_BUDGET_KIB = { initial: 182.5, chart: 262.0, export: 13.7, link: 7.5, menus: 59.6, texts: 8.5, unused: 6.5, import: 23.2, report: 26.8, template: 3, lang: 6.2, tips: 1.8 }; /** * The load group of each chunk a page loads on demand, by its file name (esbuild's `[name]-[hash]`), diff --git a/packages/pivotkit-react/CHANGELOG.md b/packages/pivotkit-react/CHANGELOG.md index 8d53dede2..191dba7fb 100644 --- a/packages/pivotkit-react/CHANGELOG.md +++ b/packages/pivotkit-react/CHANGELOG.md @@ -24,6 +24,10 @@ All notable changes to `pivotkit-react` are documented in this file. The format ### Fixed +- The chart's text on coloured fills reads in both themes, with pivotkit-core's fix + ([#913](https://github.com/eizedev/pivotkit/issues/913), [#914](https://github.com/eizedev/pivotkit/issues/914)): + a treemap's labels on plates in the background colour, in the middle of their tiles and cut to fit, a heatmap's numbers in the ink that reads on + each cell, the ▲ and ▼ of high and low points in the muted text colour (`--pk-muted`). - A report mounted again while a link is in the page's address, such as a second report on the page or one a host mounts anew on a theme switch, opens the link. Before, it threw a `TypeError` and showed nothing, because the link opened before the report was ready for it diff --git a/packages/pivotkit-react/src/chart-decorate.js b/packages/pivotkit-react/src/chart-decorate.js index 9e777d4c4..ebef2964d 100644 --- a/packages/pivotkit-react/src/chart-decorate.js +++ b/packages/pivotkit-react/src/chart-decorate.js @@ -8,7 +8,7 @@ */ import { DEFAULT_THEME } from "pivotkit-core"; -import { decorateOption } from "pivotkit-core/chart"; +import { decorateOption, drawnTiles } from "pivotkit-core/chart"; import { mergeChartOptions } from "./chart-options.js"; import { tooltipFormatter, tooltipReferences, valueAddsUp } from "./chart-tooltip.js"; @@ -25,7 +25,7 @@ const TOOLTIP_OTHER_LINES = 3; * @param {number} [height] the chart's height in px, for the room around a pie * @param {Document} [doc] the chart's document, for the tooltip's nodes * @param {number} [width] the chart's width in px, for the column names of a heatmap and the category axis - * @param {{ categoryNames?: string[], axisLabels?: string, zoom?: string, zoomAt?: { start: number, end: number }, timeline?: boolean, touch?: boolean, pixelOf?: (value: number) => number, parseColor?: (color: string) => unknown, tooltip?: { mode?: string, share?: boolean, hover?: { current: { seriesIndex: number, dataIndex: number } | null }, totalLabel?: string, moreLabel?: string, moreInTotalLabel?: string, values?: Array<{ agg?: string, showAs?: { type: string, axis?: string } | null } | undefined>, lines?: ReturnType } }} [extra] + * @param {{ categoryNames?: string[], axisLabels?: string, zoom?: string, zoomAt?: { start: number, end: number }, timeline?: boolean, touch?: boolean, pixelOf?: (value: number) => number, tileOf?: (index: number, name: string) => { width: number, height: number } | null, parseColor?: (color: string) => unknown, tooltip?: { mode?: string, share?: boolean, hover?: { current: { seriesIndex: number, dataIndex: number } | null }, totalLabel?: string, moreLabel?: string, moreInTotalLabel?: string, values?: Array<{ agg?: string, showAs?: { type: string, axis?: string } | null } | undefined>, lines?: ReturnType } }} [extra] * the categories' whole names (the tooltip's title when the axis writes them shorter), the view's * chart.axisLabels and chart.zoom (the slider, pivotkit-core's chart-zoom.js); tooltip: the view's chart.tooltip and chart.tooltipShare, the chart's hover state (chart.jsx writes the * element under the pointer into `current`, the formatter reads it), the name of a stack's total, @@ -62,7 +62,8 @@ export function decorate(option, style, height = 480, doc = undefined, width = 8 * them (`hostOptions`, checked, mergeChartOptions), and then the labels of lying reference lines * placed at their lines' real heights: after the first draw ECharts knows where each value is * (convertToPixel), so the marks are laid out again with it (pivotkit-core's decorateOption, - * pixelOf) and only the series are set again. + * pixelOf) and only the series are set again; a treemap's labels likewise at the middle of the tiles it + * drew (drawnTiles). * @param {any} instance the chart's ECharts instance * @param {any} option pivotkit-core's toEChartsOption * @param {{ getPropertyValue(name: string): string }} style @@ -74,8 +75,8 @@ export function decorate(option, style, height = 480, doc = undefined, width = 8 export function drawOption(instance, option, style, doc, extra, hostOptions) { /** @type {any} */ let own = null; - const marked = (/** @type {((v: number) => number) | undefined} */ pixelOf) => { - const drawn = decorate(option, style, instance.getHeight(), doc, instance.getWidth(), { ...extra, pixelOf }); + const marked = (/** @type {((v: number) => number) | undefined} */ pixelOf, /** @type {ReturnType} */ tileOf = undefined) => { + const drawn = decorate(option, style, instance.getHeight(), doc, instance.getWidth(), { ...extra, pixelOf, tileOf }); own ??= drawn; // the option without the report's own axisEvery, which ECharts does not know const rest = { ...drawn }; @@ -88,6 +89,9 @@ export function drawOption(instance, option, style, doc, extra, hostOptions) { if (lying && (first.series ?? []).some((/** @type {any} */ s) => s.markLine || s.markPoint)) { instance.setOption({ series: marked((value) => instance.convertToPixel({ yAxisIndex: 0 }, value)).series }); } + // a treemap's labels in the middle of the tiles it drew + const tileOf = drawnTiles(instance); + if (tileOf) instance.setOption({ series: marked(undefined, tileOf).series }); return own; } diff --git a/packages/pivotkit-report/CHANGELOG.md b/packages/pivotkit-report/CHANGELOG.md index cb4d03635..044a53c1e 100644 --- a/packages/pivotkit-report/CHANGELOG.md +++ b/packages/pivotkit-report/CHANGELOG.md @@ -10,6 +10,13 @@ All notable changes to `pivotkit-report` are documented in this file. The format - The README says that a minor release of 0.x can break things, with links to Versioning and Upgrading. +### Fixed + +- The SVG and the HTML report draw text on coloured fills as the screen does, with pivotkit-core's + fix ([#913](https://github.com/eizedev/pivotkit/issues/913), [#914](https://github.com/eizedev/pivotkit/issues/914)): + a treemap's labels on plates in the middle of their tiles and cut to fit, a heatmap's numbers in the ink that reads on each cell, the ▲ and ▼ + in the muted text colour (`--pk-muted`). + ## [0.6.0] - 2026-11-24 ### Fixed diff --git a/packages/pivotkit-report/src/svg.js b/packages/pivotkit-report/src/svg.js index 825cc20bd..97851fd2a 100644 --- a/packages/pivotkit-report/src/svg.js +++ b/packages/pivotkit-report/src/svg.js @@ -8,7 +8,7 @@ import { PivotkitError, chartPlan, chartThemeFrom, computePivot, swapAxes, toSeries } from "pivotkit-core"; // the option from the chart's entry point: a bundle with pivotkit-report keeps it off its first load -import { decorateOption, toEChartsOption } from "pivotkit-core/chart"; +import { decorateOption, drawnTiles, toEChartsOption } from "pivotkit-core/chart"; import { BIDI_CONTROLS } from "./texts.js"; import { LIGHT_TOKENS } from "./tokens.js"; @@ -166,9 +166,9 @@ export function chartSvg(result, { echarts, style, width, height, locale, labels // black: the light default stands in for it. Every other colour is written into the SVG as it is const parse = echarts.color?.parse; const readColor = typeof parse === "function" ? (/** @type {string} */ c) => (parse(c.trim()) ? c : null) : undefined; - const marked = (/** @type {((v: number) => number) | undefined} */ pixelOf) => { + const marked = (/** @type {((v: number) => number) | undefined} */ pixelOf, /** @type {ReturnType} */ tileOf = undefined) => { // axisEvery is the report's own note, not ECharts' - const decorated = decorateOption(option, style, { width, height, categoryNames: series.categories, axisLabels: view.chart.axisLabels, readColor, pixelOf }); + const decorated = decorateOption(option, style, { width, height, categoryNames: series.categories, axisLabels: view.chart.axisLabels, readColor, pixelOf, tileOf }); delete decorated.axisEvery; return decorated; }; @@ -183,6 +183,9 @@ export function chartSvg(result, { echarts, style, width, height, locale, labels if (!Array.isArray(first.yAxis) && first.yAxis?.type === "value" && (first.series ?? []).some((/** @type {any} */ s) => s.markLine || s.markPoint)) { chart.setOption({ series: marked((v) => chart.convertToPixel({ yAxisIndex: 0 }, v)).series }); } + // a treemap's labels in the middle of the tiles it drew, as on the screen + const tileOf = drawnTiles(chart); + if (tileOf) chart.setOption({ series: marked(undefined, tileOf).series }); svg = chart.renderToSVGString(); } finally { chart.dispose(); diff --git a/packages/pivotkit-report/test/svg.test.js b/packages/pivotkit-report/test/svg.test.js index 9d9a66e11..b259e1860 100644 --- a/packages/pivotkit-report/test/svg.test.js +++ b/packages/pivotkit-report/test/svg.test.js @@ -2,6 +2,7 @@ // draws must be what the screen's chart draws (pivotkit-core's chartPlan and the report's marks). import { test } from "node:test"; import assert from "node:assert/strict"; +import { drawnTiles } from "pivotkit-core/chart"; import { render } from "pivotkit-report"; import { FIXED, SALES, echarts, startTags, svgTexts } from "./fixtures.js"; @@ -123,15 +124,16 @@ test("reference lines (#48): the SVG puts each label at its line, after a sample assert.match(r.text, /fill="#5a6270"[^>]*>—— { +test("high and low points (#574): the SVG and the HTML report draw a dot and a label at each, the glyph in the text colour (#913)", async () => { // North 10, South 12, West 4, (blank) 6 units: the highest at South, the lowest at West const view = { rows: ["Region"], values: [{ field: "Units", agg: "sum" }], chart: { type: "bar", referenceLines: { average: false, trend: false, target: null, extremes: true } } }; const r = await render(view, SALES, { format: "svg", echarts, ...FIXED }); const texts = svgTexts(r.text).map((t) => t.trim()); assert.ok(texts.includes("▲") && texts.includes("12"), texts.join(" | ")); assert.ok(texts.includes("▼") && texts.includes("4"), texts.join(" | ")); - // the glyph in the first series' colour (light --pk-chart-1) - assert.match(r.text, /fill="#2a78d6"[^>]*>▲]*>▲]*> 12 t.trim()).includes("▲")); @@ -170,6 +172,13 @@ test("a combo and a treemap reach the SVG (#518)", async () => { for (const region of ["North", "South", "West"]) { assert.ok(tiles.includes(region), `${region}: ${tiles.join(" | ")}`); } + // each label in its tile's middle (#913): its name and value as far above as below the tile's centre + const lines = [...t.text.matchAll(/]*y="([-\d.e]+)" transform="translate\(([^)]+)\)"[^>]*>([^<]*)<\/text>/g)].map(([, y, at, text]) => ({ y: Number(y), at, text })); + for (const region of ["North", "South", "West"]) { + const name = lines.find((l) => l.text === region); + const value = lines.find((l) => l !== name && l.at === name?.at); + assert.ok(name && value && Math.abs(name.y + value.y) <= 1, `${region}: ${JSON.stringify([name, value])}`); + } }); test("100 % stacked bars and hidden series reach the SVG (#36)", async () => { @@ -222,3 +231,37 @@ test("colorMap takes a pair of colours for light and dark, as the React prop doe const r = await render(view, SALES, { format: "svg", echarts, colorMap: { A: ["#0a0b0c", "#f0f0f0"] }, ...FIXED }); assert.ok(r.text.includes('fill="#0a0b0c"') && !r.text.includes('fill="#f0f0f0"')); }); + +test("drawnTiles against ECharts itself: a flat treemap's tiles by item; in a tree with children no tile is taken for another item's", () => { + const draw = (/** @type {object[]} */ data) => { + const chart = echarts.init(null, null, { renderer: "svg", ssr: true, width: 600, height: 400 }); + chart.setOption({ animation: false, series: [{ type: "treemap", data, breadcrumb: { show: false } }] }); + return chart; + }; + const flat = draw([{ name: "a", value: 30 }, { name: "b", value: 10 }]); + try { + const tileOf = /** @type {(i: number, name: string) => { width: number, height: number } | null} */ (drawnTiles(flat)); + const [a, b] = [tileOf(0, "a"), tileOf(1, "b")]; + assert.ok(a && b, "both tiles found"); + // the tiles share the chart in the values' proportion: 3 to 1 + assert.ok(Math.abs((a.width * a.height) / (b.width * b.height) - 3) < 0.01, `${a.width}x${a.height} ${b.width}x${b.height}`); + assert.equal(tileOf(0, "b"), null); + assert.equal(tileOf(2, "c"), null); + } finally { + flat.dispose(); + } + // ECharts lists a tree depth first: an item after one with children is not at its index + 1 + const nested = draw([{ name: "a", value: 30 }, { name: "b", children: [{ name: "b1", value: 5 }, { name: "b2", value: 5 }] }, { name: "c", value: 10 }]); + try { + const tileOf = /** @type {(i: number, name: string) => unknown} */ (drawnTiles(nested)); + assert.ok(tileOf(0, "a")); + assert.ok(tileOf(1, "b")); + assert.equal(tileOf(2, "c"), null, "b1 sits where c would"); + } finally { + nested.dispose(); + } + const bar = echarts.init(null, null, { renderer: "svg", ssr: true, width: 600, height: 400 }); + bar.setOption({ xAxis: { data: ["a"] }, yAxis: {}, series: [{ type: "bar", data: [1] }] }); + assert.equal(drawnTiles(bar), undefined); + bar.dispose(); +}); diff --git a/scripts/growth-baseline.json b/scripts/growth-baseline.json index db04edb1e..bf9574a4e 100644 --- a/scripts/growth-baseline.json +++ b/scripts/growth-baseline.json @@ -1,7 +1,7 @@ { "docs": { "pages": { - "docs/concepts/charts.md": [316], + "docs/concepts/charts.md": [318], "docs/concepts/limits.md": [430], "docs/getting-started/kubernetes.md": [486], "docs/learn.md": [458], @@ -14,16 +14,16 @@ "docs/reference/rest.md": [972], "docs/reference/sources.md": [984], "docs/security.md": [896], - "docs/use/charts.md": [481] + "docs/use/charts.md": [487] }, - "totalLines": 24045 + "totalLines": 24091 }, "functions": { "complexity": { "packages/pivotkit-cli/src/remote.js Async function 'request'": [30], "packages/pivotkit-cli/src/sign-in.js Async function 'loginCommand'": [27], "packages/pivotkit-core/src/chart-fit.js Function 'pointLabels'": [43], - "packages/pivotkit-core/src/chart-style.js Arrow function": [50], + "packages/pivotkit-core/src/chart-style.js Arrow function": [48], "packages/pivotkit-core/src/chart-style.js Function 'decorateOption'": [136], "packages/pivotkit-core/src/chart.js Function 'toEChartsOption'": [88], "packages/pivotkit-core/src/describe.js Function 'filterText'": [38], @@ -119,7 +119,7 @@ "lines": { "packages/pivotkit-cli/src/credential-store.js Function 'credentialStore'": [134], "packages/pivotkit-cli/src/remote.js Function 'createClient'": [161], - "packages/pivotkit-core/src/chart-style.js Function 'decorateOption'": [155], + "packages/pivotkit-core/src/chart-style.js Function 'decorateOption'": [148], "packages/pivotkit-core/src/chart.js Function 'toEChartsOption'": [199], "packages/pivotkit-mcp/src/http.js Async function 'createHttpHandler'": [159], "packages/pivotkit-react/src/chip-menus.jsx Function 'TopLevel'": [125], diff --git a/tests/browser/chart/fill-labels.spec.js b/tests/browser/chart/fill-labels.spec.js new file mode 100644 index 000000000..799d9066b --- /dev/null +++ b/tests/browser/chart/fill-labels.spec.js @@ -0,0 +1,249 @@ +// Text on coloured fills (#913, #914) as ECharts drew it: a treemap's labels on plates, a heatmap's +// numbers in the ink that reads on their cell, each at 4.5:1 on what is under it, in both themes; the +// labels of high and low points never across another bar. After a theme switch every label and plate +// takes the colours a fresh render in that theme gives. +import { ELLIPSIS, PLATE_SIDE, TILE_EDGE, TILE_LABEL_PADDING, TILE_MIN_CHARS, plateLine, textWidth } from "../../../packages/pivotkit-core/src/chart-measure.js"; +import { TEXT_MIN } from "../../fill-contrast.js"; +import { installContrast } from "../contrast.js"; +import { expect, test } from "../fixtures.js"; +import { chartOf, inChart, inPage, mountReport, ROWS, tooltipOf, VIEW } from "./report.js"; + +/** Every text ECharts drew, sorted: its words, fill, outline colour and outline width. */ +const drawnTexts = (chartEl) => + inChart(chartEl, (chart) => { + const out = []; + for (const el of chart.getZr().storage.getDisplayList(true)) { + if ((el.type !== "tspan" && el.type !== "text") || el.ignore || el.invisible) continue; + const s = el.style; + if (!s.text) continue; + out.push([String(s.text), String(s.fill ?? ""), s.lineWidth ? String(s.stroke ?? "") : "", s.lineWidth ?? 0].join(" | ")); + } + return out.sort(); + }); + +/** + * Each label drawn on a mark (a tile, a cell): its words, its colour and what is under them, the + * label's own background (a plate) where it has one, else the mark's fill. + */ +const labelsOnMarks = (chartEl) => + inChart(chartEl, (chart) => { + const out = []; + for (const el of chart.getZr().storage.getDisplayList(true)) { + const text = el.getTextContent?.(); + if (!text || text.ignore || text.invisible || !el.style?.fill) continue; + const parts = text.childrenRef?.() ?? []; + // a label too wide for a plate has a transparent one: none + const plates = parts.filter((p) => p.type === "rect" && p.style?.fill && p.style.fill !== "transparent"); + for (const span of parts.filter((p) => p.type === "tspan" && p.style?.text?.trim())) { + const plate = plates.find((p) => { + const a = p.getBoundingRect(); + const b = span.getBoundingRect(); + return a.x <= b.x + 1 && a.y <= b.y + 1 && a.x + a.width >= b.x + b.width - 1 && a.y + a.height >= b.y + b.height - 1; + }); + out.push({ text: span.style.text, ink: span.style.fill, fill: plate ? plate.style.fill : el.style.fill, plated: Boolean(plate) }); + } + } + return out; + }); + +const contrasts = async (page, labels) => { + await installContrast(page); + return page.evaluate((labels) => labels.map((l) => ({ ...l, ratio: window.__pkContrast.ratio(window.__pkContrast.parse(l.ink), window.__pkContrast.parse(l.fill)) })), labels); +}; + +/** Eight regions, one tile each, and a host's light grey and near black among the colours. */ +const REGIONS = ["Central", "West", "North", "South", "East", "Alps", "Coast", "Islands"].map((Region, i) => ({ Region, Revenue: 4000 - i * 380 })); +const HOST = { Central: "#d9d9d9", West: "#1f1f1f" }; +/** The smallest tile that writes a label at the report's 14 px text, from pivotkit-core's measures (treemapLabels). */ +const TILE_MIN = { + width: textWidth(`${"M".repeat(TILE_MIN_CHARS)}${ELLIPSIS}`, 14) + 2 * (PLATE_SIDE + TILE_LABEL_PADDING), + height: plateLine(14) + 2 * TILE_EDGE +}; +/** Narrower than this no cut name fits, even of the narrowest characters (lower case): no label. */ +const TILE_NONE_WIDTH = textWidth(`${"a".repeat(TILE_MIN_CHARS)}${ELLIPSIS}`, 14) + 2 * (PLATE_SIDE + TILE_LABEL_PADDING); +/** Twenty countries by population: wide tiles and tiles too narrow for a name on a plate. */ +const COUNTRIES = [["India", 1450], ["China", 1410], ["United States", 340], ["Indonesia", 283], ["Pakistan", 251], ["Nigeria", 232], ["Brazil", 212], ["Bangladesh", 173], ["Russian Federation", 143], ["Ethiopia", 132], ["Mexico", 130], ["Japan", 124], ["Egypt, Arab Rep.", 116], ["Philippines", 115], ["Congo, Dem. Rep.", 109], ["Viet Nam", 101], ["Iran, Islamic Rep.", 91], ["Turkiye", 85], ["Germany", 83], ["Thailand", 71]].map(([Country, Population]) => ({ Country, Population })); + +for (const theme of ["light", "dark"]) { + test(`treemap, ${theme}: every label on a plate, 4.5:1, one look on every plate`, async ({ page }) => { + await page.goto("pages/host.html"); + await mountReport(page, { id: "fill-report", rows: REGIONS, view: { rows: ["Region"], values: [{ field: "Revenue", agg: "sum" }], display: "chart", chart: { type: "treemap" } }, theme, height: 480, props: { colorMap: HOST } }); + const labels = await contrasts(page, await labelsOnMarks(await chartOf(page, "fill-report", "treemap"))); + expect(labels.length).toBeGreaterThanOrEqual(16); + for (const l of labels) expect(l.ratio, `${l.text}: ${l.ink} on ${l.fill}`).toBeGreaterThanOrEqual(TEXT_MIN); + // every label on a plate, one look on all of them + expect(labels.filter((l) => !l.plated).map((l) => l.text)).toEqual([]); + expect(new Set(labels.map((l) => `${l.ink} on ${l.fill}`)).size).toBe(1); + }); + + test(`treemap, ${theme}, 390 px: each label on a plate in its tile's middle, cut to fit, 4.5:1, no plate without words`, async ({ page }) => { + await page.setViewportSize({ width: 390, height: 900 }); + await page.goto("pages/host.html"); + await mountReport(page, { id: "fill-report", rows: COUNTRIES, view: { rows: ["Country"], values: [{ field: "Population", agg: "sum" }], display: "chart", chart: { type: "treemap" } }, theme, height: 560 }); + const chartEl = await chartOf(page, "fill-report", "treemap"); + const tiles = await inChart(chartEl, (chart) => { + const out = []; + for (const el of chart.getZr().storage.getDisplayList(true)) { + const text = el.getTextContent?.(); + if (!text || !el.style?.fill) continue; + const shown = !text.ignore && !text.invisible; + const box = el.getBoundingRect().clone(); + box.applyTransform(el.getComputedTransform()); + const parts = text.childrenRef?.() ?? []; + const words = []; + for (const p of parts.filter((p) => shown && p.type === "tspan" && p.style?.text?.trim())) { + const r = p.getBoundingRect().clone(); + r.applyTransform(text.getComputedTransform()); + words.push(r); + } + const plates = parts.filter((p) => p.type === "rect" && p.style?.fill && p.style.fill !== "transparent").map((p) => { + const r = p.getBoundingRect(); + return { width: r.width, words: parts.some((w) => w.type === "tspan" && w.style?.text?.trim() && Math.abs(w.getBoundingRect().y - r.y) < r.height) }; + }); + const y0 = Math.min(...words.map((r) => r.y)); + const y1 = Math.max(...words.map((r) => r.y + r.height)); + out.push({ name: words.length ? parts.find((p) => p.type === "tspan")?.style.text : "(none)", tile: [box.y, box.y + box.height], size: [box.width, box.height], words: words.length ? [y0, y1] : null, plates: shown ? plates : [] }); + } + return out; + }); + expect(tiles.length).toBe(COUNTRIES.length); + let below = 0; + for (const t of tiles) { + for (const p of t.plates) expect(p.words, `${t.name}: a plate ${p.width} px wide without words`).toBe(true); + // a tile with room for the fewest characters of a cut name, as capitals (the widest), and the + // ellipsis on a plate, and for one line of it, shows words (at 14 px: 61 x 23 px) + if (t.size[0] >= TILE_MIN.width && t.size[1] >= TILE_MIN.height) expect(t.words, `a tile of ${t.size.map(Math.round).join(" x ")} px without words`).not.toBeNull(); + // a tile too narrow even for lower case, or lower than a line, shows neither words nor a plate + if (t.size[0] < TILE_NONE_WIDTH || t.size[1] < TILE_MIN.height) { + below++; + expect(t.words, `${t.name}: words on a tile of ${t.size.map(Math.round).join(" x ")} px`).toBeNull(); + expect(t.plates, `${t.name}: a plate on a tile of ${t.size.map(Math.round).join(" x ")} px`).toEqual([]); + } + if (!t.words) continue; + // the words' middle within 2 px of the tile's + expect(Math.abs((t.words[0] + t.words[1]) / 2 - (t.tile[0] + t.tile[1]) / 2), `${t.name}: ${JSON.stringify(t)}`).toBeLessThanOrEqual(2); + } + expect(below, "tiles below the smallest that can write a label").toBeGreaterThan(0); + // every label on a plate, cut with an ellipsis where the name is wider than its tile: 4.5:1 + const labels = await contrasts(page, await labelsOnMarks(chartEl)); + for (const l of labels) expect(l.ratio, `${l.text}: ${l.ink} on ${l.fill}`).toBeGreaterThanOrEqual(TEXT_MIN); + expect(labels.filter((l) => !l.plated).map((l) => l.text)).toEqual([]); + expect(labels.some((l) => l.text.endsWith("\u2026"))).toBe(true); + }); + + test(`heatmap, ${theme}: every number 4.5:1 on the cell ECharts drew`, async ({ page }) => { + await page.goto("pages/host.html"); + await mountReport(page, { id: "fill-report", rows: ROWS, view: { ...VIEW, chart: { type: "heatmap" } }, theme, height: 480 }); + const labels = await contrasts(page, await labelsOnMarks(await chartOf(page, "fill-report", "heatmap"))); + expect(labels.length).toBe(8); + for (const l of labels) expect(l.ratio, `${l.text}: ${l.ink} on ${l.fill}`).toBeGreaterThanOrEqual(TEXT_MIN); + }); +} + +// On a phone a tap on a tile shows its tooltip: the whole name and the value of a tile whose label is cut +// or left out +test.describe("a touch screen", () => { + test.use({ viewport: { width: 390, height: 900 }, hasTouch: true, isMobile: false }); + + test("treemap, 390 px: a tap on a tile without words or with a cut name shows its whole name and value", async ({ page }) => { + await page.goto("pages/host.html"); + await mountReport(page, { id: "fill-report", rows: COUNTRIES, view: { rows: ["Country"], values: [{ field: "Population", agg: "sum" }], display: "chart", chart: { type: "treemap" } }, theme: "light", height: 560 }); + const chartEl = await chartOf(page, "fill-report", "treemap"); + // each tile's middle and what it writes: "" for none + const tiles = await inChart(chartEl, (chart) => { + const out = []; + for (const el of chart.getZr().storage.getDisplayList(true)) { + const text = el.getTextContent?.(); + if (!text || !el.style?.fill) continue; + const box = el.getBoundingRect().clone(); + box.applyTransform(el.getComputedTransform()); + const shown = !text.ignore && !text.invisible; + const words = shown ? (text.childrenRef?.() ?? []).filter((p) => p.type === "tspan" && p.style?.text?.trim()).map((p) => p.style.text) : []; + out.push({ middle: [box.x + box.width / 2, box.y + box.height / 2], words }); + } + return out; + }); + const bare = tiles.find((t) => t.words.length === 0); + const cut = tiles.find((t) => t.words[0]?.endsWith(ELLIPSIS)); + expect(bare, "a tile without words").toBeTruthy(); + expect(cut, "a tile with a cut name").toBeTruthy(); + let before = ""; + for (const tile of [bare, cut]) { + const at = await inPage(chartEl, tile.middle); + await page.touchscreen.tap(at.x, at.y); + // the tile's own tooltip, not the one of the tile tapped before + await expect.poll(async () => (await tooltipOf(chartEl)).join(" ")).not.toBe(before); + const tip = (await tooltipOf(chartEl)).join(" "); + before = tip; + const country = COUNTRIES.find((c) => tip.includes(`${c.Country} ${c.Population}`)); + expect(country, `a tile writing ${JSON.stringify(tile.words)}: ${tip}`).toBeTruthy(); + if (tile === cut) expect(country.Country.startsWith(tile.words[0].slice(0, -1)), `${tile.words[0]}: ${tip}`).toBe(true); + // a person's pace between the taps, no double tap + await page.waitForTimeout(400); + } + }); +}); + +test("grouped bars (#913): a high or low point's label crosses no other bar and no other label", async ({ page }) => { + await page.setViewportSize({ width: 560, height: 900 }); + await page.goto("pages/host.html"); + // four teams by four priorities, counted: a light grey and a pale blue series among them + const counts = [[215, 192, 60, 124], [230, 140, 75, 105], [82, 64, 56, 70], [215, 175, 170, 172]]; + const rows = counts.flatMap((row, t) => row.flatMap((n, p) => Array.from({ length: n }, () => ({ Team: `Team ${t + 1}`, Priority: ["High", "Low", "Medium", "Urgent"][p] })))); + await mountReport(page, { id: "fill-report", rows, view: { rows: ["Team"], cols: ["Priority"], values: [{ field: "Team", agg: "count" }], display: "chart", chart: { type: "bar", referenceLines: { average: true, trend: false, target: null, extremes: true } } }, theme: "light", height: 520, props: { colorMap: { Low: "#d0d4da", Medium: "#9ecbff" } } }); + const chartEl = await chartOf(page, "fill-report", "bar"); + const drawn = await inChart(chartEl, (chart) => { + const model = chart.getModel(); + const bars = []; + model.eachSeriesByType("bar", (s) => { + const data = s.getData(); + for (let i = 0; i < data.count(); i++) { + const l = data.getItemLayout(i); + if (l) bars.push({ series: s.seriesIndex, index: i, x0: Math.min(l.x, l.x + l.width), x1: Math.max(l.x, l.x + l.width), y0: Math.min(l.y, l.y + l.height), y1: Math.max(l.y, l.y + l.height) }); + } + }); + const labels = []; + chart.getZr().storage.getDisplayList(true).forEach((el) => { + const text = el.getTextContent?.(); + if (!text || text.ignore || text.invisible || !/[▲▼]/.test(text.style?.text ?? "")) return; + const r = text.getBoundingRect().clone(); + r.applyTransform(text.getComputedTransform()); + const own = model.getSeriesByIndex(el.__ecMarkerSeries ?? -1); + labels.push({ text: text.style.text, x0: r.x, x1: r.x + r.width, y0: r.y, y1: r.y + r.height, center: el.x, series: own ? own.seriesIndex : null }); + }); + return { bars, labels }; + }); + expect(drawn.labels.length).toBeGreaterThan(0); + const cover = (a, b) => a.x0 < b.x1 - 1 && b.x0 < a.x1 - 1 && a.y0 < b.y1 - 1 && b.y0 < a.y1 - 1; + for (const l of drawn.labels) { + // its own bar is the one under its dot + const others = drawn.bars.filter((b) => !(l.center >= b.x0 && l.center <= b.x1)); + for (const b of others) expect(cover(l, b), `${l.text} across a bar of series ${b.series} at ${b.index}`).toBe(false); + for (const o of drawn.labels) if (o !== l) expect(cover(l, o), `${l.text} over ${o.text}`).toBe(false); + } +}); + +for (const type of ["treemap", "heatmap"]) { + for (const [from, to] of [ + ["light", "dark"], + ["dark", "light"] + ]) { + test(`${type}: after a switch from ${from} to ${to}, every label as a fresh render in ${to} draws it`, async ({ page }) => { + await page.goto("pages/host.html"); + const view = { ...VIEW, chart: { type } }; + await mountReport(page, { id: "fill-report", rows: ROWS, view, theme: from, height: 480 }); + await chartOf(page, "fill-report", type); + await page.evaluate((theme) => window.__rerender({ theme }), to); + await expect.poll(() => page.locator("#fill-report .pk-root").getAttribute("data-pk-theme")).toBe(to); + let chartEl = await chartOf(page, "fill-report", type); + // the texts and, for each label on a mark, its ink and what is under it (a treemap's plate) + const drawn = async (el) => ({ texts: await drawnTexts(el), marks: (await labelsOnMarks(el)).map((l) => `${l.text} | ${l.ink} on ${l.fill}`).sort() }); + const switched = await drawn(chartEl); + expect(switched.texts.length).toBeGreaterThan(0); + expect(switched.marks.length).toBeGreaterThan(0); + await mountReport(page, { id: "fill-report", rows: ROWS, view, theme: to, height: 480 }); + chartEl = await chartOf(page, "fill-report", type); + expect(switched).toEqual(await drawn(chartEl)); + }); + } +} diff --git a/tests/browser/chart/reference-lines.spec.js b/tests/browser/chart/reference-lines.spec.js index f73e6a521..7df0ebb6a 100644 --- a/tests/browser/chart/reference-lines.spec.js +++ b/tests/browser/chart/reference-lines.spec.js @@ -343,7 +343,7 @@ test.describe("reference lines", () => { }); } - for (const width of [1440, 390]) { + for (const width of [1440, 470, 390]) { test(`at ${width} px no label covers another, with lines close together and far apart`, async ({ page }) => { await page.setViewportSize({ width, height: 900 }); // A's average 25 and a target of 26, B's average 5 and both trends: five labels, two close @@ -356,14 +356,16 @@ test.describe("reference lines", () => { expect(overlap(boxes[i].box, boxes[j].box), `${JSON.stringify(chart)}: "${boxes[i].label}" and "${boxes[j].label}" overlap`).toBe(false); } } - // the labels are inside the chart, and a narrow one names the lines only + // the labels are inside the chart; a narrow one names its line where every label fits in 30 % + // of the width (470 px), else writes the value only, a trend its name (390 px) (#913) const size = await chartEl.boundingBox(); for (const l of boxes) { expect(l.box.x + l.box.width, l.label).toBeLessThanOrEqual(size.width + 1); expect(l.box.x, l.label).toBeGreaterThanOrEqual(-1); } - if (width < 480) { - expect(boxes.every((l) => !/\d/.test(l.label)), boxes.map((l) => l.label).join(", ")).toBe(true); + if (width < 400) { + expect(boxes.every((l) => l.label === "Trend" || /^\d+$/.test(l.label)), boxes.map((l) => l.label).join(", ")).toBe(true); + expect(boxes.map((l) => l.label)).toContain("26"); } else { expect(boxes.map((l) => l.label)).toContain("Target 26"); } @@ -481,7 +483,7 @@ test.describe("reference lines", () => { /** * The high and low points ECharts drew (markPoint): each label's words ("▲ 40"), its box and its dot's - * middle in the chart's pixels, the dot's fill and the glyph's colour; the plot's box with them. + * middle in the chart's pixels, the dot's fill, the glyph's and the value's colour; the plot's box with them. */ const drawnPoints = (chartEl) => chartEl.evaluate(async (el) => { @@ -499,7 +501,7 @@ const drawnPoints = (chartEl) => if (text.transform) r.applyTransform(text.transform); e.updateTransform(); const [x, y] = e.transform ? [e.transform[4], e.transform[5]] : [e.x, e.y]; - points.push({ label: `${glyph[1]} ${glyph[2]}`, box: { x: r.x, y: r.y, width: r.width, height: r.height }, dot: { x, y }, fill: e.style.fill, glyph: text.style.rich?.s?.fill ?? null }); + points.push({ label: `${glyph[1]} ${glyph[2]}`, box: { x: r.x, y: r.y, width: r.width, height: r.height }, dot: { x, y }, fill: e.style.fill, glyph: text.style.rich?.s?.fill ?? text.style.fill ?? null, ink: text.style.fill ?? null }); } return { grid: { x: grid.x, y: grid.y, width: grid.width, height: grid.height }, points }; }); @@ -511,17 +513,20 @@ test.describe("high and low points (#574)", () => { const ON = { average: false, trend: false, target: null, extremes: true }; for (const [width, theme] of [[1440, "light"], [1440, "dark"], [390, "light"], [390, "dark"]]) { - test(`lines at ${width} px, ${theme}: a dot in the series' colour at each highest and lowest value, the label inside the plot, none over another`, async ({ page }) => { + test(`lines at ${width} px, ${theme}: a dot in the series' colour at each highest and lowest value, the label in the text colour inside the plot, none over another`, async ({ page }) => { await page.setViewportSize({ width, height: 900 }); await page.goto("pages/host.html"); const chartEl = await mount(page, { type: "line", referenceLines: ON }, { theme }); const { grid, points } = await drawnPoints(chartEl); expect(points.map((p) => p.label).sort()).toEqual(["▲ 40", "▲ 7", "▼ 10", "▼ 3"]); - // the dot and the glyph in A's and B's series tokens + // the dot in A's and B's series tokens; the glyph and the value in the text colour (#913) const of = (label) => points.find((p) => p.label === label); expect(await asRgb(page, of("▲ 40").fill)).toBe(await tokenColor(page, "--pk-chart-1")); - expect(await asRgb(page, of("▲ 40").glyph)).toBe(await tokenColor(page, "--pk-chart-1")); expect(await asRgb(page, of("▼ 3").fill)).toBe(await tokenColor(page, "--pk-chart-2")); + for (const label of ["▲ 40", "▼ 3"]) { + expect(await asRgb(page, of(label).glyph)).toBe(await tokenColor(page, "--pk-muted")); + expect(await asRgb(page, of(label).ink)).toBe(await tokenColor(page, "--pk-muted")); + } // the highest above its dot, the lowest below it, each at its value expect(of("▲ 40").box.y + of("▲ 40").box.height).toBeLessThanOrEqual(of("▲ 40").dot.y); expect(of("▼ 10").box.y).toBeGreaterThanOrEqual(of("▼ 10").dot.y); diff --git a/tests/browser/chart/types.spec.js b/tests/browser/chart/types.spec.js index 61ccdbbe8..d337566ab 100644 --- a/tests/browser/chart/types.spec.js +++ b/tests/browser/chart/types.spec.js @@ -1,6 +1,6 @@ // Two chart types (#518) picked in Chart settings by real clicks: bars and lines (the first value as -// bars, the others as lines on an axis of their own) and a treemap (a tile per category, its label in -// the token colour that reads on it). The drawn marks come from the chart's own model. +// bars, the others as lines on an axis of their own) and a treemap (a tile per category, its label on a +// plate in the background colour, fill-labels.spec.js). The drawn marks come from the chart's own model. import { installContrast } from "../contrast.js"; import { expect, test } from "../fixtures.js"; import { mountReport } from "./report.js"; @@ -26,14 +26,14 @@ async function mount(page, view, { theme = "light", width = 1440 } = {}) { return page.locator("#types-report"); } -/** The series ECharts drew: type, value axis and, for a treemap, each tile's fill and label colour. */ +/** The series ECharts drew: type, value axis and, for a treemap, its tiles and its labels' plate. */ const drawnSeries = (report) => report.getByTestId("pivot-chart").evaluate(async (el) => { const { getInstanceByDom } = await import("echarts/core"); const chart = getInstanceByDom(el); if (!chart || !chart.getZr().animation.isFinished()) return null; const option = chart.getOption(); - return option.series.map((s) => ({ type: s.type, axis: s.yAxisIndex ?? 0, tiles: s.type === "treemap" ? s.data.map((d) => ({ name: d.name, fill: d.itemStyle?.color, ink: d.label?.color, outline: d.label?.textBorderColor ?? null })) : null, axes: (option.yAxis ?? []).length })); + return option.series.map((s) => ({ type: s.type, axis: s.yAxisIndex ?? 0, tiles: s.type === "treemap" ? s.data.map((d) => ({ name: d.name, fill: d.itemStyle?.color, own: d.label ?? null })) : null, plate: s.label?.rich?.plate ?? null, axes: (option.yAxis ?? []).length })); }); /** WCAG contrast of two opaque colours the page resolves. */ @@ -72,18 +72,19 @@ for (const [width, theme] of [ [390, "light"], [390, "dark"] ]) { - test(`treemap at ${width} px, ${theme}: a tile per region, each label in the token colour that reads on its tile`, async ({ page }) => { + test(`treemap at ${width} px, ${theme}: a tile per region, each label on a plate it reads on`, async ({ page }) => { const report = await mount(page, { values: [TWO[0]], chart: { type: "bar" } }, { theme, width }); await report.getByTestId("view-settings").click(); await report.getByTestId("chart-treemap").click(); await expect.poll(async () => (await drawnSeries(report))?.[0]?.type).toBe("treemap"); - const [{ tiles }] = await drawnSeries(report); + const [{ tiles, plate }] = await drawnSeries(report); expect(tiles.map((t) => t.name).sort()).toEqual(["Central", "East", "North", "South", "West"]); - // the label reads at 4.5:1 on its tile, or against the outline it gets where no token does - for (const t of tiles) { - const ratio = await contrast(page, t.ink, t.outline ?? t.fill); - expect(ratio, `${t.name}: ${t.ink} on ${t.outline ?? t.fill}`).toBeGreaterThanOrEqual(4.5); - } + // every label the same: on a plate it reads on at 4.5:1, whatever the tile's colour. A tile's own + // label sets only its padding (the tile's middle), its words cut to the tile, or hides a label that + // does not fit; never a look of its own (fill-labels.spec.js) + expect(tiles.flatMap((t) => Object.keys(t.own ?? {}).filter((k) => !["padding", "formatter", "show"].includes(k)))).toEqual([]); + const ratio = await contrast(page, plate.color, plate.backgroundColor); + expect(ratio, `${plate.color} on ${plate.backgroundColor}`).toBeGreaterThanOrEqual(4.5); // no tip about pies: a treemap holds many parts await expect(report.getByText("A pie works for")).toHaveCount(0); }); diff --git a/tests/fill-contrast.js b/tests/fill-contrast.js new file mode 100644 index 000000000..83b703b8b --- /dev/null +++ b/tests/fill-contrast.js @@ -0,0 +1,76 @@ +// The contrast of text on a coloured fill in both themes, for tests of any package: a label's ink on +// the area under it (a chart's tile or cell, a zone's fill). The themes are the report's light and dark +// tokens (pivotkit-report's kept copy of styles.css, which its tokens test keeps in step); the maths is +// pivotkit-core's contrastOf (WCAG 2.2). A colour that is no hex or rgb() after its var() is resolved +// measures null, so a test sees it instead of passing it. +import { TEXT_CONTRAST, contrastOf } from "../packages/pivotkit-core/src/chart-colors.js"; +import { DARK_TOKENS, LIGHT_TOKENS } from "../packages/pivotkit-report/src/tokens.js"; + +/** The contrast text needs on its fill (WCAG 2.2 AA, normal text). */ +export const TEXT_MIN = TEXT_CONTRAST; + +/** The --pk-* colour tokens of each theme: the dark theme sets only what differs from the light one. */ +export const THEME_TOKENS = Object.freeze({ + light: LIGHT_TOKENS, + dark: Object.freeze({ ...LIGHT_TOKENS, ...DARK_TOKENS }) +}); + +/** + * A colour with its var() references resolved against `tokens` (at most a few steps deep). + * @param {string} value + * @param {Readonly>} tokens + * @returns {string} + */ +function resolveColor(value, tokens) { + let out = String(value ?? "").trim(); + for (let step = 0; step < 8; step++) { + const ref = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/.exec(out); + if (!ref) break; + out = String(tokens[ref[1]] ?? ref[2] ?? "").trim(); + } + return out; +} + +/** + * A style as pivotkit-core's chartThemeFrom and decorateOption read it: the theme's tokens, with + * `extra` over them, var() resolved. + * @param {Readonly>} tokens + * @param {Readonly>} [extra] + * @returns {{ getPropertyValue(name: string): string }} + */ +function tokenStyle(tokens, extra = {}) { + const all = { ...tokens, ...extra }; + return { getPropertyValue: (name) => resolveColor(all[name] ?? "", all) }; +} + +/** + * The contrast of `ink` on `fill`, both resolved against `tokens`; null when either is no colour + * contrastOf reads. + * @param {string} ink + * @param {string} fill + * @param {Readonly>} [tokens] + * @returns {number | null} + */ +export function contrastOnFill(ink, fill, tokens = {}) { + return contrastOf(resolveColor(ink, tokens), resolveColor(fill, tokens)); +} + +/** + * Every label's contrast on its fill in both themes: `labelsOf(style, tokens, theme)` gives the labels + * one theme draws, each `{ name, ink, fill }`. + * @param {(style: { getPropertyValue(name: string): string }, tokens: Readonly>, theme: "light" | "dark") => { name: string, ink: string, fill: string }[]} labelsOf + * @returns {{ theme: "light" | "dark", name: string, ink: string, fill: string, ratio: number | null }[]} + */ +export function fillContrasts(labelsOf) { + return /** @type {const} */ (["light", "dark"]).flatMap((theme) => { + const tokens = THEME_TOKENS[theme]; + return labelsOf(tokenStyle(tokens), tokens, theme).map((l) => ({ theme, ...l, ratio: contrastOnFill(l.ink, l.fill, tokens) })); + }); +} + +/** + * The labels of `fillContrasts` below TEXT_MIN, or unreadable, as lines a failed assertion names. + * @param {ReturnType} measured + * @param {number} [least] + */ +export const unreadable = (measured, least = TEXT_MIN) => measured.filter((m) => m.ratio === null || m.ratio < least).map((m) => `${m.theme} ${m.name}: ${m.ink} on ${m.fill} = ${m.ratio === null ? "unreadable" : m.ratio.toFixed(2)}`);