diff --git a/docs/assets/screenshots/chart-lines-level-dark.png b/docs/assets/screenshots/chart-lines-level-dark.png index df0722d0a..7a7461754 100644 Binary files a/docs/assets/screenshots/chart-lines-level-dark.png and b/docs/assets/screenshots/chart-lines-level-dark.png differ diff --git a/docs/assets/screenshots/chart-lines-level-light.png b/docs/assets/screenshots/chart-lines-level-light.png index 09172fd99..592d0b6a7 100644 Binary files a/docs/assets/screenshots/chart-lines-level-light.png and b/docs/assets/screenshots/chart-lines-level-light.png differ diff --git a/docs/assets/screenshots/field-menu-dark.png b/docs/assets/screenshots/field-menu-dark.png index 0167f9333..4455f2553 100644 Binary files a/docs/assets/screenshots/field-menu-dark.png and b/docs/assets/screenshots/field-menu-dark.png differ diff --git a/docs/assets/screenshots/field-menu-light.png b/docs/assets/screenshots/field-menu-light.png index b717bd8d3..7fc236770 100644 Binary files a/docs/assets/screenshots/field-menu-light.png and b/docs/assets/screenshots/field-menu-light.png differ diff --git a/docs/concepts/filters.md b/docs/concepts/filters.md index 6c81e7ff6..8f8a52981 100644 --- a/docs/concepts/filters.md +++ b/docs/concepts/filters.md @@ -225,6 +225,7 @@ menu as people see it): | "A to Z", "Z to A" | a `label` sort | | "Largest … first", "Smallest … first" | a `value` sort naming the value. Without a value the sort counts rows. | | "Custom order" | a `custom` sort | +| "Default order" | no entry: the field's entry is removed, and a field order the host gives comes back | A click on a header of the table writes the same entries ([sort with a click on a header](../use/filters.md#sort-with-a-click-on-a-header)): diff --git a/docs/features.md b/docs/features.md index c34a98a2d..d593aa490 100644 --- a/docs/features.md +++ b/docs/features.md @@ -91,8 +91,8 @@ the short version. The [comparison](compare.md) sets pivotkit beside other pivot ## Totals and sorting { #sorting } - Subtotals and grand totals on or off per axis ([totals](use/fields.md#the-table)). -- Sorting by label, by any value or in a custom order. A click on a header sorts - ([sorting](use/filters.md#sorting)). +- Sorting by label, by any value or in a custom order, and back to the default order. A click on a + header sorts ([sorting](use/filters.md#sorting)). ## The rows behind a number { #drill-down } diff --git a/docs/reference/react-layout.md b/docs/reference/react-layout.md index fc4b17451..540a76620 100644 --- a/docs/reference/react-layout.md +++ b/docs/reference/react-layout.md @@ -232,7 +232,7 @@ applies. | Menu | First level | Levels | | --- | --- | --- | -| A field on Rows or Columns | Sort (A to Z, Z to A side by side), sort by its one value, Filter, Top items, Move to, Remove field | Sort by value (two or more values, or a custom order), Filter, Group (dates), Number ranges (numbers), Top items, Move to | +| A field on Rows or Columns | Sort (A to Z, Z to A side by side), sort by its one value, Default order, Filter, Top items, Move to, Remove field | Sort by value (two or more values, or a custom order), Filter, Group (dates), Number ranges (numbers), Top items, Move to | | A field in Filters | Filter, Group (dates), Move to, Remove field | Filter, Group (dates), Move to | | A value | Summarize by, Show as, Number format, Highlight (side by side), Name, Move to, Remove field | Summarize by, Show as, Number format, Name, Move to | | Table settings | Totals, Rows (Expand all, Collapse all with what it keeps: "Show Region only") | | diff --git a/docs/use/charts.md b/docs/use/charts.md index 9f4d4b3a5..fc267764d 100644 --- a/docs/use/charts.md +++ b/docs/use/charts.md @@ -114,26 +114,26 @@ type you pick stays. **Chart settings** lists the chart types first. Below them is one row per topic: Value labels, Legend, Title, Axis, Tooltip, Reference lines, Series and Layout. Each row shows what is set and opens a level. **Back**, Escape or the left arrow goes back to the row. A topic the chart has nothing for -is left out: a pie has no Axis, a heatmap no Series. +is left out: a pie has no Axis, a heatmap no Legend or Series. A choice applies at once, and the menu stays open, so the chart behind it shows the change. The settings stay with the report: in saved views, links and the chart image. They also stay when the chart type changes. An **i** explains Group labels, Tooltip, Zoom slider, Series, Stacked to 100 % and the -labels of a pie. +labels of a pie. A line under Automatic, Every n-th, All on horizontal bars, Trend and Share in the tooltip says what each does. ![Chart settings: the chart types, then the rows Value labels, Legend, Title, Axis, Tooltip, Reference lines, Series and Layout](../assets/screenshots/chart-display-light.png#only-light) ![Chart settings: the chart types, then the rows Value labels, Legend, Title, Axis, Tooltip, Reference lines, Series and Layout](../assets/screenshots/chart-display-dark.png#only-dark) | Setting | Path | Choices | Default | | --- | --- | --- | --- | -| Value labels | Chart settings › Value labels | Automatic, Off, Value. A pie and a donut also offer Percent and Value and percent. | Automatic: a pie names its slices. A heatmap writes the numbers while there are 200 cells or fewer. Bars and lines write nothing. | -| Legend | Chart settings › Legend | Automatic, Bottom, Right, Off | Automatic: above the chart when there is more than one series. A pie and a donut always have one. | +| Value labels | Chart settings › Value labels | Automatic, Off, Value. A pie and a donut also offer Percent and Value and percent. | Automatic: a pie names its slices, or writes each share with its labels inside. A treemap writes each tile's name and value. A heatmap writes the numbers while it has 200 filled cells or fewer and its cells are large enough for them. Bars and lines write nothing. | +| Legend | Chart settings › Legend | Automatic, Bottom, Right, Off. Not for a treemap or a heatmap. | Automatic: above the chart when there is more than one series. A pie and a donut always have one. | | Title | Chart settings › Title | Any text. The × removes it at once. | none | -| Axis labels | Chart settings › Axis | Automatic, All (slanted), Every n-th | Automatic | +| Axis labels | Chart settings › Axis | Automatic, All (slanted), Every n-th. Horizontal bars: All instead of All (slanted). | Automatic: straight if the labels fit, else slanted; every n-th if still too many. Horizontal bars keep them straight and leave some out; their All writes every one straight, even where they overlap. Every n-th keeps them straight, with gaps so none overlap. | | Group labels | Chart settings › Axis | Automatic, On, Off. With two or more fields in Rows. | Automatic: shown while the chart has room for them | | Zoom slider | Chart settings › Axis | Automatic, On, Off | Automatic: more than 20 categories, or an axis that would leave out 3 names or more between two | | Tooltip | Chart settings › Tooltip | Automatic, All series | Automatic: the element under the pointer | -| Share in the tooltip | Chart settings › Tooltip | on, off. Not for a heatmap. | off | +| Share in the tooltip | Chart settings › Tooltip | on, off. Not for a heatmap. Sums and counts get their share of the total, such as 25%; averages and values below zero get none. See "The share in the tooltip" below. | off | | Series | Chart settings › Series | A switch per series, or per slice of a pie or a donut, with its colour beside it. One series is listed for its colour. | all shown, in the palette or the colours your app sets | | Stacked to 100 % | Chart settings › Layout | on, off. Stacked bars and areas of sums and counts. | off | | Reference lines | Chart settings › Reference lines | Average, Trend, High and low points, Target. Bars, lines and areas. See [below](#reference-lines). | none | diff --git a/docs/use/fields.md b/docs/use/fields.md index 7856b6bea..83739fd90 100644 --- a/docs/use/fields.md +++ b/docs/use/fields.md @@ -147,13 +147,14 @@ A row opens the topic's own level in the menu's place. The level's title names t that differs from the one the report starts with has a dot before it: "Filter · ● 4 of 12". A screen reader hears ", changed" after it. -![A field's menu: sort A to Z and Z to A side by side, sort by the value, then Filter, Top items and Move to, each with what is set](../assets/screenshots/field-menu-light.png#only-light) -![A field's menu: sort A to Z and Z to A side by side, sort by the value, then Filter, Top items and Move to, each with what is set](../assets/screenshots/field-menu-dark.png#only-dark) +![A field's menu: sort A to Z and Z to A side by side, sort by the value, Default order, then Filter, Top items and Move to, each with what is set](../assets/screenshots/field-menu-light.png#only-light) +![A field's menu: sort A to Z and Z to A side by side, sort by the value, Default order, then Filter, Top items and Move to, each with what is set](../assets/screenshots/field-menu-dark.png#only-dark) | Topic | What it offers | | --- | --- | | **Sort** | A to Z and Z to A side by side on the first level. For a date they read Oldest and Newest. While the field sorts by a value, the row says by which: "Largest Sum of Revenue first". | | Sort by value | With one value in the report: "Largest Sum of Revenue first" and "Smallest Sum of Revenue first" on the first level. With more values, or a custom order: a level **Sort by value**. It has a pair for each value that gives a number. When the field has a custom order, such as the seasons in the order of the year, it also has "Custom order" and "Custom order, reversed". See [sorting](filters.md#sorting). Its row names the sort in use. | +| Sort order | **Default order** on the first level: the field's own order. See [sorting](filters.md#sorting). Greyed out, with "Already the default order.", while the field sorts this way. | | **Filter** | A level that starts with a summary of what shows. Then come, for a date, its quick choices, such as "Last 2 years". For a month-of-the-year grouping these are the years combined. Then the values to keep, and its rules as sentences with what each keeps: the item itself compared, its total compared, a rule on its name. See [filters](filters.md). Its row says what the filter keeps: "4 of 12", "last 2 years (2025; 2026 has no data)", "from 2022", "Sum of Revenue > 1,000". A chip in **Filters** has a menu of its own: Filter, Group for a date, Name, Move to and Remove field. | | **Group** (dates) | A level with the data's range on top and three kinds of choice. One item per period: year, quarter, month, week, day. Same period, years combined: quarter, month, week of the year, weekday, hour. Or no grouping. See [dates](values.md#dates-and-number-ranges). | | **Number ranges** (numbers) | A level with the size of the ranges and where they start. See [ranges](values.md#number-ranges). | diff --git a/docs/use/filters.md b/docs/use/filters.md index fad2f4d34..5b3616891 100644 --- a/docs/use/filters.md +++ b/docs/use/filters.md @@ -210,6 +210,9 @@ The menu of a row or column field offers: values, **Sort by value** lists them. - **Custom order** sorts in an order the application gives the field, such as the seasons. A field with such an order is sorted in it when you place it. Choose A to Z to use names instead. +- **Default order** takes the field back to its own order: A to Z, oldest first for a date, or the + order the application gives it. It is not the report's start view. It ends a sort by a value or by + a column too. It is greyed out while the field already sorts this way. ??? info "Values that cannot sort" Values that give no number cannot sort: a list of distinct values, the first or last entry of a diff --git a/packages/pivotkit-element/CHANGELOG.md b/packages/pivotkit-element/CHANGELOG.md index 8788750ca..9caf484d1 100644 --- a/packages/pivotkit-element/CHANGELOG.md +++ b/packages/pivotkit-element/CHANGELOG.md @@ -11,6 +11,12 @@ All notable changes to `pivotkit-element` are documented in this file. The forma - The import preview lets a person pick a column's decimal mark. See pivotkit-react's changelog. The import group grows to 23.7 KiB gzip on an official Node 24 build, its budget to 23.9 KiB ([#787](https://github.com/eizedev/pivotkit/issues/787)). +- A field's menu has Default order, and Chart settings says what its unclear choices do. See + pivotkit-react's changelog. On an official Node 24 build the menus group grows to 60.3 KiB gzip, its budget + to 60.3 KiB, and the texts group, with the German menu texts, to 8.7 KiB, its budget to 8.8 KiB + ([#916](https://github.com/eizedev/pivotkit/issues/916), + [#917](https://github.com/eizedev/pivotkit/issues/917), + [#963](https://github.com/eizedev/pivotkit/issues/963)). ### Changed diff --git a/packages/pivotkit-element/build.js b/packages/pivotkit-element/build.js index 70452403c..9dc45db91 100644 --- a/packages/pivotkit-element/build.js +++ b/packages/pivotkit-element/build.js @@ -208,7 +208,7 @@ async function licenses(metafile) { * can make the first load larger. * `--size` fails above it. */ -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.9, report: 29.7, 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: 60.3, texts: 8.8, unused: 6.5, import: 23.9, report: 29.7, 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 aee18ab4b..79a98e880 100644 --- a/packages/pivotkit-react/CHANGELOG.md +++ b/packages/pivotkit-react/CHANGELOG.md @@ -27,6 +27,19 @@ All notable changes to `pivotkit-react` are documented in this file. The format The note points there first. New texts `markOf`, `markQuestion` and `markOption` in `labels.dataImport` ([#787](https://github.com/eizedev/pivotkit/issues/787)). +- A field's menu on Rows or Columns has **Default order** ("Standardreihenfolge"), in a group named + "Sort order". It takes the field back to its own order: A to Z, oldest first, or the host's + order. It ends a sort by a value or by a column too. While the field already sorts this way, it + is greyed out with "Already the default order.". The search finds it by "reset" and "unsorted" + too, and Undo names it "default order of Region". New texts `sortOrder`, `sortDefault`, + `sortIsDefault`, `sortDefaultKeywords` and `steps.sortDefault` + ([#917](https://github.com/eizedev/pivotkit/issues/917)). +- Chart settings says what a choice does where its name alone does not. A line under Automatic says + what it shows on this chart: under Value labels, Legend and Axis labels. Lines under Every n-th, + Trend and Share in the tooltip say what they do. The Tooltip's **i** says when Share in the + tooltip adds a share: for sums and counts, not for averages or values below zero. New texts + `chartNotes` + ([#916](https://github.com/eizedev/pivotkit/issues/916)). ### Changed @@ -46,6 +59,17 @@ All notable changes to `pivotkit-react` are documented in this file. The format ### Fixed +- A heatmap's Chart settings no longer list Legend. Its colour scale takes the legend's place, so + none of its choices changed anything + ([#916](https://github.com/eizedev/pivotkit/issues/916)). +- On horizontal bars, Chart settings › Axis names its choice **All** ("Alle"), not "All (slanted)": + those labels are never slanted. A line under it says that it writes every name straight. New text + `axisLabelAllStraight` + ([#963](https://github.com/eizedev/pivotkit/issues/963)). +- A menu's search shows a greyed-out choice greyed out, with its reason, as its level does. Before, + a hit such as Default order or Reset filter looked like one to pick and did nothing. +- The line under a menu choice, what it does or why it is greyed out, is read as the choice's + description, not as part of its name. - 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 diff --git a/packages/pivotkit-react/src/labels-de.js b/packages/pivotkit-react/src/labels-de.js index fba3e63ef..3595c4fe5 100644 --- a/packages/pivotkit-react/src/labels-de.js +++ b/packages/pivotkit-react/src/labels-de.js @@ -174,6 +174,7 @@ export const de = { moved: "{field} nach {zone} verschoben", reordered: "Reihenfolge in {zone}", sort: "Sortierung von {field}", + sortDefault: "Standardreihenfolge von {field}", group: "Gruppierung von {field}", rename: "Name von {field}", filter: "Filter auf {field}", diff --git a/packages/pivotkit-react/src/labels.js b/packages/pivotkit-react/src/labels.js index 26d2eb2d5..1561beb28 100644 --- a/packages/pivotkit-react/src/labels.js +++ b/packages/pivotkit-react/src/labels.js @@ -227,6 +227,7 @@ export const en = { moved: "{field} moved to {zone}", reordered: "order in {zone}", sort: "sort of {field}", + sortDefault: "default order of {field}", group: "grouping of {field}", rename: "name of {field}", filter: "filter on {field}", diff --git a/packages/pivotkit-react/src/levels.jsx b/packages/pivotkit-react/src/levels.jsx index f7a629158..03b504878 100644 --- a/packages/pivotkit-react/src/levels.jsx +++ b/packages/pivotkit-react/src/levels.jsx @@ -17,7 +17,7 @@ import { Icon } from "./icons.jsx"; import { fill } from "./labels.js"; import { ClearInput } from "./clear-input.jsx"; import { HelpContext } from "./help.js"; -import { Group } from "./popover.jsx"; +import { Group, menuItemRole } from "./popover.jsx"; import { SettingInfo } from "./section.jsx"; import { rowName, searchEntries, searchHits, stepIndex, typeAheadIndex } from "./menu-topics.js"; @@ -202,12 +202,13 @@ export function MenuList({ label, labelledBy, describedBy, className, close, chi * label?: string, className?: string, disabled?: boolean, reason?: string, haspopup?: "menu" | "dialog", level?: string, * description?: string | null, current?: boolean, note?: string, children?: React.ReactNode }} props * `plain`: the text type-ahead matches; `start`: takes Tab first; `level`: the topic it opens; - * `note`: a line under the text of an entry that can be chosen, read with it (what a pick does); + * `note`: a line under the text of an entry that can be chosen (what a pick does); it and `reason` are + * read as the entry's description, not as part of its name; * `description`: an explanation a screen reader reads with it (the "i" next to it shows it); * `current`: the entry shown now (the view loaded), with a check and aria-current */ export function MenuItem({ id, text, onSelect, checked, checkbox, hint, icon, danger, testId, start, plain, label, className, disabled, reason, haspopup, level, description, current, note, children }) { - const role = checked === undefined ? "menuitem" : checkbox ? "menuitemcheckbox" : "menuitemradio"; + const role = menuItemRole(checked, checkbox); const reasonId = useId(); // the line under the text: why it is off, or what choosing it does const sub = disabled ? reason : note; @@ -236,7 +237,8 @@ export function MenuItem({ id, text, onSelect, checked, checkbox, hint, icon, da {text} {sub ? ( - + // out of the name (aria-hidden): a screen reader reads it once, as the description (aria-describedby) + ) : null} @@ -469,7 +471,7 @@ function SearchHits({ hits, labels, onPick, onOpen, close }) { return ( {hits.map((h) => ( - (h.choice ? onPick(h.choice) : onOpen(h.topic.id, undefined, h.focus))} /> + (h.choice ? onPick(h.choice) : onOpen(h.topic.id, undefined, h.focus))} /> ))} ); diff --git a/packages/pivotkit-react/src/menu-labels-de.js b/packages/pivotkit-react/src/menu-labels-de.js index 8f1826d81..ce892b00f 100644 --- a/packages/pivotkit-react/src/menu-labels-de.js +++ b/packages/pivotkit-react/src/menu-labels-de.js @@ -26,7 +26,7 @@ export const de = { drillJson: "Die Zeilen als JSON-Objekte, mit den Feldnamen und Rohwerten der Daten, für ein Programm.", groupLabels: "Mit zwei oder mehr Feldern in Zeilen: die Einträge des äußeren Felds einmal unter der Achse, unter ihren Kategorien.", chartColors: "Ein Schalter blendet jede Reihe oder jedes Segment ein oder aus. Die Farbe daneben legt seine Farbe nach dem Namen fest, in der Ansicht und in jedem Diagramm mit diesem Namen.", - tooltip: "Automatisch: Ein Balken, Segment oder Punkt zeigt nur seinen Wert. Dazwischen erscheinen alle Reihen. Gestapelte Summen und Anzahlen zeigen auch den Gesamtwert. Alle Reihen: immer alle Reihen dieser Kategorie.", + tooltip: "Automatisch: Ein Balken, Segment oder Punkt zeigt nur seinen Wert. Dazwischen erscheinen alle Reihen. Gestapelte Summen und Anzahlen zeigen auch den Gesamtwert. Alle Reihen: immer alle Reihen dieser Kategorie. Anteil im Tooltip ergänzt bei Summen und Anzahlen den Anteil: an der Summe der Reihe bei einer Reihe, an der Summe der Kategorie bei mehreren. Nicht bei Mittelwerten, Werten unter null oder einer Kategorie mit nur einem Wert.", stackPercent: "Jeder Stapel füllt die Achse; jeder Teil zeigt seinen Anteil. Auch die Wertbeschriftungen zeigen den Anteil. Nur für Summen und Anzahlen. Ein Stapel mit Teilen unter null füllt die Achse nicht, einer mit der Summe null fehlt.", zoom: "Ein Schieber unter der Achse zeigt einen Teil der Kategorien. Automatisch: bei mehr als 20 Kategorien, oder wenn die Achse 3 Namen oder mehr zwischen zweien auslassen müsste. Mit dem Fokus darauf bewegen ihn die Pfeiltasten. Aus zeigt alle Kategorien. Dateien und Drucke zeigen alle Kategorien.", labelPosition: "Außen: Name und Zahl jedes Segments daneben. Innen: die Zahl auf dem Segment, die Namen in der Legende; außen, wenn der Ring eines Donuts dafür zu schmal ist.", @@ -46,6 +46,10 @@ export const de = { sortByValue: "Nach Wert sortieren", sortOldestShort: "Älteste", sortNewestShort: "Neueste", + sortOrder: "Reihenfolge", + sortDefault: "Standardreihenfolge", + sortIsDefault: "Bereits die Standardreihenfolge.", + sortDefaultKeywords: "zurücksetzen unsortiert", filterTopic: "Filter", filterAll: "Alle", groupTopic: "Gruppieren", @@ -380,6 +384,7 @@ export const de = { labelPositionNames: { outside: "Außen", inside: "Innen" }, axisLabels: "Achsenbeschriftung", axisLabelNames: { auto: "Automatisch", all: "Alle (schräg)", nth: "Jede n-te" }, + axisLabelAllStraight: "Alle", groupLabels: "Gruppen unter der Achse", groupLabelNames: { auto: "Automatisch", on: "Ein", off: "Aus" }, tooltip: "Tooltip", @@ -392,6 +397,21 @@ export const de = { chartAxis: "Achse", chartLayout: "Anordnung", tooltipShare: "Anteil im Tooltip", + chartNotes: { + none: "Keine; der Tooltip zeigt die Zahlen.", + names: "Name jedes Segments.", + shares: "Anteil jedes Segments.", + treemap: "Name und Wert jeder Kachel.", + heatmap: "Die Zahlen, bis 200 gefüllte Zellen, wenn die Zellen groß genug sind.", + legend: "Oben, ab zwei Reihen.", + legendSlices: "Oben.", + axis: "Gerade, wenn sie passen, sonst schräg; jede n-te, wenn es noch zu viele sind.", + axisSide: "Alle, wenn sie passen, sonst jede n-te.", + nth: "Gerade, mit Lücken ohne Überlappung.", + allStraight: "Jeder Name, gerade, auch wo sie sich überlappen.", + trend: "Eine Gerade, die am besten zu den Werten passt.", + share: "Summen und Anzahlen mit ihrem Anteil an der Summe, etwa 25 %. Nicht bei Mittelwerten." + }, colorOf: "Farbe von {name}", colorDefault: "Standard", colorRemove: "Entfernen", diff --git a/packages/pivotkit-react/src/menu-labels.js b/packages/pivotkit-react/src/menu-labels.js index e0396b613..3037567e9 100644 --- a/packages/pivotkit-react/src/menu-labels.js +++ b/packages/pivotkit-react/src/menu-labels.js @@ -31,7 +31,7 @@ export const en = { drillJson: "The rows as JSON objects, with the data's field names and raw values, for a program.", groupLabels: "With two or more fields in Rows: the outer field's items written once under the axis, below their categories.", chartColors: "A switch shows or hides each series or slice. The colour beside it fixes its colour by name, in the view and in every chart that shows that name.", - tooltip: "Automatic: a bar, segment or point shows only itself. Between them, every series shows. Stacked sums and counts also show the total. All series: always every series of that category.", + tooltip: "Automatic: a bar, segment or point shows only itself. Between them, every series shows. Stacked sums and counts also show the total. All series: always every series of that category. Share in the tooltip adds the share of sums and counts: of the series' total with one series, of the category's total with several. Not for averages, values below zero or a category with one value left.", stackPercent: "Each stack fills the axis; each part shows its share. Value labels show the share too. Only for sums and counts. A stack with parts below zero does not fill the axis, and one that adds up to nothing is left out.", zoom: "A slider under the axis shows a part of the categories. Automatic: with more than 20 categories, or when the axis would leave out 3 names or more between two. The arrow keys move it once it has the focus. Off shows every category. Files and prints show every category.", labelPosition: "Outside: each slice's name and number next to it. Inside: the number on the slice, the names in the legend; outside when a donut's ring is too thin for it.", @@ -54,6 +54,11 @@ export const en = { sortByValue: "Sort by value", sortOldestShort: "Oldest", sortNewestShort: "Newest", + // back to the order of a new view (#917), and why it is greyed out + sortOrder: "Sort order", + sortDefault: "Default order", + sortIsDefault: "Already the default order.", + sortDefaultKeywords: "reset unsorted", filterTopic: "Filter", filterAll: "All", groupTopic: "Group", @@ -439,6 +444,8 @@ export const en = { labelPositionNames: { outside: "Outside", inside: "Inside" }, axisLabels: "Axis labels", axisLabelNames: { auto: "Automatic", all: "All (slanted)", nth: "Every n-th" }, + // horizontal bars write every name straight (#963) + axisLabelAllStraight: "All", groupLabels: "Group labels under the axis", groupLabelNames: { auto: "Automatic", on: "On", off: "Off" }, tooltip: "Tooltip", @@ -451,6 +458,24 @@ export const en = { chartAxis: "Axis", chartLayout: "Layout", tooltipShare: "Share in the tooltip", + // the line under a choice of Chart settings that says what it does (#916): what Automatic + // writes or where it puts the legend, by chart, Every n-th, All on horizontal bars, the trend + // and the share in the tooltip + chartNotes: { + none: "None; the tooltip shows the numbers.", + names: "Each slice's name.", + shares: "Each slice's share.", + treemap: "Each tile's name and value.", + heatmap: "The numbers, up to 200 filled cells, when the cells are large enough.", + legend: "Above, with two or more series.", + legendSlices: "Above.", + axis: "Straight if they fit, else slanted; every n-th if still too many.", + axisSide: "All if they fit, else every n-th.", + nth: "Straight, with gaps so none overlap.", + allStraight: "Every name, straight, even where they overlap.", + trend: "A straight line that best fits the values.", + share: "Sums and counts with their share of the total, such as 25%. Not for averages." + }, colorOf: "Colour of {name}", colorDefault: "Default", colorRemove: "Remove", diff --git a/packages/pivotkit-react/src/menu-topics.js b/packages/pivotkit-react/src/menu-topics.js index 5ddc5c9e0..02ac5045a 100644 --- a/packages/pivotkit-react/src/menu-topics.js +++ b/packages/pivotkit-react/src/menu-topics.js @@ -103,9 +103,28 @@ function moveTopic(view, zone, index, count, labels, name, type, defaults) { return { id: "move", title: labels.moveToTitle, kind: "menu", icon: "swap", groups: [{ choices }] }; } +/** + * Default order: back to the order of a new view from any sort, by a column too (#917), as Reset + * filter does for the filter. That order has no sort entry (A to Z, oldest first), or it is the + * host's order, which comes back without one (withHostOrders). Greyed out while the field sorts so. + * @param {any} view @param {string} field @param {string} name the field's name in the note + * @param {any} sort the field's sort entry, if any + * @param {boolean} hosted the host gives the field an order: `hostOrder` (fieldDefaults.order) + * @param {any[]} hostOrder + * @param {any} labels + * @returns {Topic} + */ +function defaultOrderTopic(view, field, name, sort, hosted, hostOrder, labels) { + // a custom order's items may have taken the field's type: compared entry by entry, as text + const isHostOrder = () => sort.by === "custom" && sort.order === "asc" && sort.items.length === hostOrder.length && sort.items.every((x, i) => String(x) === String(hostOrder[i])); + const isDefault = !sort || (hosted ? isHostOrder() : sort.by === "label" && sort.order === "asc"); + const choice = { id: "sort-default", text: labels.sortDefault, icon: "reset", keywords: labels.sortDefaultKeywords, disabled: isDefault, reason: isDefault ? labels.sortIsDefault : undefined, change: () => ({ view: setSort(view, field, null), note: { step: "sortDefault", field: name } }) }; + return { id: "sortDefault", title: labels.sortOrder, kind: "inline", groups: [{ choices: [choice] }] }; +} + /** * The topics of a field's menu on Rows or Columns: sort by label (side by side), sort by a value, - * Filter, the grouping of a date or a number, Top items, Move to. + * Default order, Filter, the grouping of a date or a number, Top items, Name, Move to. * @param {{ view: any, zone: string, index: number, field: string, types: Map, * labels: any, locale: string, state?: any, defaultsOf?: (field: string) => any, encoded?: any, limits?: Partial }} input * `state`: the chip's state (zones.jsx), for the filter's "3 of 12"; `limits`: the host's (LimitsContext); `encoded`: the data, for the @@ -162,6 +181,7 @@ export function axisTopics({ view, zone, index, field, types, labels, locale, st }, // one value: largest and smallest first right here; more: a level of their own { id: "sortValue", title: labels.sortByValue, kind: byValue.length <= 2 ? "inline" : "menu", icon: "sortDesc", state: otherSort, changed: Boolean(otherSort), groups: [{ choices: byValue }] }, + defaultOrderTopic(view, field, name, sort, hosted, hostOrder, labels), filterTopic({ view, field, labels, locale, state, encoded }) ]; if (date) { @@ -618,6 +638,58 @@ export function moreTopics({ labels, tips, explanations, act }) { /** The value labels a chart type offers: a share in percent is a pie's and a donut's. */ const VALUE_LABELS = Object.freeze({ slices: ["auto", "off", "value", "percent", "both"], other: ["auto", "off", "value"] }); +/** + * Chart settings' Tooltip: what it covers (bars, lines, areas: the element or all series) and the + * share of the total in it (#54), with a line that says what the share adds (#916). + * @param {any} chart the view's chart settings @param {boolean} axis the chart has axes @param {any} labels + * @param {(key: string, value: string, text: string, id: string) => Choice} pickOf one choice of several + * @param {(key: string, text: string, id: string) => Choice} flip a switch + * @returns {Topic} + */ +function tooltipTopic(chart, axis, labels, pickOf, flip) { + const mode = chart.tooltip ?? "auto"; + const state = [axis ? labels.tooltipNames[mode] : null, chart.tooltipShare ? labels.tooltipShare : null].filter(Boolean).join(", "); + return { + id: "tooltip", + title: labels.tooltip, + kind: "menu", + info: axis ? "tooltip" : undefined, + state: state || null, + changed: mode !== "auto" || Boolean(chart.tooltipShare), + groups: [...(axis ? [{ choices: ["auto", "axis"].map((v) => pickOf("tooltip", v, labels.tooltipNames[v], `tooltip-${v}`)) }] : []), { choices: [{ ...flip("tooltipShare", labels.tooltipShare, "chart-tooltip-share"), note: labels.chartNotes.share }] }] + }; +} + +/** + * The names of the Axis labels choices: horizontal bars never slant their labels, so their All is + * "All", not "All (slanted)" (#963). + * @param {string} drawn + * @param {any} labels + * @returns {Record} + */ +function axisLabelNames(drawn, labels) { + return drawn === "horizontal" ? { ...labels.axisLabelNames, all: labels.axisLabelAllStraight } : labels.axisLabelNames; +} + +/** + * The lines under the choices of Chart settings whose names alone do not say what they do (#916): + * what Automatic does on this chart, as pivotkit-core's chart.js draws it, and what Every n-th does. + * @param {string} drawn the type drawn @param {boolean} pie a slice type @param {boolean} legend the chart has a legend + * @param {any} chart the view's chart settings @param {any} labels + * @returns {{ valueLabels: Record, legend: Record, axisLabels: Record }} + */ +function chartNotes(drawn, pie, legend, chart, labels) { + const say = labels.chartNotes; + // a pie's names, or its shares inside; a treemap's names and values; a heatmap's numbers + const autoLabels = pie ? (chart.labelPosition === "inside" ? "shares" : "names") : legend ? "none" : drawn; + return { + valueLabels: { auto: say[autoLabels] }, + legend: { auto: say[pie ? "legendSlices" : "legend"] }, + // horizontal bars write their labels straight: Automatic leaves some out, All lets them overlap (#963) + axisLabels: drawn === "horizontal" ? { auto: say.axisSide, all: say.allStraight, nth: say.nth } : { auto: say.axis, nth: say.nth } + }; +} + /** * The topics of Chart settings after its types (#106, #580), each a row with what is set that opens * its level: Value labels, Legend, Title (a form), Axis (axis and group labels, the zoom slider), @@ -641,14 +713,15 @@ export function chartTopics({ view, drawn, labels, names, act, lines = { rules: const chart = view.chart; const pie = SLICE_TYPES.includes(drawn); const axis = CHART_TYPES[drawn]?.axis ?? false; - // a treemap names each tile on it: no legend - const legend = drawn !== "treemap"; + // a treemap names each tile on it, a heatmap has its colour scale: no legend + const legend = drawn !== "treemap" && drawn !== "heatmap"; /** One choice of several: radio, its patch applied at once. @returns {Choice} */ const pickOf = (/** @type {string} */ key, /** @type {string} */ value, /** @type {string} */ text, /** @type {string} */ id, /** @type {string | undefined} */ info = undefined) => ({ id, text, checked: (chart[key] ?? null) === value, info, run: () => act.display({ [key]: value }) }); /** A switch. @returns {Choice} */ const flip = (/** @type {string} */ key, /** @type {string} */ text, /** @type {string} */ id, /** @type {string | undefined} */ info = undefined) => ({ id, text, checkbox: true, checked: Boolean(chart[key]), info, run: () => act.display({ [key]: !chart[key] }) }); // a pie's "percent" on another type draws the value: it shows as "Value" there const valueLabels = !pie && (chart.valueLabels === "percent" || chart.valueLabels === "both") ? "value" : chart.valueLabels; + const notes = chartNotes(drawn, pie, legend, chart, labels); /** @type {Topic[]} */ const topics = [ { @@ -657,41 +730,29 @@ export function chartTopics({ view, drawn, labels, names, act, lines = { rules: kind: "menu", state: labels.valueLabelNames[valueLabels], changed: valueLabels !== "auto", - groups: [{ choices: (pie ? VALUE_LABELS.slices : VALUE_LABELS.other).map((v) => ({ ...pickOf("valueLabels", v, labels.valueLabelNames[v], `labels-${v}`), checked: valueLabels === v })) }] + groups: [{ choices: (pie ? VALUE_LABELS.slices : VALUE_LABELS.other).map((v) => ({ ...pickOf("valueLabels", v, labels.valueLabelNames[v], `labels-${v}`), checked: valueLabels === v, note: notes.valueLabels[v] })) }] }, - ...(legend ? [/** @type {Topic} */ ({ id: "legend", title: labels.legend, kind: "menu", state: labels.legendNames[chart.legend], changed: chart.legend !== "auto", groups: [{ choices: ["auto", "bottom", "right", "off"].map((v) => pickOf("legend", v, labels.legendNames[v], `legend-${v}`)) }] })] : []), + ...(legend ? [/** @type {Topic} */ ({ id: "legend", title: labels.legend, kind: "menu", state: labels.legendNames[chart.legend], changed: chart.legend !== "auto", groups: [{ choices: ["auto", "bottom", "right", "off"].map((v) => ({ ...pickOf("legend", v, labels.legendNames[v], `legend-${v}`), note: notes.legend[v] })) }] })] : []), { id: "title", title: labels.chartTitle, kind: "panel", state: chart.title || labels.chartTitleNone, changed: Boolean(chart.title) } ]; if (axis) { const groups = view.rows.length >= 2; + const axisNames = axisLabelNames(drawn, labels); const off = [groups && chart.groupLabels !== "auto" ? `${labels.groupLabels.toLowerCase()} ${labels.groupLabelNames[chart.groupLabels].toLowerCase()}` : null, chart.zoom !== "auto" ? `${labels.zoom.toLowerCase()} ${labels.zoomNames[chart.zoom].toLowerCase()}` : null].filter(Boolean); topics.push({ id: "axis", title: labels.chartAxis, kind: "menu", - state: [labels.axisLabelNames[chart.axisLabels], ...off].join(", "), + state: [axisNames[chart.axisLabels], ...off].join(", "), changed: chart.axisLabels !== "auto" || off.length > 0, groups: [ - { title: labels.axisLabels, choices: ["auto", "all", "nth"].map((v) => pickOf("axisLabels", v, labels.axisLabelNames[v], `axis-${v}`)) }, + { title: labels.axisLabels, choices: ["auto", "all", "nth"].map((v) => ({ ...pickOf("axisLabels", v, axisNames[v], `axis-${v}`), note: notes.axisLabels[v] })) }, ...(groups ? [{ title: labels.groupLabels, choices: ["auto", "on", "off"].map((v) => pickOf("groupLabels", v, labels.groupLabelNames[v], `groups-${v}`, v === "auto" ? "groupLabels" : undefined)) }] : []), { title: labels.zoom, choices: ["auto", "on", "off"].map((v) => pickOf("zoom", v, labels.zoomNames[v], `zoom-${v}`, v === "auto" ? "zoom" : undefined)) } ] }); } - if (drawn !== "heatmap") { - // what the tooltip covers (bars, lines, areas) and the share of the total in it (#54) - const mode = chart.tooltip ?? "auto"; - const state = [axis ? labels.tooltipNames[mode] : null, chart.tooltipShare ? labels.tooltipShare : null].filter(Boolean).join(", "); - topics.push({ - id: "tooltip", - title: labels.tooltip, - kind: "menu", - info: axis ? "tooltip" : undefined, - state: state || null, - changed: mode !== "auto" || Boolean(chart.tooltipShare), - groups: [...(axis ? [{ choices: ["auto", "axis"].map((v) => pickOf("tooltip", v, labels.tooltipNames[v], `tooltip-${v}`)) }] : []), { choices: [flip("tooltipShare", labels.tooltipShare, "chart-tooltip-share")] }] - }); - } + if (drawn !== "heatmap") topics.push(tooltipTopic(chart, axis, labels, pickOf, flip)); if (axis && CHART_TYPES[drawn]?.lines !== false) { // Reference lines: a level of switches (Average, Trend, High and low points), the target's row that opens its form // (the hidden topic "linesTarget", toolbar-panels.jsx), and why a line is off as a reason @@ -708,7 +769,7 @@ export function chartTopics({ view, drawn, labels, names, act, lines = { rules: /** @type {Choice[]} */ const choices = [ { id: "line-average", text: words.average, checkbox: true, checked: now.average, disabled: !rules.average, reason: rules.average ? undefined : say(total), run: () => set({ average: !now.average }) }, - { id: "line-trend", text: words.trend, checkbox: true, checked: now.trend, disabled: !rules.trend, reason: rules.trend ? undefined : say([...total, "noTime"]), run: () => set({ trend: !now.trend }) }, + { id: "line-trend", text: words.trend, checkbox: true, checked: now.trend, disabled: !rules.trend, note: labels.chartNotes.trend, reason: rules.trend ? undefined : say([...total, "noTime"]), run: () => set({ trend: !now.trend }) }, // the high and low points (#574): where an average is drawn, with its reason where not { id: "line-extremes", text: labels.linesExtremes, checkbox: true, checked: Boolean(now.extremes), disabled: !rules.extremes, reason: rules.extremes ? undefined : say(total), run: () => set({ extremes: !now.extremes }) }, { id: "line-target", text: words.target, hint: now.target !== null ? targetText : labels.targetNone, open: "linesTarget", disabled: !rules.target, reason: rules.target ? undefined : say(["noTotal", "percentStack", "mixedUnits"]) }, diff --git a/packages/pivotkit-react/src/popover.jsx b/packages/pivotkit-react/src/popover.jsx index 72e1ee9e0..9983f7853 100644 --- a/packages/pivotkit-react/src/popover.jsx +++ b/packages/pivotkit-react/src/popover.jsx @@ -479,6 +479,13 @@ export function Group({ title, label, menu = false, head, after, children, testI ); } +/** + * The role of a menu's item: a plain item, a toggle of its own (`checkbox`) or one of a set of choices. + * @param {boolean | undefined} checked undefined for an item that is not checked or unchecked + * @param {boolean} [checkbox] + */ +export const menuItemRole = (checked, checkbox) => (checked === undefined ? "menuitem" : checkbox ? "menuitemcheckbox" : "menuitemradio"); + /** * One option of a menu or of a chip's settings: one line. `hint` is a short second line that belongs * to the option (a date unit's example); `reason` says why a disabled option does nothing and shows @@ -491,7 +498,7 @@ export function Group({ title, label, menu = false, head, after, children, testI */ export function Option({ onSelect, icon, checked, checkbox = false, children, hint, reason, inMenu = false, disabled, danger, tone, testId, current }) { const second = disabled && reason ? reason : hint; - const role = inMenu ? (checked === undefined ? "menuitem" : checkbox ? "menuitemcheckbox" : "menuitemradio") : undefined; + const role = inMenu ? menuItemRole(checked, checkbox) : undefined; // an item of a menu that does nothing now stays in the arrow keys' way (aria-disabled), so its // reason is heard (WAI-ARIA Authoring Practices: disabled menu items are focusable) const off = inMenu && disabled; diff --git a/packages/pivotkit-react/test/chart/topics.test.js b/packages/pivotkit-react/test/chart/topics.test.js index 3cb5195b0..e2ea11185 100644 --- a/packages/pivotkit-react/test/chart/topics.test.js +++ b/packages/pivotkit-react/test/chart/topics.test.js @@ -5,6 +5,7 @@ import assert from "node:assert/strict"; import { encode, normalize } from "pivotkit-core"; // the German first-load texts: pivotkit-react adds them as it loads (deferred.js) import "../../src/deferred.js"; +import { CHART_TYPES, CHART_TYPE_NAMES } from "../../src/chart-types.js"; import { chartTopics } from "../../src/menu-topics.js"; import { rowFolding } from "../../src/view-ops.js"; import { MENU } from "../helpers.js"; @@ -69,7 +70,8 @@ test("averages: no 100 % stack; lines: smooth lines; a heatmap has no Series; tw const only = choices(byId(lt, "series")); assert.deepEqual(only.map((c) => [c.text, c.checked, c.disabled, c.reason, c.color.label]), [["Sum of Revenue", true, true, "The only series is always shown", "Colour of Sum of Revenue"]]); const heat = norm({ rows: ["Region"], cols: ["Category"], values: [{ field: "Revenue", agg: "sum" }], chart: { type: "heatmap" } }); - assert.deepEqual(ids(chartTopics({ view: heat, drawn: "heatmap", labels, names: [], act: { display: () => {} } })), ["valueLabels", "legend", "title"]); + // its colour scale takes the legend's place: no Legend, whose choices would change nothing (#916) + assert.deepEqual(ids(chartTopics({ view: heat, drawn: "heatmap", labels, names: [], act: { display: () => {} } })), ["valueLabels", "title"]); const two = norm({ rows: ["Region", "Country"], values: [{ field: "Revenue", agg: "sum" }], chart: { type: "bar" } }); assert.ok(byId(chartTopics({ view: two, drawn: "bar", labels, names: [], act: { display: () => {} } }), "axis").groups.some((g) => g.title === labels.groupLabels)); }); @@ -215,3 +217,111 @@ test("a treemap has no legend and no axis; its Series level lists its tiles (#51 assert.ok(byId(topics, "valueLabels")); assert.ok(byId(topics, "series")); }); + +/** + * The choices of Chart settings whose name says what they do, by id (a number in it stands for any), + * with why. Every other choice has a line under it (`note`), a hint beside it or an "i" (#916). + * Horizontal bars write All straight, so there All needs its line (#963): see `plain`. + */ +const PLAIN = new Map([ + ["labels-off", "Off"], + ["labels-value", "Value"], + ["labels-percent", "Percent"], + ["labels-both", "Value and percent"], + ["legend-bottom", "Bottom"], + ["legend-right", "Right"], + ["legend-off", "Off"], + ["axis-all", "All (slanted)"], + ["groups-on", "On, under the group's title Group labels under the axis"], + ["groups-off", "Off"], + ["zoom-on", "On, under Zoom slider"], + ["zoom-off", "Off"], + ["tooltip-auto", "the Tooltip's i explains Automatic and All series"], + ["tooltip-axis", "the Tooltip's i"], + ["line-average", "Average, a reference line"], + ["line-extremes", "High and low points"], + ["target-remove", "Remove the target"], + ["series-N", "a series' own name; the Series i explains its switch and colour"], + ["series-N-default", "the colour's Default, with the reset icon"], + ["color-stale-N", "Remove"], + ["chart-smooth", "Smooth lines"], + ["label-position-inside", "the i at Outside explains both"], + ["chart-show-each", "Show each Country"], + ["chart-show-only", "Show Region only"] +]); + +/** Whether a choice of a chart type needs no line: horizontal bars' All is not the slanted All (#963). */ +const plain = (type, id) => PLAIN.has(id) && !(type === "horizontal" && id === "axis-all"); + +/** Every choice Chart settings offers, with its actions, over every chart type, in one language. */ +function everyChoice(language) { + const view = (type, chart = {}) => norm({ rows: ["Region", "Country"], cols: ["Category"], values: [{ field: "Revenue", agg: "sum" }, { field: "Price", agg: "sum" }], chart: { ...CHART_TYPES[type].chart, colors: [{ name: "Hardware", color: "#123456" }, { name: "Gone", color: "#abcdef" }], ...chart } }); + const act = { display: () => {}, expand: () => {}, collapse: () => {} }; + const folding = { canExpand: true, canCollapse: true, collapsed: 0, why: {} }; + const settings = CHART_TYPE_NAMES.filter((t) => t !== "auto").flatMap((type) => [ + { view: view(type), type, lines: { rules: { average: true, trend: true, target: true, extremes: true, notes: [] }, targetText: "" } }, + // a target the chart cannot draw: Remove the target; a pie's labels inside + { view: view(type, { referenceLines: { average: false, trend: false, target: 5, extremes: false }, labelPosition: "inside" }), type, lines: { rules: { average: false, trend: false, target: false, extremes: false, notes: [] }, targetText: "5" } } + ]); + return settings.flatMap(({ view: v, type, lines }) => + chartTopics({ view: v, drawn: type, labels: language, names: ["Hardware", "Services"], act, lines, folding }).flatMap((topic) => choices(topic).flatMap((c) => [c, ...(c.actions ?? [])].map((choice) => ({ type, topic, choice, id: choice.id.replace(/\d+/g, "N") })))) + ); +} + +test("every choice of Chart settings says what it does: by its name, or by a line under it, in English and German (#916)", () => { + for (const language of [MENU.en, MENU.de]) { + const all = everyChoice(language); + const unclear = all.filter(({ type, choice, id }) => !plain(type, id) && !(choice.note || choice.hint || choice.info)).map(({ type, topic, choice }) => `${type}: ${topic.title} › ${choice.text}`); + assert.deepEqual([...new Set(unclear)], [], language.lang); + // the list names only choices there are + assert.deepEqual([...PLAIN.keys()].filter((id) => !all.some((c) => c.id === id)), []); + } + // each line in German is German, not the English one + const en = new Map(everyChoice(MENU.en).map((c) => [`${c.type} ${c.choice.id}`, c.choice.note])); + for (const c of everyChoice(MENU.de)) { + if (c.choice.note) { + assert.notEqual(c.choice.note, en.get(`${c.type} ${c.choice.id}`), c.choice.id); + } + } +}); + +test("what the lines under Automatic say follows the chart: no numbers on bars, a pie's names or shares, the legend above, the axis labels of horizontal bars (#916)", () => { + const note = (type, topic, id, chart = {}) => { + const view = norm({ rows: ["Region"], values: [{ field: "Revenue", agg: "sum" }], chart: { ...CHART_TYPES[type].chart, ...chart } }); + return choices(byId(chartTopics({ view, drawn: type, labels, names: ["North", "South"], act: { display: () => {} } }), topic)).find((c) => c.id === id).note; + }; + assert.equal(note("bar", "valueLabels", "labels-auto"), "None; the tooltip shows the numbers."); + assert.equal(note("pie", "valueLabels", "labels-auto"), "Each slice's name."); + assert.equal(note("donut", "valueLabels", "labels-auto", { labelPosition: "inside" }), "Each slice's share."); + assert.equal(note("treemap", "valueLabels", "labels-auto"), "Each tile's name and value."); + assert.equal(note("heatmap", "valueLabels", "labels-auto"), "The numbers, up to 200 filled cells, when the cells are large enough."); + assert.equal(note("line", "legend", "legend-auto"), "Above, with two or more series."); + assert.equal(note("pie", "legend", "legend-auto"), "Above."); + assert.equal(note("bar", "axis", "axis-auto"), "Straight if they fit, else slanted; every n-th if still too many."); + assert.equal(note("horizontal", "axis", "axis-auto"), "All if they fit, else every n-th."); + // horizontal bars write every name straight: All, not All (slanted) (#963) + assert.equal(note("horizontal", "axis", "axis-all"), "Every name, straight, even where they overlap."); + assert.equal(note("bar", "axis", "axis-all"), undefined); + assert.equal(note("pie", "tooltip", "chart-tooltip-share"), "Sums and counts with their share of the total, such as 25%. Not for averages."); + assert.equal(note("line", "lines", "line-trend"), "A straight line that best fits the values."); +}); + +test("horizontal bars name All without slanted, in English and German, in the choice and the Axis' state (#963)", () => { + for (const [language, all, slanted] of [[MENU.en, "All", "All (slanted)"], [MENU.de, "Alle", "Alle (schräg)"]]) { + const axisOf = (type) => byId(chartTopics({ view: norm({ rows: ["Region"], values: [{ field: "Revenue", agg: "sum" }], chart: { ...CHART_TYPES[type].chart, axisLabels: "all" } }), drawn: type, labels: language, names: [], act: { display: () => {} } }), "axis"); + assert.equal(choices(axisOf("horizontal")).find((c) => c.id === "axis-all").text, all); + assert.equal(axisOf("horizontal").state, all); + assert.equal(choices(axisOf("bar")).find((c) => c.id === "axis-all").text, slanted); + } +}); + +test("every chart type says what Automatic writes as value labels, in English and German (#916)", () => { + for (const language of [MENU.en, MENU.de]) { + for (const type of CHART_TYPE_NAMES.filter((t) => t !== "auto")) { + const view = norm({ rows: ["Region"], cols: ["Category"], values: [{ field: "Revenue", agg: "sum" }], chart: { ...CHART_TYPES[type].chart } }); + const auto = choices(byId(chartTopics({ view, drawn: type, labels: language, names: ["North"], act: { display: () => {} } }), "valueLabels")).find((c) => c.id === "labels-auto"); + assert.equal(typeof auto?.note, "string", `${language.lang} ${type}`); + assert.ok(auto.note.length > 0, `${language.lang} ${type}`); + } + } +}); diff --git a/packages/pivotkit-react/test/menu-topics.test.js b/packages/pivotkit-react/test/menu-topics.test.js index fd21e2057..e8dc5aaf6 100644 --- a/packages/pivotkit-react/test/menu-topics.test.js +++ b/packages/pivotkit-react/test/menu-topics.test.js @@ -6,6 +6,7 @@ import { encode, normalize } from "pivotkit-core"; // the German first-load texts: pivotkit-react adds them as it loads (deferred.js) import "../src/deferred.js"; import { setItemFilter, setTopFilter, setValueFilter } from "../src/menu-ops.js"; +import { setSort, withHostOrders } from "../src/view-ops.js"; import { afterDelete, axisTopics, entryIds, formatLabel, moreTopics, rowFoldTexts, rowName, searchEntries, searchHits, SEARCH_HITS, stepIndex, tableTopics, TOP_COUNTS, topText, typeAheadIndex, valueTopics } from "../src/menu-topics.js"; import { MENU } from "./helpers.js"; @@ -22,10 +23,10 @@ const units = { field: "Units", agg: "sum" }; const axis = (view, field = "Region", extra = {}) => axisTopics({ view, zone: "rows", index: view.rows.indexOf(field), field, types, labels: MENU.en, locale: "en-US", ...extra }); -test("a field's first level: sort side by side, by its one value inline, Filter, Top items, Name, Move to; each says what is set", () => { +test("a field's first level: sort side by side, by its one value inline, Default order, Filter, Top items, Name, Move to; each says what is set", () => { const view = norm({ rows: ["Region"], values: [units] }); const topics = axis(view); - assert.deepEqual(topics.map((t) => [t.id, t.kind]), [["sort", "segmented"], ["sortValue", "inline"], ["filter", "panel"], ["top", "panel"], ["name", "panel"], ["move", "menu"]]); + assert.deepEqual(topics.map((t) => [t.id, t.kind]), [["sort", "segmented"], ["sortValue", "inline"], ["sortDefault", "inline"], ["filter", "panel"], ["top", "panel"], ["name", "panel"], ["move", "menu"]]); const sort = byId(topics, "sort"); assert.deepEqual(sort.groups[0].choices.map((c) => [c.text, c.checked]), [["A to Z", true], ["Z to A", false]]); assert.deepEqual(byId(topics, "sortValue").groups[0].choices.map((c) => c.text), ["Largest Sum of Units first", "Smallest Sum of Units first"]); @@ -53,6 +54,53 @@ test("a choice changes the view as the menu did: sort, and the history's note", assert.deepEqual([byId(topics, "sortValue").state, byId(topics, "sortValue").changed], ["Largest Sum of Units first", true]); }); +test("Default order takes the field back to the order of a new view, from a sort by a value, by one column or by label; greyed out with the reason while it is in it (#917)", () => { + const sortDefault = (view, field = "Region", extra) => choice(byId(axis(view, field, extra), "sortDefault"), "sort-default"); + // a text field: A to Z without a sort entry + const fresh = norm({ rows: ["Region"], cols: ["Product"], values: [units] }); + const off = sortDefault(fresh); + assert.deepEqual([off.text, off.icon, off.disabled, off.reason], ["Default order", "reset", true, "Already the default order."]); + assert.equal(byId(axis(fresh), "sortDefault").title, "Sort order"); + for (const sort of [{ by: "value", order: "desc", value: units }, { by: "value", order: "asc", value: units, column: ["A"] }, { by: "label", order: "desc" }]) { + const sorted = norm(setSort(fresh, "Region", sort)); + const on = sortDefault(sorted); + assert.deepEqual([on.disabled, on.reason], [false, undefined]); + const { view, note } = on.change(); + assert.deepEqual(view, fresh); + // its own undo text: "default order of Region" + assert.deepEqual(note, { step: "sortDefault", field: "Region" }); + // the search finds it by "reset" and "unsorted" too + assert.equal(on.keywords, "reset unsorted"); + } + // A to Z written as an entry (a loaded view) is the default too + assert.equal(sortDefault(norm(setSort(fresh, "Region", { by: "label", order: "asc" }))).disabled, true); + // a date: oldest first + const dates = norm({ rows: ["Date"], values: [units] }); + const newest = choice(byId(axis(dates, "Date"), "sort"), "sort-label-desc").change().view; + const back = sortDefault(newest, "Date").change().view; + assert.deepEqual(back.sort, []); + assert.deepEqual([choice(byId(axis(back, "Date"), "sort"), "sort-label-asc").checked, sortDefault(back, "Date").disabled], [true, true]); + // a field in the host's order (fieldDefaults.order): it comes back once the entry is gone, as every view shown gets it (withHostOrders) + const order = ["West", "North", "South"]; + const host = { defaultsOf: (f) => (f === "Region" ? { order } : undefined) }; + const orderOf = (f) => host.defaultsOf(f)?.order; + const hosted = norm(withHostOrders(fresh, orderOf)); + assert.equal(sortDefault(hosted, "Region", host).disabled, true); + const az = norm(choice(byId(axis(hosted, "Region", host), "sort"), "sort-label-asc").change().view); + assert.deepEqual(az.sort, [{ field: "Region", by: "label", order: "asc" }]); + const reset = sortDefault(az, "Region", host); + assert.equal(reset.disabled, false); + assert.deepEqual(norm(withHostOrders(reset.change().view, orderOf)), hosted); + // another custom order is not the host's: compared item by item, as the field's type writes them + assert.equal(sortDefault(norm(setSort(hosted, "Region", { by: "custom", order: "asc", items: ["North", "West", "South"] })), "Region", host).disabled, false); + const years = { defaultsOf: () => ({ order: ["3", "1", "7"] }) }; + const numbers = norm({ rows: ["Units"], values: [{ field: "Region", agg: "count" }], sort: [{ field: "Units", by: "custom", order: "asc", items: [3, 1, 7] }] }); + assert.equal(sortDefault(numbers, "Units", years).disabled, true); + // German + const de = choice(byId(axisTopics({ view: fresh, zone: "rows", index: 0, field: "Region", types, labels: MENU.de, locale: "de-DE" }), "sortDefault"), "sort-default"); + assert.deepEqual([de.text, de.reason, de.keywords], ["Standardreihenfolge", "Bereits die Standardreihenfolge.", "zurücksetzen unsortiert"]); +}); + test("several values to sort by: a level of their own; dates sort Oldest and Newest", () => { const view = norm({ rows: ["Date"], values: [units, { field: "Units", agg: "max" }] }); const topics = axis(view, "Date"); diff --git a/scripts/growth-baseline.json b/scripts/growth-baseline.json index 3e367dc05..e48f47550 100644 --- a/scripts/growth-baseline.json +++ b/scripts/growth-baseline.json @@ -41,9 +41,8 @@ "packages/pivotkit-react/src/fields.jsx Function 'FieldPanel'": [29], "packages/pivotkit-react/src/filter-level.jsx Function 'FilterLevel'": [56], "packages/pivotkit-react/src/import-ui.jsx Function 'ImportDialog'": [39], - "packages/pivotkit-react/src/levels.jsx Function 'MenuItem'": [27], "packages/pivotkit-react/src/menu-topics.js Function 'axisTopics'": [28], - "packages/pivotkit-react/src/menu-topics.js Function 'chartTopics'": [68], + "packages/pivotkit-react/src/menu-topics.js Function 'chartTopics'": [62], "packages/pivotkit-react/src/popover.jsx Arrow function": [27], "packages/pivotkit-react/src/popover.jsx Function 'MenuButton'": [27], "packages/pivotkit-react/src/popover.jsx Function 'Popover'": [26], @@ -129,7 +128,6 @@ "packages/pivotkit-react/src/import-ui.jsx Function 'ImportDialog'": [262], "packages/pivotkit-react/src/info.jsx Function 'InfoButton'": [145], "packages/pivotkit-react/src/levels.jsx Function 'LevelMenu'": [157], - "packages/pivotkit-react/src/menu-topics.js Function 'chartTopics'": [128], "packages/pivotkit-react/src/popover.jsx Function 'Popover'": [205], "packages/pivotkit-react/src/quick-choices.jsx Function 'QuickChoices'": [349], "packages/pivotkit-react/src/table.jsx Function 'PivotTable'": [352], diff --git a/tests/browser/sort-default.spec.js b/tests/browser/sort-default.spec.js new file mode 100644 index 000000000..839f58c2b --- /dev/null +++ b/tests/browser/sort-default.spec.js @@ -0,0 +1,112 @@ +// Default order in a field's menu (#917): from a sort by a value, by one column or a custom order it +// brings back the order of a new view, the header shows no sort arrow, and Undo brings the sort back. +import { encodeViewLink } from "pivotkit-core/link"; +import { expect, test, textOf } from "./fixtures.js"; + +/** Revenue by region and channel: the regions in Rows, the channels in Columns. */ +const VIEW = { rows: ["Region"], cols: ["Channel"], values: [{ field: "Revenue", agg: "sum" }] }; +const rowNames = (page) => page.locator(".pk-table tbody th.pk-rowHeader").allTextContents(); +const sortedHeaders = (page) => page.locator(".pk-table thead th[aria-sort]"); + +/** Opens the field's menu and picks Default order; the menu says it is the default then. */ +async function defaultOrder(page, field) { + await page.getByTestId(`chip-menu-${field}`).click(); + const menu = page.locator(".pk-chip-menu"); + const choice = menu.getByTestId("sort-default"); + await expect(choice).toHaveText(textOf("sortDefault")); + await expect(choice).not.toHaveAttribute("aria-disabled"); + await choice.click(); + await expect(choice).toHaveAttribute("aria-disabled", "true"); + await expect(menu.getByTestId("sort-default-reason")).toHaveText(textOf("sortIsDefault")); + await page.keyboard.press("Escape"); +} + +test("from a sort by a value or by one column: the order of a new view, no arrow on any header; Undo sorts again", async ({ page }) => { + await page.goto(`?data=sales&lang=en&empty#pivot-playground=${encodeViewLink(VIEW)}`); + await expect(page.locator(".pk-table")).toBeVisible(); + const start = await rowNames(page); + const online = page.locator(".pk-table thead th", { hasText: /^Online$/ }); + // by one column from its header, then by the whole row from the field's menu + const sorts = [ + () => online.locator(".pk-th-sort").click(), + async () => { + await page.getByTestId("chip-menu-Region").click(); + await page.locator(".pk-chip-menu").getByTestId("sort-value-asc-0").click(); + await page.keyboard.press("Escape"); + } + ]; + for (const sort of sorts) { + await sort(); + await expect(page.getByTestId("chip-menu-Region")).toHaveAccessibleName(/^Region, sorted /); + const sorted = await rowNames(page); + expect(sorted).not.toEqual(start); + await defaultOrder(page, "Region"); + await expect.poll(() => rowNames(page)).toEqual(start); + await expect(page.getByTestId("chip-menu-Region")).toHaveAccessibleName("Region"); + await expect(sortedHeaders(page)).toHaveCount(0); + await expect(page.locator(".pk-table thead .pk-th-sort.pk-sorted")).toHaveCount(0); + await page.getByTestId("undo").click(); + // the step has its own name + await expect(page.locator(".pk-toasts")).toContainText("Undone: default order of Region"); + await expect.poll(() => rowNames(page)).toEqual(sorted); + await expect(page.getByTestId("chip-menu-Region")).toHaveAccessibleName(/^Region, sorted /); + await page.getByTestId("undo").click(); + await expect.poll(() => rowNames(page)).toEqual(start); + } + // the column's header showed its arrow while it sorted + await sorts[0](); + await expect(online).toHaveAttribute("aria-sort", "descending"); +}); + +test("a field in the host's own order: Default order brings that order back, not A to Z", async ({ page }) => { + await page.goto("?data=weather&empty"); + await page.locator('.pk-field[data-field="Season"] .pk-field-name').click(); + const header = page.getByRole("columnheader", { name: "Season" }); + await expect(header).toHaveAttribute("aria-sort", "other"); + const start = await rowNames(page); + await header.getByRole("button", { name: "Season" }).click(); + await expect(header).toHaveAttribute("aria-sort", "ascending"); + await defaultOrder(page, "Season"); + await expect.poll(() => rowNames(page)).toEqual(start); + await expect(header).toHaveAttribute("aria-sort", "other"); +}); + +/** The search's hit Default order. */ +const hitOf = (menu) => menu.getByTestId("menu-search-hits").getByRole("menuitem").filter({ hasText: textOf("sortDefault") }); + +test("the search finds Default order by reset or unsorted, greyed out with its reason as in its level; the line under it is its description, not part of its name", async ({ page }) => { + await page.goto(`?data=sales&lang=en&empty#pivot-playground=${encodeViewLink(VIEW)}`); + await page.getByTestId("chip-menu-Region").click(); + const menu = page.locator(".pk-chip-menu"); + // in its level: the reason is read once, as the description + const choice = menu.getByTestId("sort-default"); + await expect(choice).toHaveAccessibleName(textOf("sortDefault")); + await expect(choice).toHaveAccessibleDescription(textOf("sortIsDefault")); + const search = menu.getByTestId("menu-search"); + for (const word of ["reset", "unsorted"]) { + await search.fill(word); + const hit = hitOf(menu); + // its name and its path; the reason is the description only + await expect(hit).toHaveAccessibleName(`${textOf("sortDefault")} ${textOf("sortOrder")}`); + await expect(hit).toHaveAttribute("aria-disabled", "true"); + await expect(hit).toHaveAccessibleDescription(textOf("sortIsDefault")); + } + // Enter on the greyed-out hit does nothing: the search keeps its words, no undo step + await search.press("ArrowDown"); + await expect(hitOf(menu)).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(search).toHaveValue("unsorted"); + await expect(page.getByTestId("undo")).toBeDisabled(); + // sorted, the hit is one to pick, and it takes the sort back + await search.fill(""); + await page.keyboard.press("Escape"); + await expect(menu).toBeHidden(); + await page.locator(".pk-table thead th", { hasText: /^Online$/ }).locator(".pk-th-sort").click(); + await expect(page.getByTestId("chip-menu-Region")).toHaveAccessibleName(/^Region, sorted /); + await page.getByTestId("chip-menu-Region").click(); + await menu.getByTestId("menu-search").fill("unsorted"); + const hit = hitOf(menu); + await expect(hit).not.toHaveAttribute("aria-disabled"); + await hit.click(); + await expect(page.getByTestId("chip-menu-Region")).toHaveAccessibleName("Region"); +});