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
GDGT-3227: searchable column picker (#83345)
Will Frye86c531b9cdd
diff --git a/e2e/test/scenarios/question/notebook.cy.spec.js b/e2e/test/scenarios/question/notebook.cy.spec.jsindex d47598e2c10..afbbddc41e2 100644--- a/e2e/test/scenarios/question/notebook.cy.spec.js+++ b/e2e/test/scenarios/question/notebook.cy.spec.js@@ -312,9 +312,10 @@ describe("scenarios > question > notebook", { tags: "@slow" }, () => {H.popover().within(() => {cy.findByText("Select all").click();- cy.findByLabelText("ID").should("be.disabled");+ cy.findByLabelText("ID").should("have.attr", "aria-disabled", "true");cy.findByText("Tax").click();- cy.findByLabelText("ID").should("be.enabled").click();+ cy.findByLabelText("ID").should("not.have.attr", "aria-disabled");+ cy.findByLabelText("ID").click();});cy.findByTestId("step-data-0-0").findByText("Data").click(); //Dismiss popoverdiff --git a/frontend/src/metabase/querying/notebook/components/DataStep/DataStep.tsx b/frontend/src/metabase/querying/notebook/components/DataStep/DataStep.tsxindex 95c16d4475e..b181cd067c0 100644--- a/frontend/src/metabase/querying/notebook/components/DataStep/DataStep.tsx+++ b/frontend/src/metabase/querying/notebook/components/DataStep/DataStep.tsx@@ -8,7 +8,11 @@ import { METAKEY } from "metabase/utils/browser";import * as Lib from "metabase-lib";import type { NotebookStepProps } from "../../types";-import { FieldPicker, type FieldPickerItem } from "../FieldPicker";+import {+ FieldPicker,+ type FieldPickerItem,+ getNextSelectedColumns,+} from "../FieldPicker";import { useNotebookContext } from "../Notebook/context";import { NotebookCell, NotebookCellItem } from "../NotebookCell";import { CONTAINER_PADDING } from "../NotebookCell/constants";@@ -129,7 +133,7 @@ export function DataFieldPopover({updateQuery,}: DataFieldPopoverProps) {return (- <Popover position="bottom-start">+ <Popover position="bottom-start" trapFocus returnFocus><Popover.Target><Tooltip label={t`Pick columns`}><IconButtonWrapper@@ -181,14 +185,26 @@ function DataFieldPicker({updateQuery(nextQuery);};- const handleSelectAll = () => {- const nextQuery = Lib.withFields(query, stageIndex, []);- updateQuery(nextQuery);- };-- const handleSelectNone = () => {- const nextQuery = Lib.withFields(query, stageIndex, [columns[0]]);- updateQuery(nextQuery);+ const handleToggleColumns = (+ toggledColumns: Lib.ColumnMetadata[],+ isSelected: boolean,+ ) => {+ const selectedColumns = columns.filter(+ (column) => Lib.displayInfo(query, stageIndex, column).selected,+ );+ const nextColumns = getNextSelectedColumns({+ columns,+ selectedColumns,+ toggledColumns,+ isSelected,+ });+ // An empty field list means "every column", so a deselect that would+ // empty it keeps the first target instead (mirroring the the logic+ // to disable the the final selected column).+ const fields =+ nextColumns.length > 0 ? nextColumns : toggledColumns.slice(0, 1);+ const isEveryColumn = fields.length === columns.length;+ updateQuery(Lib.withFields(query, stageIndex, isEveryColumn ? [] : fields));};return (@@ -199,8 +215,7 @@ function DataFieldPicker({isColumnSelected={isColumnSelected}isColumnDisabled={isColumnDisabled}onToggle={handleToggle}- onSelectAll={handleSelectAll}- onSelectNone={handleSelectNone}+ onToggleColumns={handleToggleColumns}/>);}diff --git a/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsxindex 915a9a6e7ae..5d61666f314 100644--- a/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/DataStep/tests/common.unit.spec.tsx@@ -4,7 +4,7 @@ import fetchMock from "fetch-mock";import { createMockMetadata } from "__support__/metadata";import { fireEvent, getIcon, screen, waitFor } from "__support__/ui";import { mockGetBoundingClientRect } from "__support__/utils";-import { METAKEY } from "metabase/utils/browser";+import { METAKEY, isTouchDevice } from "metabase/utils/browser";import { checkNotNull } from "metabase/utils/types";import * as Lib from "metabase-lib";import {@@ -22,10 +22,20 @@ import {createSavedStructuredCard,} from "metabase-types/api/mocks/presets";-import { DEFAULT_QUESTION, createMockNotebookStep } from "../../../test-utils";+import {+ DEFAULT_QUESTION,+ createMockNotebookStep,+ createSampleTableQuery,+ getColumnNames,+} from "../../../test-utils";import { type SetupOpts, setup as baseSetup } from "./setup";+jest.mock("metabase/utils/browser", () => ({+ ...jest.requireActual("metabase/utils/browser"),+ isTouchDevice: jest.fn(() => false),+}));+const findAggregationOperator = (query: Lib.Query,operatorShortName: string,@@ -177,10 +187,16 @@ describe("DataStep", () => {await userEvent.click(screen.getByLabelText("Pick columns"));expect(screen.getByLabelText("Select all")).toBeChecked();- expect(screen.getByLabelText("ID")).toBeChecked();- expect(screen.getByLabelText("ID")).toBeEnabled();- expect(screen.getByLabelText("Tax")).toBeChecked();- expect(screen.getByLabelText("Tax")).toBeEnabled();+ expect(screen.getByLabelText("ID")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByLabelText("ID")).not.toHaveAttribute("aria-disabled");+ expect(screen.getByLabelText("Tax")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByLabelText("Tax")).not.toHaveAttribute("aria-disabled");});it("should render with a single column selected", async () => {@@ -188,11 +204,20 @@ describe("DataStep", () => {await setup({ step: createMockNotebookStep({ query }) });await userEvent.click(screen.getByLabelText("Pick columns"));- expect(screen.getByLabelText("Select all")).not.toBeChecked();- expect(screen.getByLabelText("ID")).toBeChecked();- expect(screen.getByLabelText("ID")).toBeDisabled();- expect(screen.getByLabelText("Tax")).not.toBeChecked();- expect(screen.getByLabelText("Tax")).toBeEnabled();+ expectElementToBePartiallyChecked(screen.getByLabelText("Select all"));+ expect(screen.getByLabelText("ID")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByLabelText("ID")).toHaveAttribute(+ "aria-disabled",+ "true",+ );+ expect(screen.getByLabelText("Tax")).toHaveAttribute(+ "aria-selected",+ "false",+ );+ expect(screen.getByLabelText("Tax")).not.toHaveAttribute("aria-disabled");});it("should render with multiple columns selected", async () => {@@ -200,13 +225,24 @@ describe("DataStep", () => {await setup({ step: createMockNotebookStep({ query }) });await userEvent.click(screen.getByLabelText("Pick columns"));- expect(screen.getByLabelText("Select all")).not.toBeChecked();- expect(screen.getByLabelText("ID")).toBeChecked();- expect(screen.getByLabelText("ID")).toBeEnabled();- expect(screen.getByLabelText("Tax")).not.toBeChecked();- expect(screen.getByLabelText("Tax")).toBeEnabled();- expect(screen.getByLabelText("Total")).toBeChecked();- expect(screen.getByLabelText("Total")).toBeEnabled();+ expectElementToBePartiallyChecked(screen.getByLabelText("Select all"));+ expect(screen.getByLabelText("ID")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByLabelText("ID")).not.toHaveAttribute("aria-disabled");+ expect(screen.getByLabelText("Tax")).toHaveAttribute(+ "aria-selected",+ "false",+ );+ expect(screen.getByLabelText("Tax")).not.toHaveAttribute("aria-disabled");+ expect(screen.getByLabelText("Total")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByLabelText("Total")).not.toHaveAttribute(+ "aria-disabled",+ );});it("should allow selecting a column", async () => {@@ -256,6 +292,115 @@ describe("DataStep", () => {expect(Lib.fields(nextQuery, 0)).toHaveLength(1);});+ describe("when searching", () => {+ afterEach(() => {+ jest.mocked(isTouchDevice).mockReturnValue(false);+ });++ const getSelectedColumnNames = (query: Lib.Query) =>+ getColumnNames(+ query,+ 0,+ Lib.fieldableColumns(query, 0).filter(+ (column) => Lib.displayInfo(query, 0, column).selected,+ ),+ );++ const searchAndToggleAllMatches = async (searchText: string) => {+ await userEvent.click(screen.getByLabelText("Pick columns"));+ await userEvent.type(+ screen.getByLabelText("Search columns"),+ searchText,+ );+ await userEvent.click(screen.getByLabelText("Select all of these"));+ };++ it("should focus the search box when the picker opens", async () => {+ const query = createSampleTableQuery("PEOPLE");+ await setup({ step: createMockNotebookStep({ query }) });++ await userEvent.click(screen.getByLabelText("Pick columns"));++ await waitFor(() =>+ expect(screen.getByLabelText("Search columns")).toHaveFocus(),+ );+ });++ it("should focus the column list instead of the search box on touch devices", async () => {+ jest.mocked(isTouchDevice).mockReturnValue(true);+ const query = createSampleTableQuery("PEOPLE");+ await setup({ step: createMockNotebookStep({ query }) });++ await userEvent.click(screen.getByLabelText("Pick columns"));++ await waitFor(() =>+ expect(+ screen.getByRole("listbox", { name: "Columns" }),+ ).toHaveFocus(),+ );+ });++ it("should close the picker on Escape even with a search query", async () => {+ const query = createSampleTableQuery("PEOPLE");+ await setup({ step: createMockNotebookStep({ query }) });+ const trigger = screen.getByLabelText("Pick columns");++ await userEvent.click(trigger);+ await userEvent.type(screen.getByLabelText("Search columns"), "tude");+ await userEvent.keyboard("{Escape}");++ await waitFor(() =>+ expect(+ screen.queryByLabelText("Search columns"),+ ).not.toBeInTheDocument(),+ );+ await waitFor(() => expect(trigger).toHaveFocus());+ });++ it("should only select the matching columns", async () => {+ const query = createSampleTableQuery("PEOPLE", ["ID"]);+ const { getNextQuery } = await setup({+ step: createMockNotebookStep({ query }),+ });++ await searchAndToggleAllMatches("tude");++ expect(getSelectedColumnNames(getNextQuery())).toEqual([+ "ID",+ "LATITUDE",+ "LONGITUDE",+ ]);+ });++ it("should keep the first match selected when deselecting every selected column", async () => {+ const query = createSampleTableQuery("PEOPLE", [+ "LONGITUDE",+ "LATITUDE",+ ]);+ const { getNextQuery } = await setup({+ step: createMockNotebookStep({ query }),+ });++ await searchAndToggleAllMatches("tude");++ expect(getSelectedColumnNames(getNextQuery())).toEqual(["LATITUDE"]);+ });++ it("should drop the explicit fields once every column is selected", async () => {+ const columnNames = getSelectedColumnNames(+ createSampleTableQuery("PEOPLE"),+ ).filter((name) => name !== "LATITUDE");+ const query = createSampleTableQuery("PEOPLE", columnNames);+ const { getNextQuery } = await setup({+ step: createMockNotebookStep({ query }),+ });++ await searchAndToggleAllMatches("tude");++ expect(Lib.fields(getNextQuery(), 0)).toHaveLength(0);+ });+ });+it("should not display fields picker in read-only mode", async () => {await setup({ readOnly: true });expect(screen.queryByLabelText("Pick columns")).not.toBeInTheDocument();@@ -422,3 +567,7 @@ describe("DataStep", () => {});});});++function expectElementToBePartiallyChecked(element: HTMLElement) {+ expect(element).toHaveAttribute("aria-checked", "mixed");+}diff --git a/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.module.css b/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.module.cssindex e14c44d49cc..713314e1346 100644--- a/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.module.css+++ b/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.module.css@@ -1,37 +1,92 @@-.ItemTitle {- color: var(--mb-color-text-secondary);- min-width: 10ch;-}+/* The popover dropdown is the scroll container, so pin the search box to its top. */+.SearchContainer {+ position: sticky;+ top: 0;+ z-index: 1;+ padding: 0.5em 0.5em 0;+ background: var(--mb-color-background_surface-primary);-.ItemIcon {- margin: 0 0.5em;- margin-left: 0.75em;- color: var(--mb-color-text-disabled);+ /* Mantine styles Combobox.Search as a dropdown header (negative margins, no+ side borders, raw palette colors); restore the regular input look. */+ .Search {+ margin: 0;+ width: 100%;+ border: 1px solid var(--mb-color-border-neutral);+ border-radius: var(--default-border-radius);+ background-color: var(--mb-color-background_surface-primary);++ &:focus {+ border-color: var(--mb-color-core-brand);+ }+ }}-.ItemList {+.List {padding: 0.5em;++ .Options {+ padding: 0;++ /* The highlighted option already shows where keyboard focus is. */+ &:focus-visible {+ outline: none;+ }+ }++ .Option {+ padding: 0;+ border-radius: 6px;+ color: inherit;++ &:hover,+ &[data-combobox-selected="true"] {+ color: inherit;+ background: var(--mb-color-background_page-tertiary);+ }++ &[data-combobox-disabled="true"] {+ cursor: default;+ }+ }++ .Empty {+ padding: 0.5em;+ }}-.Label {+.Row {display: flex;align-items: center;padding: 0 0.5em;padding-right: 0;- border-radius: 6px;- cursor: pointer;min-height: 2.25rem;+}- &:hover {- background: var(--mb-color-background_page-tertiary);- }+.RowCheckbox {+ pointer-events: none;}-.ToggleItem {- border-bottom: 1px solid var(--mb-color-border-neutral);- margin-bottom: 0.5em;+.ToggleRow {+ composes: Row;.ItemTitle {margin-left: 1em;}}++.ColumnGroup {+ margin-top: 0.25em;+ padding-top: 0.25em;+ border-top: 1px solid var(--mb-color-border-neutral);+}++.ItemTitle {+ color: var(--mb-color-text-secondary);+ min-width: 10ch;+}++.ItemIcon {+ margin: 0 0.5em;+ margin-left: 0.75em;+ color: var(--mb-color-text-disabled);+}diff --git a/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.tsx b/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.tsxindex 2d29afaccfc..b8f1bf32eb5 100644--- a/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.tsx+++ b/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.tsx@@ -1,16 +1,39 @@-import { useMemo } from "react";-import { t } from "ttag";+import {+ type KeyboardEvent,+ useCallback,+ useEffect,+ useId,+ useMemo,+ useState,+} from "react";+import { flushSync } from "react-dom";+import { msgid, ngettext, t } from "ttag";import {HoverParent,QueryColumnInfoIcon,} from "metabase/common/components/MetadataInfo/QueryColumnInfoIcon";import { useTranslateContent } from "metabase/content-translation/hooks";-import { Checkbox, DelayGroup } from "metabase/ui";+import visuallyHidden from "metabase/css/core/visually-hidden.module.css";+import {+ Checkbox,+ type CheckboxProps,+ Combobox,+ DelayGroup,+ Icon,+ Input,+ useCombobox,+} from "metabase/ui";+import { isTouchDevice } from "metabase/utils/browser";import * as Lib from "metabase-lib";import S from "./FieldPicker.module.css";+export const MIN_SEARCHABLE_COLUMN_COUNT = 10;++// Column option values are indices, so this can't collide with one.+const SELECT_ALL_VALUE = "select-all";+export interface FieldPickerItem {column: Lib.ColumnMetadata;columnInfo: Lib.ColumnDisplayInfo;@@ -30,8 +53,7 @@ interface FieldPickerProps {items: FieldPickerItem[],) => boolean;onToggle: (column: Lib.ColumnMetadata, isSelected: boolean) => void;- onSelectAll: () => void;- onSelectNone: () => void;+ onToggleColumns: (columns: Lib.ColumnMetadata[], isSelected: boolean) => void;}export const FieldPicker = ({@@ -39,75 +61,278 @@ export const FieldPicker = ({stageIndex,columns,onToggle,- onSelectAll,- onSelectNone,+ onToggleColumns,isColumnSelected,isColumnDisabled,...props}: FieldPickerProps) => {const tc = useTranslateContent();+ const matchCountId = useId();+ // The popover's focus trap places focus. Plain autoFocus would fire before+ // the popover records where to return focus on close. On a touch device,+ // focusing the search box would open the on-screen keyboard over the list.+ const shouldFocusSearch = !isTouchDevice();+ const [searchText, setSearchText] = useState("");++ const combobox = useCombobox({ opened: true });+const items = useMemo(() => {const items = columns.map((column) => ({column,columnInfo: Lib.displayInfo(query, stageIndex, column),}));- return items.map((item) => ({+ return items.map((item, index) => ({...item,+ id: String(index),+ title: tc(item.columnInfo.displayName),isSelected: isColumnSelected(item, items),- isDisabled: isColumnDisabled?.(item, items),+ isDisabled: isColumnDisabled?.(item, items) ?? false,}));- }, [query, stageIndex, columns, isColumnSelected, isColumnDisabled]);+ }, [query, stageIndex, columns, isColumnSelected, isColumnDisabled, tc]);- const isAll = items.every((item) => item.isSelected);- const isNone = items.every((item) => !item.isSelected);+ // Gate on the full column count so the search box doesn't disappear once+ // the user has filtered the list down.+ const isSearchable = items.length >= MIN_SEARCHABLE_COLUMN_COUNT;+ const normalizedSearchText = searchText.trim().toLowerCase();+ const isSearching = normalizedSearchText.length > 0;+ const isSearchAutofocused = isSearchable && shouldFocusSearch;++ const visibleItems = useMemo(+ () =>+ isSearching+ ? items.filter((item) =>+ item.title.toLowerCase().includes(normalizedSearchText),+ )+ : items,+ [items, isSearching, normalizedSearchText],+ );- const handleLabelToggle = () => {- if (isAll) {- onSelectNone();- } else {- onSelectAll();+ const hasSelectAll = visibleItems.length > 0;+ const { selectFirstOption, selectNextOption, getSelectedOptionIndex } =+ combobox;++ const highlightFirstColumn = useCallback(() => {+ selectFirstOption();++ const hasSelectedSelectAll = getSelectedOptionIndex() === 0;+ if (hasSelectedSelectAll) {+ /**+ * Reasons to skip "Select all" and select the first actual column:+ * - When searching you expect the first match to toggle+ * - An accidental "Select all" is lossy+ */+ selectNextOption();+ }+ }, [selectFirstOption, selectNextOption, getSelectedOptionIndex]);++ useEffect(() => {+ highlightFirstColumn();+ }, [highlightFirstColumn]);++ const isAllVisibleSelected = visibleItems.every((item) => item.isSelected);+ const isNoneVisibleSelected = visibleItems.every((item) => !item.isSelected);+ // When every visible column is selected the control deselects them;+ // otherwise it selects the rest.+ const itemsToToggle = visibleItems.filter(+ (item) => !item.isDisabled && item.isSelected === isAllVisibleSelected,+ );++ const handleSearchChange = (value: string) => {+ // highlightFirstColumn reads the rendered options, so commit the filtered+ // list first.+ flushSync(() => setSearchText(value));+ highlightFirstColumn();+ };++ const handleSearchClear = () => {+ handleSearchChange("");+ // The clear button unmounts once the search is empty, which would drop+ // focus to the document body.+ combobox.focusSearchInput();+ };++ const handleOptionSubmit = (id: string) => {+ if (id === SELECT_ALL_VALUE) {+ onToggleColumns(+ itemsToToggle.map((item) => item.column),+ !isAllVisibleSelected,+ );+ return;+ }+ const item = items.find((item) => item.id === id);+ if (item && !item.isDisabled) {+ onToggle(item.column, !item.isSelected);+ }+ };++ const handleListKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key === " " && combobox.getSelectedOptionIndex() !== -1) {+ event.preventDefault();+ combobox.clickSelectedOption();}};return (- <ul className={S.ItemList} data-testid={props["data-testid"]}>- <li className={S.ToggleItem}>- <HoverParent as="label" className={S.Label}>- <Checkbox- variant="stacked"- checked={isAll}- indeterminate={!isAll && !isNone}- onChange={handleLabelToggle}- />- <div className={S.ItemTitle}>{t`Select all`}</div>- </HoverParent>- </li>- <DelayGroup>- {items.map((item) => (- <li key={item.columnInfo.longDisplayName}>- <HoverParent className={S.Label} as="label">- <Checkbox- checked={item.isSelected}- disabled={item.isDisabled}- onChange={(event) =>- onToggle(item.column, event.target.checked)- }- />- <QueryColumnInfoIcon- className={S.ItemIcon}- query={query}- stageIndex={stageIndex}- column={item.column}- position="top-start"- size={16}- />- <div className={S.ItemTitle}>- {tc(item.columnInfo.displayName)}- </div>- </HoverParent>- </li>- ))}- </DelayGroup>- </ul>+ <div data-testid={props["data-testid"]}>+ <Combobox+ store={combobox}+ onOptionSubmit={handleOptionSubmit}+ classNames={{+ search: S.Search,+ options: S.Options,+ option: S.Option,+ empty: S.Empty,+ }}+ >+ {isSearchable && (+ <div className={S.SearchContainer}>+ <Combobox.Search+ aria-label={t`Search columns`}+ placeholder={t`Search columns…`}+ value={searchText}+ data-autofocus={isSearchAutofocused || undefined}+ leftSection={<Icon name="search" />}+ rightSectionPointerEvents="all"+ rightSection={+ searchText.length > 0 ? (+ <Input.ClearButton+ aria-label={t`Clear search`}+ c="text-secondary"+ onClick={handleSearchClear}+ />+ ) : null+ }+ onChange={(event) =>+ handleSearchChange(event.currentTarget.value)+ }+ />+ <div+ id={matchCountId}+ role="status"+ aria-live="polite"+ className={visuallyHidden.visuallyHidden}+ >+ {isSearching &&+ ngettext(+ msgid`${visibleItems.length} column found`,+ `${visibleItems.length} columns found`,+ visibleItems.length,+ )}+ </div>+ </div>+ )}+ <div className={S.List}>+ {/* The listbox itself takes focus and drives navigation via+ aria-activedescendant; drop the attributes that only make sense+ on a combobox input. */}+ <Combobox.EventsTarget+ aria-haspopup={undefined}+ aria-controls={undefined}+ >+ <Combobox.Options+ aria-label={t`Columns`}+ aria-multiselectable="true"+ tabIndex={0}+ data-autofocus={!isSearchAutofocused || undefined}+ onKeyDown={handleListKeyDown}+ >+ {hasSelectAll && (+ <SelectAllOption+ label={isSearching ? t`Select all of these` : t`Select all`}+ checked={isAllVisibleSelected}+ indeterminate={+ !isAllVisibleSelected && !isNoneVisibleSelected+ }+ disabled={itemsToToggle.length === 0}+ descriptionId={isSearching ? matchCountId : undefined}+ />+ )}+ {visibleItems.length > 0 && (+ <Combobox.Group className={S.ColumnGroup}>+ <DelayGroup>+ {visibleItems.map((item) => (+ <Combobox.Option+ key={item.id}+ value={item.id}+ disabled={item.isDisabled}+ aria-label={item.title}+ aria-selected={item.isSelected}+ aria-disabled={item.isDisabled || undefined}+ >+ <HoverParent className={S.Row}>+ <Checkbox+ className={S.RowCheckbox}+ checked={item.isSelected}+ disabled={item.isDisabled}+ readOnly+ aria-hidden+ tabIndex={-1}+ />+ <QueryColumnInfoIcon+ className={S.ItemIcon}+ query={query}+ stageIndex={stageIndex}+ column={item.column}+ position="top-start"+ size={16}+ />+ <div className={S.ItemTitle}>{item.title}</div>+ </HoverParent>+ </Combobox.Option>+ ))}+ </DelayGroup>+ </Combobox.Group>+ )}+ {isSearching && visibleItems.length === 0 && (+ <Combobox.Empty>{t`No columns found`}</Combobox.Empty>+ )}+ </Combobox.Options>+ </Combobox.EventsTarget>+ </div>+ </Combobox>+ </div>);};++interface SelectAllOptionProps extends Pick<+ CheckboxProps,+ "checked" | "indeterminate" | "disabled"+> {+ label: string;+ descriptionId?: string;+}++function SelectAllOption({+ label,+ checked,+ indeterminate,+ disabled,+ descriptionId,+}: SelectAllOptionProps) {+ return (+ <Combobox.Option+ value={SELECT_ALL_VALUE}+ disabled={disabled}+ aria-label={label}+ // Mantine rewrites aria-selected to mark the keyboard highlight, and+ // aria-checked can also express the partial state.+ aria-checked={indeterminate ? "mixed" : checked}+ aria-disabled={disabled || undefined}+ aria-describedby={descriptionId}+ >+ <div className={S.ToggleRow}>+ <Checkbox+ className={S.RowCheckbox}+ variant="stacked"+ checked={checked}+ indeterminate={indeterminate}+ disabled={disabled}+ readOnly+ aria-hidden+ tabIndex={-1}+ />+ <div className={S.ItemTitle}>{label}</div>+ </div>+ </Combobox.Option>+ );+}diff --git a/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.unit.spec.tsxnew file mode 100644index 00000000000..779857147a1--- /dev/null+++ b/frontend/src/metabase/querying/notebook/components/FieldPicker/FieldPicker.unit.spec.tsx@@ -0,0 +1,445 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import { setupForContentTranslationTest } from "metabase/content-translation/test-utils";+import * as Lib from "metabase-lib";++import {+ type SampleTableName,+ createSampleTableQuery,+ getColumnNames,+} from "../../test-utils";++import {+ FieldPicker,+ type FieldPickerItem,+ MIN_SEARCHABLE_COLUMN_COUNT,+} from "./FieldPicker";++const STAGE_INDEX = 0;++interface SetupOpts {+ tableName?: SampleTableName;+ selectedColumnNames?: string[];+}++function isColumnSelected({ columnInfo }: FieldPickerItem) {+ return Boolean(columnInfo.selected);+}++function isColumnDisabled(item: FieldPickerItem, items: FieldPickerItem[]) {+ const isOnlySelected = items.filter(isColumnSelected).length === 1;+ return isColumnSelected(item) && isOnlySelected;+}++function createFieldPicker({+ tableName = "ORDERS",+ selectedColumnNames,+}: SetupOpts = {}) {+ const query = createSampleTableQuery(tableName, selectedColumnNames);+ const columns = Lib.fieldableColumns(query, STAGE_INDEX);+ const onToggle = jest.fn();+ const onToggleColumns = jest.fn();++ const component = (+ <FieldPicker+ query={query}+ stageIndex={STAGE_INDEX}+ columns={columns}+ isColumnSelected={isColumnSelected}+ isColumnDisabled={isColumnDisabled}+ onToggle={onToggle}+ onToggleColumns={onToggleColumns}+ data-testid="fields-picker"+ />+ );++ return { component, query, columns, onToggle, onToggleColumns };+}++function setup(opts: SetupOpts = {}) {+ const { component, ...rest } = createFieldPicker(opts);+ renderWithProviders(component);+ return rest;+}++function setupSearchable(opts: Omit<SetupOpts, "tableName"> = {}) {+ return setup({ ...opts, tableName: "PEOPLE" });+}++function getSearchInput() {+ return screen.getByLabelText("Search columns");+}++function getListbox() {+ return screen.getByRole("listbox", { name: "Columns" });+}++function getColumnOptions() {+ const columnGroup = within(getListbox()).getByRole("group");+ return within(columnGroup).getAllByRole("option");+}++function getOptionNames() {+ return getColumnOptions().map((option) => option.getAttribute("aria-label"));+}++function getHighlightedOptionName() {+ return getListbox()+ .querySelector("[data-combobox-selected]")+ ?.getAttribute("aria-label");+}++function getToggledColumnName(+ onToggle: jest.Mock,+ query: Lib.Query,+): [string, boolean] {+ const [column, isSelected] = onToggle.mock.calls[0];+ return [Lib.displayInfo(query, STAGE_INDEX, column).name, isSelected];+}++function getToggledColumnNames(+ onToggleColumns: jest.Mock,+ query: Lib.Query,+): [string[], boolean] {+ const [columns, isSelected] = onToggleColumns.mock.calls[0];+ return [getColumnNames(query, STAGE_INDEX, columns), isSelected];+}++describe("FieldPicker", () => {+ it("should render the columns as a multiselectable listbox", () => {+ const { columns } = setup();++ expect(screen.getByRole("listbox")).toHaveAttribute(+ "aria-multiselectable",+ "true",+ );+ expect(getColumnOptions()).toHaveLength(columns.length);+ expect(screen.getByRole("option", { name: "Select all" })).toBeChecked();+ });++ it("should not show a search box when there are few columns", () => {+ const { columns } = setup();++ expect(columns.length).toBeLessThan(MIN_SEARCHABLE_COLUMN_COUNT);+ expect(screen.queryByLabelText("Search columns")).not.toBeInTheDocument();+ expect(getListbox()).toHaveAttribute("data-autofocus");+ });++ it("should reflect selection and disabled state on the options", () => {+ setup({ selectedColumnNames: ["ID"] });++ expect(screen.getByRole("option", { name: "ID" })).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByRole("option", { name: "ID" })).toHaveAttribute(+ "aria-disabled",+ "true",+ );+ expect(screen.getByRole("option", { name: "Tax" })).toHaveAttribute(+ "aria-selected",+ "false",+ );+ expect(screen.getByRole("option", { name: "Tax" })).not.toHaveAttribute(+ "aria-disabled",+ );+ });++ it("should select a column when its option is clicked", async () => {+ const { onToggle, query } = setup({ selectedColumnNames: ["ID"] });++ await userEvent.click(screen.getByRole("option", { name: "Tax" }));++ expect(onToggle).toHaveBeenCalledTimes(1);+ expect(getToggledColumnName(onToggle, query)).toEqual(["TAX", true]);+ });++ it("should deselect a selected column", async () => {+ const { onToggle, query } = setup({ selectedColumnNames: ["ID", "TAX"] });++ await userEvent.click(screen.getByRole("option", { name: "Tax" }));++ expect(getToggledColumnName(onToggle, query)).toEqual(["TAX", false]);+ });++ it("should not toggle a disabled column", async () => {+ const { onToggle } = setup({ selectedColumnNames: ["ID"] });++ await userEvent.click(screen.getByRole("option", { name: "ID" }));++ expect(onToggle).not.toHaveBeenCalled();+ });++ it("should navigate the list from the listbox when there is no search box", async () => {+ const { onToggle, query, columns } = setup();+ const [, secondColumnName] = getColumnNames(query, STAGE_INDEX, columns);++ getListbox().focus();+ await userEvent.keyboard("{ArrowDown}{Enter}");++ expect(getToggledColumnName(onToggle, query)).toEqual([+ secondColumnName,+ false,+ ]);+ expect(onToggle).toHaveBeenCalledTimes(1);+ });++ it("should toggle the highlighted column with Space", async () => {+ const { onToggle, query, columns } = setup();+ const [firstColumnName] = getColumnNames(query, STAGE_INDEX, columns);++ getListbox().focus();+ await userEvent.keyboard(" ");++ expect(getToggledColumnName(onToggle, query)).toEqual([+ firstColumnName,+ false,+ ]);+ });++ it("should reach 'Select all' with the arrow keys", async () => {+ const { onToggle, onToggleColumns, query, columns } = setup();++ getListbox().focus();+ await userEvent.keyboard("{ArrowUp}");+ expect(getHighlightedOptionName()).toBe("Select all");++ await userEvent.keyboard("{Enter}");++ expect(onToggle).not.toHaveBeenCalled();+ expect(getToggledColumnNames(onToggleColumns, query)).toEqual([+ getColumnNames(query, STAGE_INDEX, columns),+ false,+ ]);+ });++ it("should select the remaining columns and skip disabled ones", async () => {+ const { onToggleColumns, query, columns } = setup({+ selectedColumnNames: ["ID"],+ });++ await userEvent.click(screen.getByLabelText("Select all"));++ expect(getToggledColumnNames(onToggleColumns, query)).toEqual([+ getColumnNames(query, STAGE_INDEX, columns).filter(+ (name) => name !== "ID",+ ),+ true,+ ]);+ });++ it("should deselect every column when all of them are selected", async () => {+ const { onToggleColumns, query, columns } = setup();++ await userEvent.click(screen.getByLabelText("Select all"));++ expect(getToggledColumnNames(onToggleColumns, query)).toEqual([+ getColumnNames(query, STAGE_INDEX, columns),+ false,+ ]);+ });++ describe("searching", () => {+ it("should mark the search box for autofocus when there are many columns", () => {+ const { columns } = setupSearchable();++ expect(columns.length).toBeGreaterThanOrEqual(+ MIN_SEARCHABLE_COLUMN_COUNT,+ );+ expect(getSearchInput()).toHaveAttribute("data-autofocus");+ expect(getListbox()).not.toHaveAttribute("data-autofocus");+ });++ it("should filter columns case-insensitively", async () => {+ setupSearchable();++ await userEvent.type(getSearchInput(), "TUDE");++ expect(getOptionNames()).toEqual(["Latitude", "Longitude"]);+ expect(screen.getByRole("status")).toHaveTextContent("2 columns found");+ });++ it("should keep the search box while the filtered list is short", async () => {+ setupSearchable();++ await userEvent.type(getSearchInput(), "email");++ expect(getOptionNames()).toEqual(["Email"]);+ expect(getSearchInput()).toBeInTheDocument();+ });++ it("should show an empty state when nothing matches", async () => {+ setupSearchable();++ await userEvent.type(getSearchInput(), "does not exist");++ expect(screen.getByText("No columns found")).toBeInTheDocument();+ expect(screen.getByRole("status")).toHaveTextContent("0 columns found");+ expect(+ screen.queryByLabelText("Select all of these"),+ ).not.toBeInTheDocument();+ });++ it("should toggle a column by clicking it in the filtered list", async () => {+ const { onToggle, query } = setupSearchable({+ selectedColumnNames: ["ID"],+ });++ await userEvent.type(getSearchInput(), "email");+ await userEvent.click(screen.getByRole("option", { name: "Email" }));++ expect(onToggle).toHaveBeenCalledTimes(1);+ expect(getToggledColumnName(onToggle, query)).toEqual(["EMAIL", true]);+ });++ it("should highlight the first match while typing and toggle it with Enter", async () => {+ const { onToggle, query } = setupSearchable({+ selectedColumnNames: ["ID"],+ });++ await userEvent.type(getSearchInput(), "email");+ expect(getHighlightedOptionName()).toBe("Email");++ await userEvent.keyboard("{Enter}");++ expect(getToggledColumnName(onToggle, query)).toEqual(["EMAIL", true]);+ expect(getSearchInput()).toHaveFocus();+ });++ it("should move the highlight with the arrow keys from the search box", async () => {+ const { onToggle, query } = setupSearchable({+ selectedColumnNames: ["ID"],+ });++ await userEvent.type(getSearchInput(), "tude");+ expect(getHighlightedOptionName()).toBe("Latitude");++ await userEvent.keyboard("{ArrowDown}");+ expect(getHighlightedOptionName()).toBe("Longitude");++ await userEvent.keyboard("{ArrowUp}");+ expect(getHighlightedOptionName()).toBe("Latitude");++ await userEvent.keyboard("{ArrowDown}{Enter}");+ expect(getToggledColumnName(onToggle, query)).toEqual([+ "LONGITUDE",+ true,+ ]);+ });++ it("should restore the full list when the search is cleared", async () => {+ const { columns } = setupSearchable();++ await userEvent.type(getSearchInput(), "email");+ await userEvent.click(screen.getByLabelText("Clear search"));++ expect(getSearchInput()).toHaveValue("");+ expect(+ screen.getByRole("option", { name: "Select all" }),+ ).toBeInTheDocument();+ expect(getColumnOptions()).toHaveLength(columns.length);+ });++ it("should return focus to the search box when the search is cleared", async () => {+ setupSearchable();++ await userEvent.type(getSearchInput(), "email");+ await userEvent.click(screen.getByLabelText("Clear search"));++ await waitFor(() => expect(getSearchInput()).toHaveFocus());+ });++ it("should render each column once across repeated searches", async () => {+ const { columns } = setupSearchable();+ const allNames = getOptionNames();++ for (const term of ["tude", "email", "zzz"]) {+ await userEvent.type(getSearchInput(), term);+ await userEvent.clear(getSearchInput());++ expect(getOptionNames()).toEqual(allNames);+ expect(getColumnOptions()).toHaveLength(columns.length);+ expect(screen.getAllByText("ID")).toHaveLength(1);+ }+ });++ describe("'Select all of these'", () => {+ it("should replace 'Select all' while searching and describe the match count", async () => {+ setupSearchable();++ await userEvent.type(getSearchInput(), "tude");++ const option = screen.getByRole("option", {+ name: "Select all of these",+ });+ expect(option).toBeChecked();+ expect(option).toHaveAccessibleDescription("2 columns found");+ expect(screen.queryByLabelText("Select all")).not.toBeInTheDocument();+ });++ it("should only select the matching columns that aren't selected yet", async () => {+ const { onToggleColumns, query } = setupSearchable({+ selectedColumnNames: ["ID", "LONGITUDE"],+ });++ await userEvent.type(getSearchInput(), "tude");+ const option = screen.getByRole("option", {+ name: "Select all of these",+ });+ // toBeChecked() throws on aria-checked="mixed", and toBePartiallyChecked()+ // only supports checkboxes, not options.+ // eslint-disable-next-line jest-dom/prefer-checked+ expect(option).toHaveAttribute("aria-checked", "mixed");+ await userEvent.click(option);++ expect(getToggledColumnNames(onToggleColumns, query)).toEqual([+ ["LATITUDE"],+ true,+ ]);+ });++ it("should only deselect the matching columns when they are all selected", async () => {+ const { onToggleColumns, query } = setupSearchable();++ await userEvent.type(getSearchInput(), "tude");+ await userEvent.click(screen.getByLabelText("Select all of these"));++ expect(getToggledColumnNames(onToggleColumns, query)).toEqual([+ ["LATITUDE", "LONGITUDE"],+ false,+ ]);+ });++ it("should be disabled when the only matches can't be toggled", async () => {+ setupSearchable({ selectedColumnNames: ["ID"] });++ await userEvent.type(getSearchInput(), "id");++ expect(getOptionNames()).toEqual(["ID"]);+ expect(+ screen.getByRole("option", { name: "Select all of these" }),+ ).toHaveAttribute("aria-disabled", "true");+ });+ });++ it("should match against the translated column name", async () => {+ const { component } = createFieldPicker({ tableName: "PEOPLE" });+ setupForContentTranslationTest({+ component,+ enterprisePlugins: ["content_translation"],+ tokenFeatures: { content_translation: true },+ staticallyEmbedded: true,+ dictionary: [{ msgid: "Email", msgstr: "Correo", locale: "en" }],+ });++ expect(+ await screen.findByRole("option", { name: "Correo" }),+ ).toBeInTheDocument();++ await userEvent.type(getSearchInput(), "corr");++ expect(getOptionNames()).toEqual(["Correo"]);+ });+ });+});diff --git a/frontend/src/metabase/querying/notebook/components/FieldPicker/index.ts b/frontend/src/metabase/querying/notebook/components/FieldPicker/index.tsindex c21c4106892..4a4f769ed03 100644--- a/frontend/src/metabase/querying/notebook/components/FieldPicker/index.ts+++ b/frontend/src/metabase/querying/notebook/components/FieldPicker/index.ts@@ -1 +1,2 @@export * from "./FieldPicker";+export * from "./utils";diff --git a/frontend/src/metabase/querying/notebook/components/FieldPicker/utils.ts b/frontend/src/metabase/querying/notebook/components/FieldPicker/utils.tsnew file mode 100644index 00000000000..24709ae6493--- /dev/null+++ b/frontend/src/metabase/querying/notebook/components/FieldPicker/utils.ts@@ -0,0 +1,29 @@+interface GetNextSelectedColumnsOpts<T> {+ columns: readonly T[];+ selectedColumns: readonly T[];+ toggledColumns: readonly T[];+ isSelected: boolean;+}++/**+ * Called after a subset of columns is toggled, returning the new set of+ * selected columns.+ * @param arg+ * @param arg.columns - all available columns+ * @param arg.selectedColumns - selected columns before calling this function+ * @param arg.toggledColumns - columns to toggle+ * @param arg.isSelected - value to change the toggled columns to+ */+export function getNextSelectedColumns<T>({+ columns,+ selectedColumns,+ toggledColumns,+ isSelected,+}: GetNextSelectedColumnsOpts<T>): T[] {+ const selected = new Set(selectedColumns);+ const targets = new Set(toggledColumns);++ return columns.filter((column) =>+ targets.has(column) ? isSelected : selected.has(column),+ );+}diff --git a/frontend/src/metabase/querying/notebook/components/FieldPicker/utils.unit.spec.ts b/frontend/src/metabase/querying/notebook/components/FieldPicker/utils.unit.spec.tsnew file mode 100644index 00000000000..d71f8b84522--- /dev/null+++ b/frontend/src/metabase/querying/notebook/components/FieldPicker/utils.unit.spec.ts@@ -0,0 +1,38 @@+import { getNextSelectedColumns } from "./utils";++const COLUMNS = ["a", "b", "c", "d"];++describe("getNextSelectedColumns", () => {+ it("should add the targets to the selection in column order", () => {+ expect(+ getNextSelectedColumns({+ columns: COLUMNS,+ selectedColumns: ["c"],+ toggledColumns: ["d", "a"],+ isSelected: true,+ }),+ ).toEqual(["a", "c", "d"]);+ });++ it("should remove the targets and keep the rest of the selection", () => {+ expect(+ getNextSelectedColumns({+ columns: COLUMNS,+ selectedColumns: ["a", "b", "c"],+ toggledColumns: ["b"],+ isSelected: false,+ }),+ ).toEqual(["a", "c"]);+ });++ it("should return an empty selection when every selected column is removed", () => {+ expect(+ getNextSelectedColumns({+ columns: COLUMNS,+ selectedColumns: ["a", "b"],+ toggledColumns: ["a", "b"],+ isSelected: false,+ }),+ ).toEqual([]);+ });+});diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsxindex c9d1d2999ee..438c6ddef17 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinStep.unit.spec.tsx@@ -37,13 +37,14 @@ import {} from "metabase-types/api/mocks";import {ORDERS_ID,+ PEOPLE_ID,PRODUCTS_ID,createSampleDatabase,createSavedStructuredCard,createStructuredModelCard,} from "metabase-types/api/mocks/presets";-import { createMockNotebookStep } from "../../test-utils";+import { createMockNotebookStep, getColumnNames } from "../../test-utils";import type { NotebookStep } from "../../types";import { NotebookProvider } from "../Notebook/context";@@ -874,15 +875,30 @@ describe("Notebook Editor > Join Step", () => {"join-columns-picker",);await userEvent.click(within(joinColumnsPicker).getByText("Select all"));- expect(within(joinColumnsPicker).getByLabelText("ID")).not.toBeChecked();- expect(within(joinColumnsPicker).getByLabelText("ID")).toBeEnabled();+ expect(within(joinColumnsPicker).getByLabelText("ID")).toHaveAttribute(+ "aria-selected",+ "false",+ );+ expect(+ within(joinColumnsPicker).getByLabelText("ID"),+ ).not.toHaveAttribute("aria-disabled");await userEvent.click(within(joinColumnsPicker).getByLabelText("ID"));- expect(within(joinColumnsPicker).getByLabelText("ID")).toBeChecked();- expect(within(joinColumnsPicker).getByLabelText("ID")).toBeEnabled();+ expect(within(joinColumnsPicker).getByLabelText("ID")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(+ within(joinColumnsPicker).getByLabelText("ID"),+ ).not.toHaveAttribute("aria-disabled");await userEvent.click(within(joinColumnsPicker).getByLabelText("ID"));- expect(within(joinColumnsPicker).getByLabelText("ID")).not.toBeChecked();- expect(within(joinColumnsPicker).getByLabelText("ID")).toBeEnabled();+ expect(within(joinColumnsPicker).getByLabelText("ID")).toHaveAttribute(+ "aria-selected",+ "false",+ );+ expect(+ within(joinColumnsPicker).getByLabelText("ID"),+ ).not.toHaveAttribute("aria-disabled");});it("should be able to select no columns when adding a new join", async () => {@@ -964,6 +980,62 @@ describe("Notebook Editor > Join Step", () => {const { fields } = getRecentJoin();expect(fields).toBe("none");});++ it("should only change the matching columns for an existing join when searching", async () => {+ const query = Lib.createTestQuery(provider, {+ stages: [+ {+ source: { type: "table", id: ORDERS_ID },+ joins: [+ {+ source: { type: "table", id: PEOPLE_ID },+ strategy: "left-join",+ conditions: [+ {+ operator: "=",+ left: {+ type: "column",+ sourceName: "ORDERS",+ name: "USER_ID",+ },+ right: { type: "column", sourceName: "PEOPLE", name: "ID" },+ },+ ],+ },+ ],+ },+ ],+ });+ const [join] = Lib.joins(query, 0);+ const peopleColumnNames = getColumnNames(+ query,+ 0,+ Lib.joinableColumns(query, 0, join),+ );+ const { getRecentJoin } = setup({+ step: createMockNotebookStep({ query }),+ });++ await userEvent.click(screen.getByLabelText("Pick columns"));+ const picker = await screen.findByTestId("join-columns-picker");+ await userEvent.type(+ within(picker).getByLabelText("Search columns"),+ "tude",+ );+ await userEvent.click(+ within(picker).getByLabelText("Select all of these"),+ );++ const { query: nextQuery, fields } = getRecentJoin();+ if (fields === "all" || fields === "none") {+ throw new Error(`Expected an explicit column list, got "${fields}"`);+ }+ expect(getColumnNames(nextQuery, 0, fields)).toEqual(+ peopleColumnNames.filter(+ (name) => name !== "LATITUDE" && name !== "LONGITUDE",+ ),+ );+ });});describe("multiple conditions", () => {diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnDraftPicker/JoinTableColumnDraftPicker.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnDraftPicker/JoinTableColumnDraftPicker.tsxindex 4fed5446f02..4b416a2efed 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnDraftPicker/JoinTableColumnDraftPicker.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnDraftPicker/JoinTableColumnDraftPicker.tsx@@ -1,6 +1,10 @@import type * as Lib from "metabase-lib";-import { FieldPicker, type FieldPickerItem } from "../../FieldPicker";+import {+ FieldPicker,+ type FieldPickerItem,+ getNextSelectedColumns,+} from "../../FieldPicker";interface JoinTableColumnPickerDraftProps {query: Lib.Query;@@ -32,12 +36,18 @@ export function JoinTableColumnDraftPicker({onChange(newSelectedColumns);};- const handleSelectAll = () => {- onChange(columns);- };-- const handleSelectNone = () => {- onChange([]);+ const handleToggleColumns = (+ toggledColumns: Lib.ColumnMetadata[],+ isSelected: boolean,+ ) => {+ onChange(+ getNextSelectedColumns({+ columns,+ selectedColumns,+ toggledColumns,+ isSelected,+ }),+ );};return (@@ -47,8 +57,7 @@ export function JoinTableColumnDraftPicker({columns={columns}isColumnSelected={isColumnSelected}onToggle={handleToggle}- onSelectAll={handleSelectAll}- onSelectNone={handleSelectNone}+ onToggleColumns={handleToggleColumns}data-testid="join-columns-picker"/>);diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnPicker/JoinTableColumnPicker.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnPicker/JoinTableColumnPicker.tsxindex f3042182e23..0ecb892508f 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnPicker/JoinTableColumnPicker.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTableColumnPicker/JoinTableColumnPicker.tsx@@ -2,7 +2,11 @@ import { useMemo } from "react";import * as Lib from "metabase-lib";-import { FieldPicker, type FieldPickerItem } from "../../FieldPicker";+import {+ FieldPicker,+ type FieldPickerItem,+ getNextSelectedColumns,+} from "../../FieldPicker";interface JoinTableColumnPickerProps {query: Lib.Query;@@ -29,14 +33,23 @@ export function JoinTableColumnPicker({onChange(newQuery);};- const handleSelectAll = () => {- const newJoin = Lib.withJoinFields(join, "all");- const newQuery = Lib.replaceClause(query, stageIndex, join, newJoin);- onChange(newQuery);- };-- const handleSelectNone = () => {- const newJoin = Lib.withJoinFields(join, "none");+ const handleToggleColumns = (+ toggledColumns: Lib.ColumnMetadata[],+ isSelected: boolean,+ ) => {+ const selectedColumns = columns.filter(+ (column) => Lib.displayInfo(query, stageIndex, column).selected,+ );+ const nextColumns = getNextSelectedColumns({+ columns,+ selectedColumns,+ toggledColumns,+ isSelected,+ });+ const newJoin = Lib.withJoinFields(+ join,+ getJoinFields(nextColumns, columns),+ );const newQuery = Lib.replaceClause(query, stageIndex, join, newJoin);onChange(newQuery);};@@ -48,8 +61,7 @@ export function JoinTableColumnPicker({columns={columns}isColumnSelected={isColumnSelected}onToggle={handleToggle}- onSelectAll={handleSelectAll}- onSelectNone={handleSelectNone}+ onToggleColumns={handleToggleColumns}data-testid="join-columns-picker"/>);@@ -58,3 +70,16 @@ export function JoinTableColumnPicker({function isColumnSelected({ columnInfo }: FieldPickerItem) {return Boolean(columnInfo.selected);}++function getJoinFields(+ selectedColumns: Lib.ColumnMetadata[],+ columns: Lib.ColumnMetadata[],+): Lib.JoinFields {+ if (selectedColumns.length === 0) {+ return "none";+ }+ if (selectedColumns.length === columns.length) {+ return "all";+ }+ return selectedColumns;+}diff --git a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTablePicker/JoinTablePicker.tsx b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTablePicker/JoinTablePicker.tsxindex 22ab9437c9c..49c4e3d9683 100644--- a/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTablePicker/JoinTablePicker.tsx+++ b/frontend/src/metabase/querying/notebook/components/JoinStep/JoinTablePicker/JoinTablePicker.tsx@@ -100,7 +100,7 @@ function JoinTableColumnPicker({ columnPicker }: JoinTableColumnPickerProps) {const [isOpened, setIsOpened] = useState(false);return (- <Popover opened={isOpened} onChange={setIsOpened}>+ <Popover opened={isOpened} onChange={setIsOpened} trapFocus returnFocus><Popover.Target><Tooltip label={t`Pick columns`}><IconButtonWrapperdiff --git a/frontend/src/metabase/querying/notebook/test-utils.ts b/frontend/src/metabase/querying/notebook/test-utils.tsindex 921739f272e..5ba1342b679 100644--- a/frontend/src/metabase/querying/notebook/test-utils.ts+++ b/frontend/src/metabase/querying/notebook/test-utils.ts@@ -2,7 +2,11 @@import { createMockMetadata } from "__support__/metadata";import { checkNotNull } from "metabase/utils/types";+import * as Lib from "metabase-lib";+import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";import {+ ORDERS_ID,+ PEOPLE_ID,createSampleDatabase,createSavedStructuredCard,} from "metabase-types/api/mocks/presets";@@ -44,3 +48,38 @@ export function createMockNotebookStep({...opts,};}++const SAMPLE_TABLE_IDS = {+ ORDERS: ORDERS_ID,+ PEOPLE: PEOPLE_ID,+};++export type SampleTableName = keyof typeof SAMPLE_TABLE_IDS;++export function createSampleTableQuery(+ tableName: SampleTableName,+ fieldNames?: string[],+) {+ return Lib.createTestQuery(SAMPLE_PROVIDER, {+ stages: [+ {+ source: { type: "table", id: SAMPLE_TABLE_IDS[tableName] },+ fields: fieldNames?.map((name) => ({+ type: "column",+ sourceName: tableName,+ name,+ })),+ },+ ],+ });+}++export function getColumnNames(+ query: Lib.Query,+ stageIndex: number,+ columns: Lib.ColumnMetadata[],+) {+ return columns.map(+ (column) => Lib.displayInfo(query, stageIndex, column).name,+ );+}