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
Fix custom row limit resetting the provided value (#74490)
Oleh K080a04582a18
diff --git a/frontend/src/metabase/query_builder/components/LimitPopover.tsx b/frontend/src/metabase/query_builder/components/LimitPopover.tsxindex 1eab8d25297..8775673017f 100644--- a/frontend/src/metabase/query_builder/components/LimitPopover.tsx+++ b/frontend/src/metabase/query_builder/components/LimitPopover.tsx@@ -1,85 +1,107 @@import cx from "classnames";-import type { KeyboardEvent } from "react";+import { useEffect, useRef, useState } from "react";+import { useLatest } from "react-use";import { t } from "ttag";import { Radio } from "metabase/common/components/Radio";import CS from "metabase/css/core/index.css";import { LimitInput } from "metabase/querying/components/LimitInput";+import { Box } from "metabase/ui";import { formatNumber } from "metabase/utils/formatting";import { HARD_ROW_LIMIT } from "metabase-lib/v1/queries/utils";-interface CustomRowLimitProps {+interface LimitPopoverProps {limit: number | null;onChangeLimit: (limit: number | null) => void;onClose: () => void;+ className?: string;}-const CustomRowLimit = ({+export const LimitPopover = ({limit,onChangeLimit,onClose,-}: CustomRowLimitProps) => {+ className,+}: LimitPopoverProps) => {+ const [isCustom, setIsCustom] = useState(limit != null);+ const [value, setValue] = useState(+ limit != null ? String(limit) : String(HARD_ROW_LIMIT),+ );+ const inputRef = useRef<HTMLInputElement>(null);+ // Set when the popover is dismissed with Escape so the pending value is+ // discarded instead of applied on unmount+ const cancelRef = useRef(false);++ const parsedValue = parseInt(value, 10);+ const selectedLimit = isCustom && parsedValue > 0 ? parsedValue : null;++ const selectedLimitRef = useLatest(selectedLimit);+ const limitRef = useLatest(limit);+ const onChangeLimitRef = useLatest(onChangeLimit);++ useEffect(() => {+ const applyPendingLimit = () => {+ if (cancelRef.current) {+ return;+ }+ if (selectedLimitRef.current !== limitRef.current) {+ onChangeLimitRef.current(selectedLimitRef.current);+ }+ };+ return () => applyPendingLimit();+ }, [selectedLimitRef, limitRef, onChangeLimitRef]);+return (- <LimitInput- small- defaultValue={limit ?? undefined}- className={cx({ [cx(CS.textBrand, CS.borderBrand)]: limit != null })}- placeholder={t`Pick a limit`}- onKeyPress={(e: KeyboardEvent<HTMLInputElement>) => {- if (e.nativeEvent.isComposing) {- return;+ <Box+ className={cx(className, CS.textBold, CS.textMedium)}+ onKeyDownCapture={(e) => {+ if (e.key === "Escape") {+ cancelRef.current = true;}- if (e.key === "Enter") {- const value = parseInt(e.currentTarget.value, 10);- if (value > 0) {- onChangeLimit(value);+ }}+ >+ <Radio+ vertical+ value={isCustom ? "custom" : "maximum"}+ options={[+ {+ name: t`Show maximum (first ${formatNumber(HARD_ROW_LIMIT)})`,+ value: "maximum",+ },+ {+ name: t`Set custom limit`,+ value: "custom",+ },+ ]}+ onChange={(selected: string) => {+ if (selected === "maximum") {+ setIsCustom(false);} else {- onChangeLimit(null);+ setIsCustom(true);+ inputRef.current?.focus();+ inputRef.current?.select();}- onClose();- }- }}- />+ }}+ />+ <Box mt="sm" ml="1.25rem">+ <LimitInput+ ref={inputRef}+ small+ value={value}+ className={cx({ [cx(CS.textBrand, CS.borderBrand)]: isCustom })}+ placeholder={t`Pick a limit`}+ onFocus={() => setIsCustom(true)}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={(e) => {+ if (e.nativeEvent.isComposing) {+ return;+ }+ if (e.key === "Enter") {+ onClose();+ }+ }}+ />+ </Box>+ </Box>);};--interface LimitPopoverProps {- limit: number | null;- onChangeLimit: (limit: number | null) => void;- onClose: () => void;- className?: string;-}--export const LimitPopover = ({- limit,- onChangeLimit,- onClose,- className,-}: LimitPopoverProps) => (- <div className={cx(className, CS.textBold, CS.textMedium)}>- <Radio- vertical- value={limit == null ? "maximum" : "custom"}- options={[- {- name: t`Show maximum (first ${formatNumber(HARD_ROW_LIMIT)})`,- value: "maximum",- },- {- name: (- <CustomRowLimit- key={limit == null ? "a" : "b"}- limit={limit}- onChangeLimit={onChangeLimit}- onClose={onClose}- />- ),- value: "custom",- },- ]}- onChange={(value: string) =>- value === "maximum" ? onChangeLimit(null) : onChangeLimit(2000)- }- />- </div>-);diff --git a/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.tsx b/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.tsxindex 53cf1fa1cab..9ff1efe39ad 100644--- a/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.tsx+++ b/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.tsx@@ -114,7 +114,7 @@ function QuestionRowCountInner({}return (- <Popover opened={opened} onClose={close} position="bottom-start">+ <Popover opened={opened} onDismiss={close} position="bottom-end"><Popover.Target><UnstyledButton onClick={toggle} id={POPOVER_ID} aria-haspopup="dialog"><RowCountLabeldiff --git a/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.unit.spec.tsxindex 778f6ec9235..069f08ecbdf 100644--- a/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.unit.spec.tsx+++ b/frontend/src/metabase/query_builder/components/view/QuestionRowCount/QuestionRowCount.unit.spec.tsx@@ -156,17 +156,109 @@ describe("QuestionRowCount", () => {expect(rowCount).toHaveTextContent("Showing 321 rows");});- it("allows setting a limit", async () => {+ it("renders the limit input and focuses it when selecting the custom option", async () => {+ await setup({ question: getCard() });++ await userEvent.click(await screen.findByLabelText("Row count"));++ // The input is always rendered, defaulting to the hard row limit+ const input = await screen.findByPlaceholderText("Pick a limit");+ expect(input).toHaveDisplayValue("2000");+ expect(input).not.toHaveFocus();++ await userEvent.click(+ await screen.findByRole("radio", { name: /Set custom limit/i }),+ );++ expect(input).toHaveFocus();+ });++ it("activates the custom option when focusing the input", async () => {+ await setup({ question: getCard() });++ await userEvent.click(await screen.findByLabelText("Row count"));++ const customRadio = await screen.findByRole("radio", {+ name: /Set custom limit/i,+ });+ expect(customRadio).not.toBeChecked();++ await userEvent.click(+ await screen.findByPlaceholderText("Pick a limit"),+ );++ expect(customRadio).toBeChecked();+ });++ it("allows setting a limit with Enter", async () => {const { rowCount } = await setup({ question: getCard() });await userEvent.click(rowCount);+ await userEvent.click(+ await screen.findByRole("radio", { name: /Set custom limit/i }),+ );const input = await screen.findByPlaceholderText("Pick a limit");fireEvent.change(input, { target: { value: "25" } });- fireEvent.keyPress(input, { key: "Enter", charCode: 13 });+ fireEvent.keyDown(input, { key: "Enter" });await waitFor(() => {expect(rowCount).toHaveTextContent("Show 25 rows");});+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("applies the typed value when the popover is dismissed (metabase#71276)", async () => {+ const { rowCount } = await setup({ question: getCard() });++ await userEvent.click(rowCount);+ await userEvent.click(+ await screen.findByRole("radio", { name: /Set custom limit/i }),+ );+ const input = await screen.findByPlaceholderText("Pick a limit");+ fireEvent.change(input, { target: { value: "25" } });++ // dismiss the popover without pressing Enter+ await userEvent.click(rowCount);++ await waitFor(() => {+ expect(rowCount).toHaveTextContent("Show 25 rows");+ });+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("discards the typed value when dismissed with Escape", async () => {+ const { rowCount } = await setup({ question: getCard() });++ await userEvent.click(rowCount);+ await userEvent.click(+ await screen.findByRole("radio", { name: /Set custom limit/i }),+ );+ const input = await screen.findByPlaceholderText("Pick a limit");+ fireEvent.change(input, { target: { value: "25" } });++ fireEvent.keyDown(input, { key: "Escape" });++ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ expect(rowCount).not.toHaveTextContent("Show 25 rows");+ });++ it("discards an updated value when dismissed with Escape", async () => {+ const { rowCount } = await setup({+ question: getCard({ dataset_query: getDatasetQueryWithLimit(25) }),+ });++ await userEvent.click(rowCount);+ const input = await screen.findByDisplayValue("25");+ fireEvent.change(input, { target: { value: "400" } });++ fireEvent.keyDown(input, { key: "Escape" });++ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ expect(rowCount).not.toHaveTextContent("Show 400 rows");});it("allows updating a limit", async () => {@@ -177,7 +269,7 @@ describe("QuestionRowCount", () => {await userEvent.click(rowCount);const input = await screen.findByDisplayValue("25");fireEvent.change(input, { target: { value: "400" } });- fireEvent.keyPress(input, { key: "Enter", charCode: 13 });+ fireEvent.keyDown(input, { key: "Enter" });await waitFor(() => {expect(rowCount).toHaveTextContent("Show 400 rows");@@ -193,6 +285,8 @@ describe("QuestionRowCount", () => {await userEvent.click(await screen.findByRole("radio", { name: /Show maximum/i }),);+ // the reset is committed when the popover is dismissed+ await userEvent.click(rowCount);await waitFor(() =>expect(rowCount).toHaveTextContent(@@ -201,6 +295,27 @@ describe("QuestionRowCount", () => {);});+ it("discards a reset to maximum when dismissed with Escape", async () => {+ const { rowCount } = await setup({+ question: getCard({ dataset_query: getDatasetQueryWithLimit(25) }),+ result: createMockDataset(),+ isResultDirty: true,+ });++ await userEvent.click(rowCount);+ const maximumRadio = await screen.findByRole("radio", {+ name: /Show maximum/i,+ });+ await userEvent.click(maximumRadio);+ fireEvent.keyDown(maximumRadio, { key: "Escape" });++ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ // the limit stays at 25 instead of being reset to the maximum+ expect(rowCount).toHaveTextContent("Show 25 rows");+ });+it("doesn't allow managing limit if query is read-only", async () => {const { rowCount } = await setup({question: getCard(),diff --git a/frontend/src/metabase/querying/components/LimitInput.tsx b/frontend/src/metabase/querying/components/LimitInput.tsxindex ffeefed88ac..db49d2981f1 100644--- a/frontend/src/metabase/querying/components/LimitInput.tsx+++ b/frontend/src/metabase/querying/components/LimitInput.tsx@@ -1,4 +1,5 @@import cx from "classnames";+import { forwardRef } from "react";import ButtonsS from "metabase/css/components/buttons.module.css";import CS from "metabase/css/core/index.css";@@ -12,20 +13,19 @@ interface LimitInputProps extends React.InputHTMLAttributes<HTMLInputElement> {medium?: boolean;}-export const LimitInput = ({- className,- small,- medium,- style = {},- ...props-}: LimitInputProps) => (- <input- className={cx(CS.input, className, CS.bgWhite, {- // HACK: reuse Button styles- [ButtonsS.ButtonSmall]: small,- [ButtonsS.ButtonMedium]: medium,- })}- style={{ ...DEFAULT_STYLE, ...style }}- {...props}- />+export const LimitInput = forwardRef<HTMLInputElement, LimitInputProps>(+ function LimitInput({ className, small, medium, style = {}, ...props }, ref) {+ return (+ <input+ ref={ref}+ className={cx(CS.input, className, CS.bgWhite, {+ // HACK: reuse Button styles+ [ButtonsS.ButtonSmall]: small,+ [ButtonsS.ButtonMedium]: medium,+ })}+ style={{ ...DEFAULT_STYLE, ...style }}+ {...props}+ />+ );+ },);