The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Place unsectioned chart-settings widgets in the highest-priority section, not the first inserted (#73805)
Andrei Chernykh68cd362ae607
diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsxindex d952356e614..aa6a1cae7a0 100644--- a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx+++ b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.tsx@@ -42,7 +42,7 @@ export const BaseChartSettings = ({const {chartSettingCurrentSection,currentSectionHasColumnSettings,- sectionNames,+ orderedSectionNames,setCurrentSection,showSectionPicker,visibleWidgets,@@ -206,7 +206,7 @@ export const BaseChartSettings = ({<Radiovalue={chartSettingCurrentSection ?? undefined}onChange={handleShowSection}- options={sectionNames}+ options={orderedSectionNames}optionNameFn={(v) => v}optionValueFn={(v) => v}optionKeyFn={(v) => v}diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.unit.spec.tsxindex ce5bcdaf86d..38ff2d7b9af 100644--- a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/BaseChartSettings.unit.spec.tsx@@ -1,3 +1,5 @@+import { addLocale, useLocale } from "ttag";+import { fireEvent, renderWithProviders, screen } from "__support__/ui";import registerVisualizations from "metabase/visualizations/register";import type { Widget } from "metabase/visualizations/types";@@ -131,4 +133,94 @@ describe("ChartSettings", () => {expect(screen.queryByText("Foo")).not.toBeInTheDocument();});++ it("should put unsectioned widgets into the first section by priority, not insertion order", () => {+ // matches the scalar shape: a non-priority section is registered before a+ // priority section. The unsectioned widget should land in Formatting, not+ // in the first-inserted "Conditional colors".+ setup({+ widgets: [+ widget({ title: "Unsectioned", section: undefined }),+ widget({ title: "InColors", section: "Conditional colors" }),+ widget({ title: "InFormatting", section: "Formatting" }),+ ],+ initial: { section: "Formatting" },+ });++ // Formatting tab is active, so unsectioned + Formatting widget should be visible+ expect(+ screen.getByText("Unsectioned", { exact: false }),+ ).toBeInTheDocument();+ expect(+ screen.getByText("InFormatting", { exact: false }),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("InColors", { exact: false }),+ ).not.toBeInTheDocument();++ // switch to Conditional colors and verify the unsectioned widget does not follow+ fireEvent.click(screen.getByText("Conditional colors"));+ expect(+ screen.queryByText("Unsectioned", { exact: false }),+ ).not.toBeInTheDocument();+ expect(screen.getByText("InColors", { exact: false })).toBeInTheDocument();+ });++ describe("with a non-English locale", () => {+ beforeAll(() => {+ addLocale("es-fake", {+ headers: { "plural-forms": "nplurals=2; plural=(n != 1);" },+ translations: {+ "": {+ Data: { msgid: "Data", msgstr: ["Datos"] },+ Columns: { msgid: "Columns", msgstr: ["Columnas"] },+ Display: { msgid: "Display", msgstr: ["Visualización"] },+ Axes: { msgid: "Axes", msgstr: ["Ejes"] },+ Ranges: { msgid: "Ranges", msgstr: ["Rangos"] },+ Formatting: { msgid: "Formatting", msgstr: ["Formato"] },+ },+ },+ });+ useLocale("es-fake");+ });++ afterAll(() => {+ // restore the default locale so later tests aren't affected+ useLocale("en");+ });++ it("should sort translated sections by priority, not by insertion order", () => {+ setup({+ widgets: [+ widget({ title: "InAxes", section: "Ejes" }),+ widget({ title: "InData", section: "Datos" }),+ widget({ title: "InFormatting", section: "Formato" }),+ ],+ });++ // Data is first in the priority order, so its localized label ("Datos") is the active tab+ expect(screen.getByLabelText("Datos")).toBeChecked();+ expect(screen.getByLabelText("Ejes")).not.toBeChecked();+ expect(screen.getByLabelText("Formato")).not.toBeChecked();+ });++ it("should put unsectioned widgets into the highest-priority translated section", () => {+ setup({+ widgets: [+ widget({ title: "Unsectioned", section: undefined }),+ widget({ title: "InColors", section: "Conditional colors" }),+ widget({ title: "InFormatting", section: "Formato" }),+ ],+ initial: { section: "Formato" },+ });++ // unsectioned widget landed in the translated Formato tab, not Conditional colors+ expect(+ screen.getByText("Unsectioned", { exact: false }),+ ).toBeInTheDocument();+ expect(+ screen.getByText("InFormatting", { exact: false }),+ ).toBeInTheDocument();+ });+ });});diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.ts b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.tsindex 3a9fdc3d96a..ed4b0094ebe 100644--- a/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.ts+++ b/frontend/src/metabase/visualizations/components/ChartSettings/BaseChartSettings/hooks.ts@@ -1,14 +1,64 @@import { useMemo, useState } from "react";import { t } from "ttag";-import _ from "underscore";import type { Widget } from "metabase/visualizations/types";import type { BaseChartSettingsProps } from "./types";-// section names are localized-// eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045-const DEFAULT_TAB_PRIORITY = [t`Data`];+// Section labels in priority order. Evaluated at call time so the order works+// in any locale — widgets store their `section` as a localized t`` string,+// which we compare against this same set of t`` calls.+const getSectionPriority = (): string[] => [+ t`Data`,+ t`Columns`,+ t`Display`,+ t`Axes`,+ t`Ranges`,+ t`Formatting`,+];++const orderSectionNames = (names: string[]): string[] => {+ const priority = getSectionPriority();+ const knownSections: (string | undefined)[] = new Array(priority.length);+ const unrecognizedSections: string[] = [];+ for (const name of names) {+ const idx = priority.indexOf(name);+ if (idx >= 0) {+ knownSections[idx] = name;+ } else {+ unrecognizedSections.push(name);+ }+ }+ // known sections fill their priority slot; the rest keep insertion order+ return [+ ...knownSections.filter((n): n is string => n !== undefined),+ ...unrecognizedSections,+ ];+};++const groupWidgetsBySection = (widgets: Widget[]): Record<string, Widget[]> => {+ const sectionObj: Record<string, Widget[]> = {};+ for (const widget of widgets) {+ if (widget.widget && !widget.hidden) {+ const key = String(widget.section);+ (sectionObj[key] ??= []).push(widget);+ }+ }+ return sectionObj;+};++// Remove unsectioned widgets so the caller can place them elsewhere, but+// only if there is somewhere else to put them. Mutates `sectionObj`.+const extractUnsectionedWidgets = (+ sectionObj: Record<string, Widget[]>,+): Widget[] | undefined => {+ if (!sectionObj["undefined"] || Object.keys(sectionObj).length <= 1) {+ return undefined;+ }+ const extras = sectionObj["undefined"];+ delete sectionObj["undefined"];+ return extras;+};export const useChartSettingsSections = ({initial,@@ -18,85 +68,47 @@ export const useChartSettingsSections = ({initial?.section ?? null,);- const sections: Record<string, Widget[]> = useMemo(() => {- const sectionObj: Record<string, Widget[]> = {};- for (const widget of widgets) {- if (widget.widget && !widget.hidden) {- const section = String(widget.section);- sectionObj[section] = sectionObj[section] || [];- sectionObj[section].push(widget);- }- }-- // Move settings from the "undefined" section in the first tab- if (sectionObj["undefined"] && Object.values(sectionObj).length > 1) {- const extra = sectionObj["undefined"];- delete sectionObj["undefined"];- Object.values(sectionObj)[0].unshift(...extra);- }- return sectionObj;- }, [widgets]);-- // This sorts the section radio buttons.- const sectionNames = useMemo(() => {- const names = Object.keys(sections);-- const sectionSortOrder = [- "data",- "columns",- "display",- "axes",- "ranges",- "formatting",- // include all section names so any forgotten sections are sorted to the end- ...names.map((x) => x.toLowerCase()),- ];- names.sort((a, b) => {- const [aIdx, bIdx] = [a, b].map((x) =>- sectionSortOrder.indexOf(x.toLowerCase()),- );- return aIdx - bIdx;- });+ const { orderedSectionNames, chartSettingCurrentSection, visibleWidgets } =+ useMemo(() => {+ const sectionObj = groupWidgetsBySection(widgets);+ const extras = extractUnsectionedWidgets(sectionObj);+ const orderedSectionNames = orderSectionNames(Object.keys(sectionObj));- return names;- }, [sections]);+ // place extras at the top of the first section by priority+ if (extras && orderedSectionNames.length > 0) {+ sectionObj[orderedSectionNames[0]].unshift(...extras);+ }- const chartSettingCurrentSection = useMemo(- () =>- currentSection && sections[currentSection]- ? currentSection- : _.find(DEFAULT_TAB_PRIORITY, (name) => name in sections) ||- sectionNames[0],- [currentSection, sectionNames, sections],- );+ // Data is first in the priority order, so orderedSectionNames[0] is the natural default+ const chartSettingCurrentSection =+ currentSection && sectionObj[currentSection]+ ? currentSection+ : orderedSectionNames[0];- const visibleWidgets = useMemo(- () => sections[chartSettingCurrentSection] || [],- [chartSettingCurrentSection, sections],- );+ return {+ orderedSectionNames,+ chartSettingCurrentSection,+ visibleWidgets: sectionObj[chartSettingCurrentSection] || [],+ };+ }, [widgets, currentSection]);- const currentSectionHasColumnSettings = useMemo(- () =>- visibleWidgets.some((widget: Widget) => widget.id === "column_settings"),- [visibleWidgets],+ const currentSectionHasColumnSettings = visibleWidgets.some(+ (widget: Widget) => widget.id === "column_settings",);- const showSectionPicker = useMemo(- () =>- // don't show section tabs for a single section- sectionNames.length > 1 &&- // hide the section picker if the only widget is column_settings- !(- visibleWidgets.length === 1 &&- visibleWidgets[0].id === "column_settings" &&- // and this section doesn't have that as a direct child- !currentSectionHasColumnSettings- ),- [currentSectionHasColumnSettings, sectionNames.length, visibleWidgets],- );+ const showSectionPicker =+ // don't show section tabs for a single section+ orderedSectionNames.length > 1 &&+ // hide the section picker if the only widget is column_settings+ !(+ visibleWidgets.length === 1 &&+ visibleWidgets[0].id === "column_settings" &&+ // and this section doesn't have that as a direct child+ !currentSectionHasColumnSettings+ );return {- sectionNames,+ orderedSectionNames,setCurrentSection,currentSectionHasColumnSettings,chartSettingCurrentSection,